-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.ts
882 lines (725 loc) · 26.6 KB
/
main.ts
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
import { App, Editor, MarkdownView, Notice, Plugin, TFile, TFolder } from 'obsidian';
//settings
import { DEFAULT_SETTINGS, TickTickSyncSettings, TickTickSyncSettingTab } from './src/settings';
//TickTick api
import { TickTickRestAPI } from './src/TicktickRestAPI';
import { TickTickSyncAPI } from './src/TicktickSyncAPI';
//task parser
import { TaskParser } from './src/taskParser';
//cache task read and write
import { CacheOperation } from './src/cacheOperation';
//file operation
import { FileOperation } from './src/fileOperation';
//sync module
import { SyncMan } from './src/syncModule';
//import modals
import { SetDefaultProjectForFileModal } from 'src/modals/DefaultProjectModal';
import {LatestChangesModal} from "./src/modals/LatestChangesModal"
import { DateMan } from './src/dateMan';
export default class TickTickSync extends Plugin {
settings: TickTickSyncSettings;
tickTickRestAPI: TickTickRestAPI | undefined | null;
tickTickSyncAPI: TickTickSyncAPI | undefined;
taskParser: TaskParser | undefined;
dateMan : DateMan | undefined;
cacheOperation: CacheOperation | undefined;
fileOperation: FileOperation | undefined;
tickTickSync: SyncMan | undefined;
lastLines: Map<string, number>;
statusBar: any;
syncLock: Boolean;
async onload() {
//We're doing too much at load time, and it's causing issues. Do it properly!
this.app.workspace.onLayoutReady(() => {
this.registerEvent(this.app.vault.on('create', this.pluginLoad(), this));
});
}
private async pluginLoad() {
const isSettingsLoaded = await this.loadSettings();
if (!isSettingsLoaded) {
new Notice('Settings failed to load. Please reload the TickTickSync plugin.');
return;
}
//We're going to handle data structure conversions here.
if (!this.settings.version) {
const fileMetataDataStructure = this.settings.fileMetadata;
for (let file in fileMetataDataStructure) {
let oldTasksHolder = fileMetataDataStructure[file]; //an array of tasks.
let newTasksHolder = {};
newTasksHolder = {
TickTickTasks: oldTasksHolder.TickTickTasks.map((taskIDString) => ({
taskId: taskIDString, taskItems: []
})), TickTickCount: oldTasksHolder.TickTickCount, defaultProjectId: oldTasksHolder.defaultProjectId
};
fileMetataDataStructure[file] = newTasksHolder;
}
//Force a sync
if (this.settings && this.settings.apiInitialized) {
await this.scheduledSynchronization();
}
}
if ((!this.settings.version) || (this.isOlder(this.settings.version, '1.0.10'))) {
//get rid of user name and password. we don't need them no more.
delete this.settings.username;
delete this.settings.password;
}
//After this point, there's a need to document changes for the users.
let notableChanges: string [][] = [];
if ((!this.settings.version) || (this.isOlder(this.settings.version, '1.0.36'))) {
//default to AND because that's what we used to do:
this.settings.tagAndOr = 1;
//warn about tag changes.
notableChanges.push(['New Task Limiting rules', 'Please update your preferences in settings as needed.', 'priorTo1.0.36']);
}
if ((!this.settings.version) || (this.isOlder(this.settings.version, '1.0.40'))) {
//warn about the date/time foo
notableChanges.push(['New Date/Time Handling', 'Old date formats will be converted on the next synchronization operation.', 'priorTo1.0.40']);
}
if (notableChanges.length > 0) {
await this.LatestChangesModal(notableChanges);
}
//Update the version number. It will save me headaches later.
if ((!this.settings.version) || (this.isOlder(this.settings.version, this.manifest.version))) {
this.settings.version = this.manifest.version;
await this.saveSettings();
}
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new TickTickSyncSettingTab(this.app, this));
this.settings.apiInitialized = false;
try {
await this.initializePlugin();
} catch (Error) {
console.error('API Initialization Failed.');
}
//lastLine object {path:line} is saved in lastLines map
this.lastLines = new Map();
//Popular Request: Always on Sync Icon.
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('sync', 'TickTickSync', async (evt: MouseEvent) => {
// Called when the user clicks the icon.
await this.scheduledSynchronization();
await this.unlockSynclock();
new Notice(`Sync completed..`);
});
if (this.settings.debugMode) {
//Used for testing adhoc code.
// const ribbonIconEl1 = this.addRibbonIcon('check', 'TickTickSync', async (evt: MouseEvent) => {
// // Nothing to see here right now.
// });
}
//Key event monitoring, judging line breaks and deletions
this.registerDomEvent(document, 'keyup', async (evt: KeyboardEvent) => {
if (!this.settings.apiInitialized) {
return;
}
//console.log(`key pressed`)
const markDownView = this.app.workspace.getActiveViewOfType(MarkdownView);
const editor = markDownView?.app.workspace.activeEditor?.editor;
if ((!markDownView) || !(editor) || (editor) && !(editor.hasFocus())) {
// (console.log(`editor is not focused`))
return;
}
if (evt.key === 'ArrowUp' || evt.key === 'ArrowDown' || evt.key === 'ArrowLeft' || evt.key === 'ArrowRight' || evt.key === 'PageUp' || evt.key === 'PageDown') {
// console.log(`${evt.key} arrow key is released`);
if (!(this.checkModuleClass())) {
return;
}
await this.lineNumberCheck();
}
if (evt.key === 'Delete' || evt.key === 'Backspace') {
try {
//console.log(`${evt.key} key is released`);
if (!(this.checkModuleClass())) {
return;
}
if (!await this.checkAndHandleSyncLock()) return;
await this.tickTickSync?.deletedTaskCheck(null);
await this.unlockSynclock();
await this.saveSettings();
} catch (error) {
console.error(`An error occurred while deleting tasks: ${error}`);
await this.unlockSynclock();
}
}
});
//This is here to try and find nested checkboxes, which I put on hold for now.
function traverseDOMBackwards(element, callback) {
while (element) {
callback(element);
element = element.previousElementSibling;
}
}
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', async (evt: MouseEvent) => {
const { target } = evt;
const markDownView = this.app.workspace.getActiveViewOfType(MarkdownView);
const file = markDownView?.app.workspace.activeEditor?.file;
const fileName = file?.name;
const filepath = file?.path;
//Here for future debugging.
// traverseDOMBackwards(target, (element) => {
// console.log(element);
// });
if (!this.settings.apiInitialized) {
return;
}
if (!(this.checkModuleClass())) {
return;
}
if (this.app.workspace.activeEditor?.editor?.hasFocus()) {
await this.lineNumberCheck();
} else {
return;
}
//Here for future debugging.
// const target = evt.target as HTMLInputElement;
if (target && target.type === 'checkbox') {
await this.checkboxEventhandle(evt);
}
// // this.tickTickSync?.fullTextModifiedTaskCheck()
//
// }
});
//hook editor-change event, if the current line contains #ticktick, it means there is a new task
this.registerEvent(this.app.workspace.on('editor-change', async (editor, view: MarkdownView) => {
try {
if (!this.settings.apiInitialized) {
return;
}
if (!(this.checkModuleClass())) {
return;
}
await this.lineNumberCheck();
if (this.settings.enableFullVaultSync) {
return;
}
if (!await this.checkAndHandleSyncLock()) return;
await this.tickTickSync?.lineContentNewTaskCheck(editor, view);
await this.saveSettings();
await this.unlockSynclock();
} catch (error) {
console.error(`An error occurred while check new task in line: ${error.message}`);
await this.unlockSynclock();
}
}));
//Listen to the delete event
this.registerEvent(this.app.vault.on('delete', async (file) => {
if (file instanceof TFolder) {
//individual file deletes will be handled. I hope.
return;
}
if (!this.settings.apiInitialized) {
console.error('API Not intialized!');
return;
}
const fileMetadata = await this.cacheOperation?.getFileMetadata(file.path, null);
if (!fileMetadata || !fileMetadata.TickTickTasks) {
//console.log('There is no task in the deleted file')
return;
}
if (!(this.checkModuleClass())) {
return;
}
// @ts-ignore
await this.tickTickSync.deletedTaskCheck(file.path);
await this.cacheOperation?.deleteFilepathFromMetadata(file.path);
await this.saveSettings();
await this.unlockSynclock();
}));
//Listen to the rename event and update the path in task data
this.registerEvent(this.app.vault.on('rename', async (file, oldpath) => {
if (!this.settings.apiInitialized) {
console.error('API Not intialized!');
return;
}
// console.log(`${oldpath} is renamed`)
//Read fileMetadata
//const fileMetadata = await this.fileOperation.getFileMetadata(file)
const fileMetadata = await this.cacheOperation?.getFileMetadata(oldpath, null);
// console.log(fileMetadata)
if (!fileMetadata || !fileMetadata.TickTickTasks) {
//console.log('There is no task in the deleted file')
return;
}
if (!(this.checkModuleClass())) {
return;
}
await this.cacheOperation?.updateRenamedFilePath(oldpath, file.path);
await this.saveSettings();
//update task description
if (!await this.checkAndHandleSyncLock()) return;
try {
await this.tickTickSync?.updateTaskContent(file.path);
} catch (error) {
console.error('An error occurred in updateTaskDescription:', error);
}
await this.unlockSynclock();
}));
//Listen for file modified events and execute fullTextNewTaskCheck
this.registerEvent(this.app.vault.on('modify', async (file) => {
try {
if (!this.settings.apiInitialized) {
return;
}
const filepath = file.path;
// console.log(`${filepath} is modified`)
//get current view
const activateFile = this.app.workspace.getActiveFile();
// console.log(activateFile?.path, filepath)
//To avoid conflicts, Do not check files being edited
if (activateFile?.path == filepath) {
//TODO: find out if they cut or pasted task(s) in here.
return;
}
if (!await this.checkAndHandleSyncLock()) return;
// console.log("go check.")
await this.tickTickSync?.fullTextNewTaskCheck(filepath);
await this.unlockSynclock();
} catch (error) {
console.error(`An error occurred while modifying the file: ${error.message}`);
await this.unlockSynclock();
// You can add further error handling logic here. For example, you may want to
// revert certain operations, or alert the user about the error.
}
}));
this.registerInterval(window.setInterval(async () => await this.scheduledSynchronization(), this.settings.automaticSynchronizationInterval * 1000));
this.registerEvent(this.app.workspace.on('active-leaf-change', async (leaf) => {
await this.setStatusBarText();
}));
// set default project for TickTick task in the current file
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'set-default-project-for-TickTick-task-in-the-current-file',
name: 'Set default TickTick project for Tasks in the current file',
editorCallback: (editor: Editor, view: MarkdownView) => {
if (!view) {
return;
}
const filepath = view.file.path;
new SetDefaultProjectForFileModal(this.app, this, filepath);
}
});
//display default project for the current file on status bar
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
this.statusBar = this.addStatusBarItem();
console.log(`${this.manifest.name} ${this.manifest.version} loaded!`);
}
async onunload() {
console.log(`TickTickSync unloaded!`);
}
async loadSettings() {
try {
const data = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, data);
return true; // Returning true indicates that the settings are loaded successfully
} catch (error) {
console.error('Failed to load data:', error);
return false; // Returning false indicates that the setting loading failed
}
}
async saveSettings() {
try {
// Verify that the setting exists and is not empty
if (this.settings && Object.keys(this.settings).length > 0) {
await this.saveData(this.settings);
} else {
console.error('Settings are empty or invalid, not saving to avoid data loss.');
}
} catch (error) {
//Print or handle errors
console.error('Error saving settings:', error);
}
}
// return true of false
async initializePlugin() {
//initialize TickTick restapi
this.tickTickRestAPI = new TickTickRestAPI(this.app, this, null);
await this.tickTickRestAPI.initializeAPI();
//initialize data read and write object
this.cacheOperation = new CacheOperation(this.app, this);
let isProjectsSaved = false;
if (this.settings.apiInitialized) {
isProjectsSaved = await this.cacheOperation?.saveProjectsToCache();
}
if (!isProjectsSaved) {
this.tickTickRestAPI = undefined;
this.tickTickSyncAPI = undefined;
this.taskParser = undefined;
this.cacheOperation = undefined;
this.fileOperation = undefined;
this.tickTickSync = undefined;
this.dateMan = undefined;
new Notice(`TickTickSync plugin initialization failed, please check userID and password in settings.`);
return;
}
if (!this.settings.initialized) {
//Create a backup folder to back up TickTick data
try {
if (!this.settings.SyncTag) {
this.settings.SyncTag = '';
await this.saveSettings();
}
if (!this.settings.SyncProject) {
this.settings.SyncProject = '';
await this.saveSettings();
}
//Start the plug-in for the first time and back up TickTick data
//init task parser
this.taskParser = new TaskParser(this.app, this);
//init date manager
this.dateMan = new DateMan();
//initialize file operation
this.fileOperation = new FileOperation(this.app, this);
//initialize ticktick sync api
this.tickTickSyncAPI = new TickTickSyncAPI(this.app, this);
//initialize TickTick sync module
this.tickTickSync = new SyncMan(this.app, this);
// console.log('ticktick sync : ', this.tickTickSync) ;
//Back up all data before each startup
this.tickTickSync?.backupTickTickAllResources();
} catch (error) {
console.error(`error creating user data folder: ${error}`);
new Notice(`error creating user data folder`);
return;
}
//Initialize settings
this.settings.initialized = true;
await this.saveSettings();
new Notice(`TickTickSync initialization successful. TickTick data has been backed up.`);
}
await this.initializeModuleClass();
//get user plan resources
//const rsp = await this.TickTickSyncAPI.getUserResource()
// this.settings.apiInitialized = true
await this.unlockSynclock();
new Notice(`TickTickSync loaded successfully.`);
return true;
}
async initializeModuleClass() {
// console.log("initializeModuleClass")
//initialize TickTick restapi
if (!this.tickTickRestAPI) {
// console.log("API wasn't inited?")
this.tickTickRestAPI = new TickTickRestAPI(this.app, this, null);
}
//initialize data read and write object
this.cacheOperation = new CacheOperation(this.app, this);
//init taskparser
this.taskParser = new TaskParser(this.app, this);
//init date manager
this.dateMan = new DateMan();
//initialize file operation
this.fileOperation = new FileOperation(this.app, this);
//initialize TickTick sync api
this.tickTickSyncAPI = new TickTickSyncAPI(this.app, this);
//initialize TickTick sync module
this.tickTickSync = new SyncMan(this.app, this);
}
async lineNumberCheck() {
if (!await this.checkAndHandleSyncLock()) {
console.log("We're locked. Returning.");
return;
}
let modified = false;
const markDownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markDownView) {
const cursor = markDownView?.editor.getCursor();
const line = cursor?.line;
//const lineText = view.editor.getLine(line)
const fileContent = markDownView.data;
//console.log(line)
//const fileName = view.file?.name
const file = markDownView?.app.workspace.activeEditor?.file;
const fileName = file?.name;
const filepath = file?.path;
if (typeof this.lastLines === 'undefined' || typeof this.lastLines.get(fileName as string) === 'undefined') {
this.lastLines.set(fileName as string, line as number);
await this.unlockSynclock();
return false;
}
//console.log(`filename is ${fileName}`)
if (this.lastLines.has(fileName as string) && line !== this.lastLines.get(fileName as string)) {
const lastLine = this.lastLines.get(fileName as string);
// if (this.settings.debugMode) {
// console.log('Line changed!', `current line is ${line}`, `last line is ${lastLine}`);
// }
//Perform the operation you want
const lastLineText = markDownView.editor.getLine(lastLine as number);
// console.log(lastLineText)
if (!(this.checkModuleClass())) {
await this.unlockSynclock();
return false;
}
this.lastLines.set(fileName as string, line as number);
// try{
modified = await this.tickTickSync?.lineModifiedTaskCheck(filepath as string, lastLineText, lastLine as number, fileContent);
// }catch(error){
// console.error(`An error occurred while check modified task in line text: ${error}`);
// await this.unlockSynclock();
// }
} else {
//console.log('Line not changed');
}
}
await this.unlockSynclock();
return modified;
}
async checkboxEventhandle(evt: MouseEvent) {
const target = evt.target as HTMLInputElement;
const bOpenTask = target.checked;
new Notice(`Task will be updated as ${bOpenTask ? 'closed' : 'opened'} on next Sync`);
}
// async oldCheckboxEventhandle(evt: MouseEvent) {
// if (!(this.checkModuleClass())) {
// return;
// }
//
//
// const target = evt.target as HTMLInputElement;
// const bOpenTask = target.checked;
// console.log('Second: Checked: ', bOpenTask);
//
// //This breaks for subtasks if Tasks is installed. See: https://github.com/obsidian-tasks-group/obsidian-tasks/discussions/2685
// //hence the else.
// const taskElement = target.closest('div');
// if (taskElement) {
// const taskLine = taskElement.textContent;
// const taskId = this.taskParser?.getTickTickIdFromLineText(taskLine);
// if (taskId) {
// // let task = this.taskParser?.convertTextToTickTickTaskObject(tas)
// if (bOpenTask) {
// console.log('it\'s open, close it.');
// this.tickTickSync?.closeTask(taskId);
// } else {
// console.log('it\'s closed, open it.');
// this.tickTickSync?.reopenTask(taskId);
// }
// }
// } else {
// console.log('#### TickTick_id not found -- do it the hard way.');
// //Start full-text search and check status updates
// try {
// console.log('#### Full text modified??');
// let file = this.app.workspace.getActiveFile();
// let filePath = null;
// if (file instanceof TFile) {
// filePath = file.path;
// }
//
// if (!await this.checkAndHandleSyncLock()) return;
// await this.tickTickSync?.fullTextModifiedTaskCheck(filePath);
// await this.unlockSynclock();
// } catch (error) {
// console.error(`An error occurred while check modified tasks in the file: ${error}`);
// await this.unlockSynclock();
//
// }
// }
// }
//return true
checkModuleClass() {
if (this.settings.apiInitialized === true) {
if (this.tickTickRestAPI === undefined || this.tickTickSyncAPI === undefined || this.cacheOperation === undefined || this.fileOperation === undefined || this.tickTickSync === undefined || this.taskParser === undefined) {
this.initializeModuleClass();
}
return true;
} else {
new Notice(`Please login from settings.`);
return (false);
}
}
async setStatusBarText() {
if (!(this.checkModuleClass())) {
return;
}
const markDownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!markDownView) {
this.statusBar.setText('');
} else {
const filepath = markDownView?.file?.path;
if (filepath === undefined) {
// console.log(`file path undefined`)
return;
}
const defaultProjectName = await this.cacheOperation?.getDefaultProjectNameForFilepath(filepath as string);
if (defaultProjectName === undefined) {
// console.log(`projectName undefined`)
return;
}
this.statusBar.setText(defaultProjectName);
}
}
async scheduledSynchronization() {
if (!(this.checkModuleClass())) {
return;
}
console.log('TickTick scheduled synchronization task started at', new Date().toLocaleString());
try {
if (!await this.checkAndHandleSyncLock()) {
console.error('TickTick scheduled synchronization task terminated for sync loc at', new Date().toLocaleString());
return;
}
try {
let bChanged = await this.tickTickSync?.syncTickTickToObsidian();
if (bChanged) {
//the file system is farckled. Wait until next sync to avoid race conditions.
await this.unlockSynclock();
console.log('TickTick scheduled synchronization task completed at', new Date().toLocaleString());
return;
}
} catch (error) {
console.error('An error occurred in syncTickTickToObsidian:', error);
console.error('TickTick terminated synchronization task at', new Date().toLocaleString());
await this.unlockSynclock();
return;
}
await this.unlockSynclock();
try {
await this.saveSettings();
} catch (error) {
console.error('An error occurred in saveSettings:', error);
}
const filesToSync = this.settings.fileMetadata;
let newFilesToSync = filesToSync;
//If one project is to be synced, don't look at it's other files.
if (this.settings.SyncProject) {
newFilesToSync = Object.fromEntries(Object.entries(filesToSync).filter(([key, value]) =>
value.defaultProjectId == this.settings.SyncProject));
}
//Check for duplicates before we do anything
try {
const result = this.cacheOperation?.checkForDuplicates(newFilesToSync);
if (result?.duplicates && (JSON.stringify(result.duplicates) != "{}")) {
let dupText = '';
for (let duplicatesKey in result.duplicates) {
dupText += "Task: " + duplicatesKey + '\nin files: \n';
result.duplicates[duplicatesKey].forEach(file => {
dupText += file + "\n"
})
}
const msg =
"Found duplicates in MetaData.\n\n" +
`${dupText}` +
"\nPlease fix manually. This causes unpredictable results" +
"\nPlease open an issue in the TickTickSync repository if you continue to see this issue." +
"\n\nTo prevent data corruption. Sync is aborted."
console.log("Metadata Duplicates: ", result.duplicates);
new Notice(msg, 0);
return;
}
const duplicateTasksInFiles = await this.fileOperation?.checkForDuplicates(filesToSync, result?.taskIds)
if (duplicateTasksInFiles && (JSON.stringify(duplicateTasksInFiles) != "{}")) {
let dupText = ""
for (let duplicateTasksInFilesKey in duplicateTasksInFiles) {
dupText += "Task: " + duplicateTasksInFilesKey + "\nFound in Files: \n"
duplicateTasksInFiles[duplicateTasksInFilesKey].forEach(file => {
dupText += file + "\n"
})
}
const msg =
"Found duplicates in Files.\n\n" +
`${dupText}` +
"\nPlease fix manually. This causes unpredictable results" +
"\nPlease open an issue in the TickTickSync repository if you continue to see this issue." +
"\n\nTo prevent data corruption. Sync is aborted."
new Notice(msg, 0)
return;
}
} catch (Error) {
console.error(Error)
new Notice(`Duplicate check failed: ${Error}`, 0)
return
}
//let's see if any files got killed while we weren't watching
for (const fileKey in newFilesToSync) {
const file = this.app.vault.getAbstractFileByPath(fileKey);
if (!file) {
console.log("File ", fileKey, " was deleted before last sync.");
await this.cacheOperation?.deleteFilepathFromMetadata(fileKey);
delete newFilesToSync[fileKey]
}
}
// console.time("TIMING File Check");
//Now do the task checking.
for (const fileKey in newFilesToSync) {
if (this.settings.debugMode) {
console.log(fileKey);
}
if (!await this.checkAndHandleSyncLock()) return;
try {
await this.tickTickSync?.fullTextNewTaskCheck(fileKey);
} catch (error) {
console.error('An error occurred in fullTextNewTaskCheck:', error);
}
await this.unlockSynclock();
if (!await this.checkAndHandleSyncLock()) return;
try {
await this.tickTickSync?.fullTextModifiedTaskCheck(fileKey);
} catch (error) {
console.error('An error occurred in fullTextModifiedTaskCheck:', error);
}
await this.unlockSynclock();
if (!await this.checkAndHandleSyncLock()) return;
try {
await this.tickTickSync?.deletedTaskCheck(fileKey);
} catch (error) {
console.error('An error occurred in deletedTaskCheck:', error);
}
await this.unlockSynclock();
}
// console.timeEnd("TIMING File Check");
} catch (error) {
console.error('An error occurred:', error);
new Notice('An error occurred:', error);
await this.unlockSynclock();
}
console.log('TickTick scheduled synchronization task completed at', new Date().toLocaleString());
}
async checkSyncLock() {
let checkCount = 0;
while (this.settings.syncLock && checkCount < 10) {
await new Promise(resolve => setTimeout(resolve, 1000));
checkCount++;
}
return !this.settings.syncLock;
}
async unlockSynclock() {
this.settings.syncLock = false;
await this.saveSettings();
}
async checkAndHandleSyncLock() {
if (this.settings.syncLock) {
// console.log('sync locked.');
const isSyncLockChecked = await this.checkSyncLock();
if (!isSyncLockChecked) {
return false;
}
// console.log('sync unlocked.')
}
this.settings.syncLock = true;
await this.saveSettings();
return true;
}
private isOlder(version1: string, version2: string) {
const v1 = version1.split('.');
const v2 = version2.split('.');
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
const num1 = parseInt(v1[i] || 0);
const num2 = parseInt(v2[i] || 0);
if (num1 < num2) {
return true;
} else if (num1 > num2) {
return false;
}
}
return false;
}
private async LatestChangesModal(notableChanges: string[][]) {
const myModal = new LatestChangesModal(this.app, notableChanges, (result) => {
this.ret = result;
});
const bConfirmation = await myModal.showModal();
return bConfirmation;
}
}