-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathwebdav-sync.js
More file actions
1836 lines (1628 loc) · 73.7 KB
/
Copy pathwebdav-sync.js
File metadata and controls
1836 lines (1628 loc) · 73.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const WEBDAV_SYNC_FILES = [
{ key: 'config', fileName: 'config.json' },
{ key: 'statistics', fileName: 'statistics.json' },
{ key: 'recap', fileName: 'recap.json' }
];
const WEBDAV_SYNC_CONFIG_KEY = 'webdav-sync';
const WEBDAV_SYNC_ENABLED_DEFAULT = true;
const WEBDAV_AUTO_SYNC_READY_KEY = 'webdav-sync.autoSyncReady';
const WEBDAV_UNSYNCED_EXIT_MARKER_KEY = 'webdav-sync-unsynced-exit';
const WEBDAV_CREDENTIAL_SERVICE = 'wnr.webdav-sync';
const WEBDAV_EXCLUDED_CONFIG_KEYS = ['webdav-sync', 'version', 'previous-language', 'just-back', 'just-launched', 'just-relaunched', 'settings-goto', WEBDAV_UNSYNCED_EXIT_MARKER_KEY];
const WEBDAV_REQUEST_TIMEOUT_MS = 8000;
const WEBDAV_SYNC_LOG_FILE = 'webdav-sync.log';
const WEBDAV_SYNC_INTENT_PRIORITY = {
manualPull: 1,
manualPush: 2,
beforeQuitFlush: 3,
startupPull: 4,
autoPush: 5
};
function cloneStoreData(data) {
return JSON.parse(JSON.stringify(data || {}));
}
function createWebDavError(userMessage, detail) {
const error = new Error(userMessage);
error.userMessage = userMessage;
error.detail = detail || '';
return error;
}
function toWebDavErrorPayload(error, fallbackMessage) {
const message = (error && (error.userMessage || error.message)) || fallbackMessage;
const detail = (error && error.detail) || '';
return {
ok: false,
message: message,
detail: detail
};
}
function delay(ms) {
return new Promise(function (resolve) {
setTimeout(resolve, ms);
});
}
function getWebDavFailureDetailOperationClass(source) {
switch (source) {
case 'startupPull':
return 'startupPull';
case 'manualPull':
return 'pull';
case 'autoPush':
case 'manualPush':
case 'beforeQuitFlush':
return 'push';
case 'testConnection':
default:
return null;
}
}
function getWebDavFailureResolutionClasses(failureClass) {
switch (failureClass) {
case 'startupPull':
return ['pull'];
case 'pull':
return ['pull'];
case 'push':
return ['push'];
default:
return [];
}
}
function getLatestWebDavFailureDetailFromStatus(syncStatus) {
let entries = Object.values(syncStatus || {}).filter(Boolean);
if (entries.length === 0) return '';
let latestFailuresByClass = new Map();
let latestSuccessOrdersByClass = new Map();
entries.forEach(function (entry) {
let operationClass = getWebDavFailureDetailOperationClass(entry.source);
if (entry.status === 'failed') {
if (operationClass == null) return;
let currentLatestFailure = latestFailuresByClass.get(operationClass);
if (currentLatestFailure == null || (entry.order || 0) > (currentLatestFailure.order || 0)) {
latestFailuresByClass.set(operationClass, entry);
}
}
if (entry.status === 'success') {
if (operationClass == null) return;
let currentLatestSuccessOrder = latestSuccessOrdersByClass.get(operationClass) || 0;
latestSuccessOrdersByClass.set(operationClass, Math.max(currentLatestSuccessOrder, entry.order || 0));
}
});
let remainingFailures = [];
latestFailuresByClass.forEach(function (entry, failureClass) {
let resolutionClasses = getWebDavFailureResolutionClasses(failureClass);
let latestResolutionOrder = 0;
resolutionClasses.forEach(function (resolutionClass) {
latestResolutionOrder = Math.max(latestResolutionOrder, latestSuccessOrdersByClass.get(resolutionClass) || 0);
});
if ((entry.order || 0) > latestResolutionOrder) remainingFailures.push(entry);
});
if (remainingFailures.length === 0) return '';
remainingFailures.sort(function (a, b) {
return (b.order || 0) - (a.order || 0);
});
return remainingFailures[0].detail || '';
}
function buildSyncConfigPayloadFromStore(store) {
let configSnapshot = cloneStoreData(store.store);
for (let i = 0; i < WEBDAV_EXCLUDED_CONFIG_KEYS.length; i++) {
delete configSnapshot[WEBDAV_EXCLUDED_CONFIG_KEYS[i]];
}
return configSnapshot;
}
function applyFullStoreData(targetStore, snapshot) {
targetStore.clear();
targetStore.set(snapshot);
}
function applyRemoteWebDavPayloadsToStores(stores, fetchedPayloads) {
let store = stores.store;
let statistics = stores.statistics;
let recapStore = stores.recapStore;
let currentConfig = cloneStoreData(store.store);
let currentStatistics = cloneStoreData(statistics.store);
let currentRecap = cloneStoreData(recapStore.store);
let localWebDavConfig = cloneStoreData(store.get(WEBDAV_SYNC_CONFIG_KEY, {}));
try {
let configPayload = cloneStoreData(fetchedPayloads.config);
configPayload[WEBDAV_SYNC_CONFIG_KEY] = localWebDavConfig;
applyFullStoreData(store, configPayload);
applyFullStoreData(statistics, fetchedPayloads.statistics);
applyFullStoreData(recapStore, fetchedPayloads.recap);
} catch (e) {
applyFullStoreData(store, currentConfig);
applyFullStoreData(statistics, currentStatistics);
applyFullStoreData(recapStore, currentRecap);
throw e;
}
}
function createWebDavSyncService(deps) {
const {
app,
fs,
path,
fetch,
ipcMain,
i18n,
keytar,
notifyWarning,
getStore,
getStatisticsStore,
getRecapStore,
showExitDialog,
hideExitDialog
} = deps;
let webDavWatchersStarted = false;
let webDavAutoPushTimer = null;
let lastSyncedCoreSignature = null;
let webDavSyncStatus = {
startupPull: null,
lastPull: null,
lastPush: null,
lastTest: null
};
let webDavSyncStatusOrder = 0;
let webDavSyncSuppressionTokens = new Map();
let webDavCoordinator = null;
let webDavStartupMutationSuppressionToken = null;
let exitAuthority = null;
let ipcHandlersRegistered = false;
let cachedWebDavPassword = '';
let cachedWebDavCredentialError = '';
function getStores() {
return {
store: getStore(),
statistics: getStatisticsStore(),
recapStore: getRecapStore()
};
}
function getStoreOrNull() {
return getStores().store;
}
function getStoredWebDavConfigSnapshot() {
let store = getStoreOrNull();
let config = cloneStoreData(store != null ? store.get(WEBDAV_SYNC_CONFIG_KEY, {}) : {});
return {
url: String(config.url || '').trim(),
username: String(config.username || ''),
remotePath: String(config.remotePath || '').trim(),
enabled: config.enabled !== false
};
}
function normalizeWebDavRemotePath(remotePath) {
let normalized = String(remotePath || '').trim().replace(/\\/g, '/');
normalized = normalized.replace(/\/+/g, '/');
normalized = normalized.replace(/^\/+|\/+$/g, '');
return normalized;
}
function buildWebDavCredentialAccount(config) {
let username = String(config.username || '').trim();
let remotePath = normalizeWebDavRemotePath(config.remotePath);
try {
let parsed = new URL(String(config.url || '').trim());
let hostname = parsed.hostname.toLowerCase();
let port = parsed.port;
let protocol = parsed.protocol.toLowerCase();
if (port === '443' && protocol === 'https:') port = '';
let hostWithPort = port ? `${ hostname }:${ port }` : hostname;
return `${ username }@${ hostWithPort }:${ remotePath }`;
} catch (e) {
return `${ username }@${ String(config.url || '').trim() }:${ remotePath }`;
}
}
async function getCredentialPassword(config) {
if (keytar == null) return '';
return await keytar.getPassword(WEBDAV_CREDENTIAL_SERVICE, buildWebDavCredentialAccount(config)) || '';
}
async function setCredentialPassword(config, password) {
if (keytar == null) throw new Error('keytar unavailable');
await keytar.setPassword(WEBDAV_CREDENTIAL_SERVICE, buildWebDavCredentialAccount(config), String(password || ''));
}
async function deleteCredentialPassword(config) {
if (keytar == null) return false;
return await keytar.deletePassword(WEBDAV_CREDENTIAL_SERVICE, buildWebDavCredentialAccount(config));
}
async function refreshCachedWebDavPassword(configOverride) {
let config = configOverride || getStoredWebDavConfigSnapshot();
try {
cachedWebDavPassword = await getCredentialPassword(config);
cachedWebDavCredentialError = '';
} catch (e) {
cachedWebDavPassword = '';
cachedWebDavCredentialError = e && e.message ? e.message : String(e);
}
return cachedWebDavPassword;
}
async function migrateLegacyWebDavPasswordIfNeeded(configOverride) {
let store = getStoreOrNull();
if (store == null || !store.has('webdav-sync.password')) return false;
let legacyPassword = String(store.get('webdav-sync.password') || '');
if (legacyPassword === '') {
store.delete('webdav-sync.password');
return false;
}
let config = configOverride || getStoredWebDavConfigSnapshot();
await setCredentialPassword(config, legacyPassword);
store.delete('webdav-sync.password');
cachedWebDavPassword = legacyPassword;
cachedWebDavCredentialError = '';
return true;
}
async function persistNonSensitiveWebDavConfig(nextConfig) {
let store = getStoreOrNull();
if (store == null) return getStoredWebDavConfigSnapshot();
let currentConfig = cloneStoreData(store.get(WEBDAV_SYNC_CONFIG_KEY, {}));
let mergedConfig = Object.assign({}, currentConfig, {
url: String(nextConfig.url || '').trim(),
username: String(nextConfig.username || ''),
remotePath: String(nextConfig.remotePath || '').trim()
});
if (mergedConfig.url === '' || mergedConfig.username === '' || mergedConfig.remotePath === '') {
mergedConfig.enabled = false;
}
delete mergedConfig.password;
store.set(WEBDAV_SYNC_CONFIG_KEY, mergedConfig);
store.delete('webdav-sync.password');
setWebDavAutoSyncReady(false, 'settings-updated');
await refreshCachedWebDavPassword(mergedConfig);
return getStoredWebDavConfigSnapshot();
}
async function setWebDavPassword(password) {
let normalizedPassword = String(password || '');
let config = getStoredWebDavConfigSnapshot();
await setCredentialPassword(config, normalizedPassword);
let store = getStoreOrNull();
if (store != null && store.has('webdav-sync.password')) store.delete('webdav-sync.password');
cachedWebDavPassword = normalizedPassword;
cachedWebDavCredentialError = '';
setWebDavAutoSyncReady(false, 'password-updated');
return {
hasPassword: normalizedPassword !== ''
};
}
async function clearWebDavPassword() {
let config = getStoredWebDavConfigSnapshot();
await deleteCredentialPassword(config);
let store = getStoreOrNull();
if (store != null) {
if (store.has('webdav-sync.password')) store.delete('webdav-sync.password');
let currentConfig = cloneStoreData(store.get(WEBDAV_SYNC_CONFIG_KEY, {}));
currentConfig.enabled = false;
store.set(WEBDAV_SYNC_CONFIG_KEY, currentConfig);
}
cachedWebDavPassword = '';
cachedWebDavCredentialError = '';
setWebDavAutoSyncReady(false, 'password-cleared');
return {
hasPassword: false
};
}
async function getWebDavConfigUiState() {
let config = getStoredWebDavConfigSnapshot();
await refreshCachedWebDavPassword(config);
let isConfigured = String(config.url || '').trim() !== ''
&& String(config.username || '').trim() !== ''
&& cachedWebDavPassword !== ''
&& String(config.remotePath || '').trim() !== '';
return Object.assign({}, config, {
enabled: config.enabled === true && isConfigured,
hasPassword: cachedWebDavPassword !== '',
password: cachedWebDavPassword
});
}
function appendWebDavSyncLog(event, detail) {
try {
const logPath = path.join(app.getPath('userData'), WEBDAV_SYNC_LOG_FILE);
const line = `[${ new Date().toISOString() }] ${ event }${ detail ? ' | ' + detail : '' }\n`;
fs.appendFileSync(logPath, line, 'utf8');
} catch (e) {
console.log(e);
}
}
function setWebDavSyncStatus(key, status, message, detail, source) {
webDavSyncStatus[key] = {
status: status,
message: message,
detail: detail || '',
source: source || key,
updatedAt: new Date().toISOString(),
order: ++webDavSyncStatusOrder
};
}
function getWebDavSyncStatus() {
return Object.assign(cloneStoreData(webDavSyncStatus), {
configured: isWebDavConfigured(),
enabled: isWebDavSyncEnabled(),
latestFailureDetail: getLatestWebDavFailureDetailFromStatus(webDavSyncStatus),
autoReady: isWebDavAutoSyncReady(),
suppressed: isWebDavAutoSyncSuppressed(),
coordinatorBusy: webDavCoordinator != null && webDavCoordinator.currentOperation != null,
remoteWriteFrozen: webDavCoordinator != null && webDavCoordinator.remoteWriteFrozen === true,
remoteWriteFreezeReason: webDavCoordinator != null ? webDavCoordinator.remoteWriteFreezeReason : null
});
}
function getWebDavSyncConfig() {
let config = getStoredWebDavConfigSnapshot();
return {
url: config.url,
username: config.username,
password: cachedWebDavPassword,
remotePath: config.remotePath
};
}
function isWebDavSyncEnabled() {
return getStoredWebDavConfigSnapshot().enabled === true && isWebDavConfigured();
}
function isWebDavConfigured() {
let config = getWebDavSyncConfig();
return config.url !== '' && config.username !== '' && config.password !== '' && config.remotePath !== '';
}
function isWebDavAutoSyncReady() {
let store = getStoreOrNull();
return store != null && store.get(WEBDAV_AUTO_SYNC_READY_KEY) === true;
}
function setWebDavAutoSyncReady(ready, reason) {
let store = getStoreOrNull();
if (store == null) return;
let normalizedReady = ready === true;
if (store.get(WEBDAV_AUTO_SYNC_READY_KEY) === normalizedReady) return;
store.set(WEBDAV_AUTO_SYNC_READY_KEY, normalizedReady);
appendWebDavSyncLog('auto-sync-ready', `${ normalizedReady ? 'enabled' : 'disabled' }${ reason ? ' | ' + reason : '' }`);
}
function setWebDavSyncEnabled(enabled, reason) {
let store = getStoreOrNull();
if (store == null) {
return Object.assign(getStoredWebDavConfigSnapshot(), {
hasPassword: cachedWebDavPassword !== ''
});
}
let currentConfig = cloneStoreData(store.get(WEBDAV_SYNC_CONFIG_KEY, {}));
let normalizedEnabled = enabled === true;
if (normalizedEnabled && !isWebDavConfigured()) normalizedEnabled = false;
currentConfig.enabled = normalizedEnabled;
store.set(WEBDAV_SYNC_CONFIG_KEY, currentConfig);
if (!normalizedEnabled) {
if (webDavAutoPushTimer) {
clearTimeout(webDavAutoPushTimer);
webDavAutoPushTimer = null;
}
clearQueuedAutoPushes('disabled-by-user');
}
appendWebDavSyncLog('auto-sync-toggle', `${ normalizedEnabled ? 'enabled' : 'disabled' }${ reason ? ' | ' + reason : '' }`);
return Object.assign(getStoredWebDavConfigSnapshot(), {
hasPassword: cachedWebDavPassword !== ''
});
}
function getSyncPayloadMap() {
let stores = getStores();
return {
config: buildSyncConfigPayloadFromStore(stores.store),
statistics: cloneStoreData(stores.statistics.store),
recap: cloneStoreData(stores.recapStore.store)
};
}
function computeCoreSyncSignature() {
return JSON.stringify(getSyncPayloadMap());
}
function createWebDavSyncSuppressionToken(scope, reason, operationId) {
let tokenId = `${ scope || 'unknown' }-${ Date.now() }-${ Math.random().toString(16).slice(2) }`;
webDavSyncSuppressionTokens.set(tokenId, {
scope: scope || 'unknown',
reason: reason || '',
operationId: operationId || null,
startedAt: new Date().toISOString()
});
appendWebDavSyncLog('sync-suppression-start', `${ tokenId } [${ scope || 'unknown' }]${ reason ? ' ' + reason : '' }`);
return tokenId;
}
function isWebDavAutoSyncSuppressed() {
return webDavSyncSuppressionTokens.size > 0;
}
function releaseWebDavSyncSuppressionToken(tokenId) {
if (!webDavSyncSuppressionTokens.has(tokenId)) return;
let token = webDavSyncSuppressionTokens.get(tokenId);
webDavSyncSuppressionTokens.delete(tokenId);
appendWebDavSyncLog('sync-suppression-end', `${ tokenId } [${ token.scope }]`);
}
async function runWithWebDavSyncSuppressed(fn, scope, reason, operationId) {
let tokenId = createWebDavSyncSuppressionToken(scope, reason, operationId);
try {
return await fn();
} finally {
releaseWebDavSyncSuppressionToken(tokenId);
}
}
function getWebDavSyncTestOptions() {
return {
enabled: process.env.WEBDAV_SYNC_TEST_MODE === '1',
uploadDelayMs: Math.max(0, Number(process.env.WEBDAV_SYNC_TEST_UPLOAD_DELAY_MS || 0)),
watcherDelayMs: Math.max(0, Number(process.env.WEBDAV_SYNC_TEST_WATCHER_DELAY_MS || 0)),
quitDrainTimeoutMs: Math.max(1000, Number(process.env.WEBDAV_SYNC_TEST_QUIT_DRAIN_TIMEOUT_MS || 5000)),
failUpload: process.env.WEBDAV_SYNC_TEST_FAIL_UPLOAD === '1',
failDownload: process.env.WEBDAV_SYNC_TEST_FAIL_DOWNLOAD === '1'
};
}
async function runWebDavSyncTestHook(name, context) {
let options = getWebDavSyncTestOptions();
if (!options.enabled) return;
if (name === 'before-upload-complete') {
if (options.uploadDelayMs > 0) {
appendWebDavSyncLog('test-hook-upload-delay', `${ options.uploadDelayMs }ms`);
await delay(options.uploadDelayMs);
}
if (options.failUpload) {
throw createWebDavError(i18n.__('webdav-sync-upload-failed'), 'forced upload failure in test mode');
}
}
if (name === 'before-download-apply' && options.failDownload) {
throw createWebDavError(i18n.__('webdav-sync-download-failed'), 'forced download failure in test mode');
}
if (name === 'watcher-delay' && options.watcherDelayMs > 0) {
appendWebDavSyncLog('test-hook-watcher-delay', `${ options.watcherDelayMs }ms${ context ? ' [' + context + ']' : '' }`);
await delay(options.watcherDelayMs);
}
}
function ensureWebDavSyncCoordinator() {
if (webDavCoordinator != null) return webDavCoordinator;
webDavCoordinator = {
queue: [],
isRunning: false,
currentOperation: null,
pendingAutoPushOperation: null,
nextOperationId: 1,
nextUploadTaskId: 1,
stateVersion: 0,
lastObservedSignature: null,
remoteWriteFrozen: false,
remoteWriteFreezeReason: null,
remoteWriteFrozenByOperationId: null,
remoteWriteFrozenAt: null
};
return webDavCoordinator;
}
function isWebDavRemoteWriteIntent(type) {
return type === 'autoPush' || type === 'manualPush' || type === 'beforeQuitFlush';
}
function freezeWebDavRemoteWriteLane(reason, operationId) {
let coordinator = ensureWebDavSyncCoordinator();
coordinator.remoteWriteFrozen = true;
coordinator.remoteWriteFreezeReason = reason || 'unknown';
coordinator.remoteWriteFrozenByOperationId = operationId || null;
coordinator.remoteWriteFrozenAt = new Date().toISOString();
appendWebDavSyncLog('freeze-enter', `${ coordinator.remoteWriteFreezeReason }${ operationId ? ' | op=' + operationId : '' }`);
}
function unfreezeWebDavRemoteWriteLane(reason, operationId) {
let coordinator = ensureWebDavSyncCoordinator();
if (!coordinator.remoteWriteFrozen) return;
appendWebDavSyncLog('freeze-exit', `${ reason || 'manual-push' }${ operationId ? ' | op=' + operationId : '' }`);
coordinator.remoteWriteFrozen = false;
coordinator.remoteWriteFreezeReason = null;
coordinator.remoteWriteFrozenByOperationId = null;
coordinator.remoteWriteFrozenAt = null;
}
function isWebDavWriteLaneFrozen() {
let coordinator = ensureWebDavSyncCoordinator();
return coordinator.remoteWriteFrozen === true;
}
function canOperationBypassWebDavWriteFreeze(operation) {
if (!isWebDavRemoteWriteIntent(operation.type)) return true;
return operation.type === 'manualPush' && operation.options.explicitUserAction === true;
}
function logWebDavWriteBlocked(operation, reason) {
appendWebDavSyncLog('write-blocked', `${ operation.type }#${ operation.operationId } | ${ reason || 'remote-write-frozen' }`);
}
function synchronizeWebDavObservedState(reason) {
let coordinator = ensureWebDavSyncCoordinator();
coordinator.lastObservedSignature = computeCoreSyncSignature();
coordinator.stateVersion += 1;
appendWebDavSyncLog('sync-state-synchronized', `${ reason || 'unknown' } | v${ coordinator.stateVersion }`);
return {
signature: coordinator.lastObservedSignature,
stateVersion: coordinator.stateVersion
};
}
function observeWebDavLocalState(reason) {
let coordinator = ensureWebDavSyncCoordinator();
let signature = computeCoreSyncSignature();
if (coordinator.lastObservedSignature !== signature) {
coordinator.lastObservedSignature = signature;
coordinator.stateVersion += 1;
appendWebDavSyncLog('sync-state-observed', `${ reason || 'unknown' } | v${ coordinator.stateVersion }`);
}
return {
signature: signature,
stateVersion: coordinator.stateVersion
};
}
function createWebDavCoordinatorOperation(type, options) {
let coordinator = ensureWebDavSyncCoordinator();
let operation = {
type: type,
priority: WEBDAV_SYNC_INTENT_PRIORITY[type] || 99,
options: Object.assign({}, options),
operationId: coordinator.nextOperationId++,
enqueuedAt: Date.now()
};
operation.promise = new Promise(function (resolve, reject) {
operation.resolve = resolve;
operation.reject = reject;
});
return operation;
}
function sortWebDavCoordinatorQueue() {
let coordinator = ensureWebDavSyncCoordinator();
coordinator.queue.sort(function (a, b) {
if (a.priority !== b.priority) return a.priority - b.priority;
return a.operationId - b.operationId;
});
}
function clearQueuedAutoPushes(reason) {
let coordinator = ensureWebDavSyncCoordinator();
if (coordinator.pendingAutoPushOperation != null) {
coordinator.pendingAutoPushOperation.resolve({
ok: true,
skipped: true,
message: i18n.__('webdav-sync-auto-idle'),
reason: reason || 'cleared'
});
}
coordinator.queue = coordinator.queue.filter(function (operation) {
return operation.type !== 'autoPush';
});
coordinator.pendingAutoPushOperation = null;
}
function cancelPendingWebDavOverwriteConfirm() {
let coordinator = ensureWebDavSyncCoordinator();
if (!coordinator.remoteWriteFrozen || coordinator.remoteWriteFreezeReason !== 'awaitingManualOverwriteConfirm') return;
unfreezeWebDavRemoteWriteLane('manual-overwrite-confirm-cancelled', coordinator.remoteWriteFrozenByOperationId);
}
function resolvePendingWebDavOverwriteConfirm(reason) {
let coordinator = ensureWebDavSyncCoordinator();
if (!coordinator.remoteWriteFrozen || coordinator.remoteWriteFreezeReason !== 'awaitingManualOverwriteConfirm') return;
unfreezeWebDavRemoteWriteLane(reason || 'manual-overwrite-confirm-resolved', coordinator.remoteWriteFrozenByOperationId);
}
function queueWebDavCoordinatorOperation(type, options) {
let coordinator = ensureWebDavSyncCoordinator();
let operation = createWebDavCoordinatorOperation(type, options);
coordinator.queue.push(operation);
sortWebDavCoordinatorQueue();
processWebDavCoordinatorQueue();
return operation.promise;
}
function requestWebDavIntent(type, options) {
let coordinator = ensureWebDavSyncCoordinator();
let intentOptions = Object.assign({}, options);
if (type === 'manualPush' && intentOptions.explicitUserAction === true && coordinator.remoteWriteFrozen) {
unfreezeWebDavRemoteWriteLane('explicit-manual-push', coordinator.currentOperation != null ? coordinator.currentOperation.operationId : null);
}
if (type === 'autoPush') {
if (!isWebDavSyncEnabled()) {
appendWebDavSyncLog('auto-push-skip', `disabled-by-user [${ intentOptions.reason || 'unknown' }]`);
return Promise.resolve({
ok: true,
skipped: true,
disabledByUser: true,
message: i18n.__('webdav-sync-user-disabled')
});
}
if (!isWebDavAutoSyncReady()) {
appendWebDavSyncLog('auto-push-skip', `initial-sync-required [${ intentOptions.reason || 'unknown' }]`);
return Promise.resolve({
ok: true,
skipped: true,
autoSyncNotReady: true,
message: i18n.__('webdav-sync-auto-awaiting-initial-sync')
});
}
if (!intentOptions.ignoreSuppression && isWebDavAutoSyncSuppressed()) {
appendWebDavSyncLog('auto-push-skip', `suppressed [${ intentOptions.reason || 'unknown' }]`);
return Promise.resolve({
ok: true,
skipped: true,
message: i18n.__('webdav-sync-auto-idle')
});
}
let observed = observeWebDavLocalState(`auto-push:${ intentOptions.reason || 'unknown' }`);
if (observed.signature === lastSyncedCoreSignature) {
appendWebDavSyncLog('auto-push-skip', `already-synced [${ intentOptions.reason || 'unknown' }]`);
return Promise.resolve({
ok: true,
skipped: true,
message: i18n.__('webdav-sync-upload-ok')
});
}
if (coordinator.pendingAutoPushOperation != null) {
let pending = coordinator.pendingAutoPushOperation;
let reasons = pending.options.reasons || [];
if (intentOptions.reason && !reasons.includes(intentOptions.reason)) reasons.push(intentOptions.reason);
pending.options.reasons = reasons;
pending.options.ignoreSuppression = pending.options.ignoreSuppression || intentOptions.ignoreSuppression === true;
return pending.promise;
}
intentOptions.reasons = intentOptions.reason ? [intentOptions.reason] : [];
let operation = createWebDavCoordinatorOperation(type, intentOptions);
coordinator.pendingAutoPushOperation = operation;
coordinator.queue.push(operation);
sortWebDavCoordinatorQueue();
processWebDavCoordinatorQueue();
return operation.promise;
}
if (type === 'startupPull' && !isWebDavSyncEnabled()) {
appendWebDavSyncLog('startup-sync-skip', 'disabled-by-user');
return Promise.resolve({
ok: true,
skipped: true,
disabledByUser: true,
message: i18n.__('webdav-sync-user-disabled')
});
}
if (type === 'beforeQuitFlush' && !isWebDavSyncEnabled()) {
appendWebDavSyncLog('quit-flush-skip', `disabled-by-user [${ intentOptions.reason || 'unknown' }]`);
return Promise.resolve({
ok: true,
skipped: true,
disabledByUser: true,
message: i18n.__('webdav-sync-user-disabled')
});
}
if (type === 'beforeQuitFlush' && !isWebDavAutoSyncReady()) {
appendWebDavSyncLog('quit-flush-blocked', `initial-sync-required [${ intentOptions.reason || 'unknown' }]`);
return Promise.resolve({
ok: false,
autoSyncNotReady: true,
blockedByInitialSync: true,
message: i18n.__('webdav-sync-auto-awaiting-initial-sync'),
detail: i18n.__('webdav-sync-auto-awaiting-initial-sync')
});
}
if (type === 'beforeQuitFlush' && coordinator.remoteWriteFrozen) {
appendWebDavSyncLog('quit-flush-skipped-due-to-freeze', coordinator.remoteWriteFreezeReason || 'awaiting-confirmation');
return Promise.resolve({
ok: true,
skipped: true,
blockedByFreeze: true,
message: i18n.__('webdav-sync-auto-idle')
});
}
if (type === 'manualPush' || type === 'beforeQuitFlush') {
observeWebDavLocalState(`${ type }:${ intentOptions.reason || 'manual' }`);
}
return queueWebDavCoordinatorOperation(type, intentOptions);
}
function requestWebDavIntentInBackground(type, options) {
requestWebDavIntent(type, options).catch(function (e) {
console.log(e);
appendWebDavSyncLog('sync-intent-background-failed', `${ type } | ${ e.detail || e.message || '' }`);
});
}
function ensureExitAuthority() {
if (exitAuthority != null) return exitAuthority;
exitAuthority = {
active: false,
finalizing: false,
sessionId: 0,
dialogState: null,
source: null,
interactive: false,
relaunch: false,
mayMutateLocal: true,
mutationApplied: false,
beforeExitMutation: null,
beforeFinalizeCallbacks: [],
pendingDecisionResolver: null,
promise: null
};
return exitAuthority;
}
function clearWebDavUnsyncedExitMarker() {
try {
let store = getStoreOrNull();
if (store != null && store.has(WEBDAV_UNSYNCED_EXIT_MARKER_KEY)) {
store.delete(WEBDAV_UNSYNCED_EXIT_MARKER_KEY);
}
} catch (e) {
console.log(e);
}
}
function setWebDavUnsyncedExitMarker(source, reason) {
try {
let store = getStoreOrNull();
if (store == null) return;
store.set(WEBDAV_UNSYNCED_EXIT_MARKER_KEY, {
source: source || 'unknown',
reason: reason || 'unknown',
timestamp: new Date().toISOString()
});
} catch (e) {
console.log(e);
}
}
function applyGuardedExitRequiredCleanup() {
try {
let store = getStoreOrNull();
if (store != null) store.set('just-back', false);
} catch (e) {
console.log(e);
}
}
function resetExitAuthority(authority) {
authority.active = false;
authority.finalizing = false;
authority.source = null;
authority.interactive = false;
authority.relaunch = false;
authority.dialogState = null;
authority.mayMutateLocal = true;
authority.mutationApplied = false;
authority.beforeExitMutation = null;
authority.beforeFinalizeCallbacks = [];
authority.pendingDecisionResolver = null;
authority.promise = null;
}
function getExitSyncDialogPayload(authority, state, detail) {
let payload = {
dialogKind: 'exit-sync',
exitSessionId: authority.sessionId,
state: state,
title: i18n.__('webdav-sync-exit-timeout-title'),
msg: i18n.__('webdav-sync-exit-timeout-message'),
detail: detail || '',
interactive: false,
primaryLabel: '',
secondaryLabel: '',
tertiaryLabel: ''
};
if (state === 'syncing') {
payload.title = i18n.__('webdav-sync-exit-syncing-title');
payload.msg = i18n.__('webdav-sync-exit-syncing-message');
} else if (state === 'initial-sync-choice') {
payload.title = i18n.__('webdav-sync-exit-initial-choice-title');
payload.msg = i18n.__('webdav-sync-exit-initial-choice-message');
payload.interactive = true;
payload.primaryLabel = i18n.__('webdav-sync-exit-upload-local');
payload.secondaryLabel = i18n.__('webdav-sync-exit-download-cloud');
payload.tertiaryLabel = i18n.__('cancel');
} else if (state === 'timeout') {
payload.interactive = true;
payload.primaryLabel = i18n.__('webdav-sync-exit-wait');
payload.secondaryLabel = i18n.__('webdav-sync-exit-force-quit');
} else if (state === 'failed') {
payload.title = i18n.__('webdav-sync-exit-failed-title');
payload.msg = i18n.__('webdav-sync-exit-failed-message');
payload.interactive = true;
payload.primaryLabel = i18n.__('webdav-sync-exit-retry');
payload.secondaryLabel = i18n.__('webdav-sync-exit-force-quit');
}
return payload;
}
function requestExitSyncDialogDecision(authority, state, detail) {
authority.dialogState = state;
appendWebDavSyncLog('exit-ui-state', `${ state } | session=${ authority.sessionId }`);
let shown = showExitDialog(getExitSyncDialogPayload(authority, state, detail));
if (!shown) {
appendWebDavSyncLog('exit-ui-fallback-unavailable', `${ state } | session=${ authority.sessionId }`);
return Promise.resolve('force-quit');
}
return new Promise(function (resolve) {
authority.pendingDecisionResolver = resolve;
});
}
async function runExitSyncAttempt(source) {
appendWebDavSyncLog('exit-sync-attempt', source || 'unknown');
if (!isWebDavConfigured() || !isWebDavSyncEnabled()) {
clearWebDavUnsyncedExitMarker();
appendWebDavSyncLog('exit-sync-success', `${ source || 'unknown' } | ${ !isWebDavConfigured() ? 'webdav-not-configured' : 'disabled-by-user' }`);
return { ok: true, skipped: true };
}
if (webDavAutoPushTimer) {
clearTimeout(webDavAutoPushTimer);
webDavAutoPushTimer = null;
appendWebDavSyncLog('before-quit-flush-cancel-pending-timer');
}
if (computeCoreSyncSignature() === lastSyncedCoreSignature) {
clearWebDavUnsyncedExitMarker();
appendWebDavSyncLog('exit-sync-success', `${ source || 'unknown' } | already-synced`);
return { ok: true, skipped: true };
}
let timeoutMs = getWebDavSyncTestOptions().quitDrainTimeoutMs;
try {
let result = await Promise.race([
requestWebDavIntent('beforeQuitFlush', {
reason: source || 'exit-guard',
ignoreSuppression: true
}),
delay(timeoutMs).then(function () {
return { ok: false, timeout: true, reason: 'timeout' };
})
]);
if (result && result.blockedByFreeze) {
appendWebDavSyncLog('exit-sync-timeout', `${ source || 'unknown' } | blocked-by-freeze`);
return { ok: false, blockedByFreeze: true, reason: 'blocked-by-freeze' };
}
if (result && result.blockedByInitialSync) {
appendWebDavSyncLog('exit-sync-initial-sync-choice-required', `${ source || 'unknown' }`);
return {
ok: false,
requiresInitialSyncChoice: true,
reason: 'initial-sync-choice',
detail: result.detail || result.message || ''
};
}
if (result && result.timeout) {
appendWebDavSyncLog('exit-sync-timeout', `${ source || 'unknown' } | timeout`);
return result;
}
if (result && result.ok === false) {
appendWebDavSyncLog('exit-sync-failed', `${ source || 'unknown' } | ${ result.detail || result.message || 'failed' }`);
return { ok: false, failed: true, reason: 'failed', detail: result.detail || result.message || '' };
}
clearWebDavUnsyncedExitMarker();
appendWebDavSyncLog('exit-sync-success', source || 'unknown');
return { ok: true };
} catch (e) {
appendWebDavSyncLog('exit-sync-failed', `${ source || 'unknown' } | ${ e.detail || e.message || 'error' }`);
return { ok: false, failed: true, reason: 'failed', detail: e.detail || e.message || '' };
}
}
async function finalizeExitAuthority(authority, reason) {
if (authority.finalizing) return { finalized: true };
authority.finalizing = true;
appendWebDavSyncLog('exit-authority-finalize', `${ authority.source || 'unknown' }${ reason ? ' | ' + reason : '' }`);
hideExitDialog();
applyGuardedExitRequiredCleanup();
authority.beforeFinalizeCallbacks.forEach(function (fn) {
try {
fn();
} catch (e) {
console.log(e);
}
});
if (authority.relaunch) app.relaunch();
app.exit(0);
return { finalized: true };
}
async function runExitAuthorityFlow(authority) {
appendWebDavSyncLog('exit-guard-begin', authority.source || 'unknown');
if (authority.beforeExitMutation != null && !authority.mutationApplied) {
await authority.beforeExitMutation();
authority.mutationApplied = true;
}