-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.ts
2431 lines (2304 loc) · 67 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
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
import {
App,
Modal,
Notice,
Plugin,
PluginSettingTab,
setIcon,
Setting,
TAbstractFile,
TFile,
FileSystemAdapter,
} from "obsidian";
import axios from "axios";
import ShortUniqueId from "short-unique-id";
import {
deleteFile,
getFile,
getFileInfo,
getFilesList,
getFoldersList,
getVaultId,
modifyFile,
renameFile,
uploadFile,
uploadFolder,
} from "./actions";
const PENDING_SYNC_FILE_NAME = "pendingSync-gdrive-plugin";
const ERROR_LOG_FILE_NAME = "error-log-gdrive-plugin.md";
const VERBOSE_LOG_FILE_NAME = "verbose-log-gdrive-plugin.md";
const ATTACHMENT_TRACKING_FOLDER_NAME =
".attachment-tracking-obsidian-gdrive-sync";
const ignoreFiles = [
PENDING_SYNC_FILE_NAME,
ERROR_LOG_FILE_NAME,
VERBOSE_LOG_FILE_NAME,
];
/* helper functions */
function objectToMap(obj: Record<string, string>) {
const map: Map<string, string> = new Map();
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
map.set(key, obj[key]);
}
}
return map;
}
function mapToObject(map: Map<string, string>) {
let obj: Record<string, string> = {};
for (const [key, value] of map.entries()) {
obj[key] = value;
}
return obj;
}
function bufferEqual(a: ArrayBuffer, b: ArrayBuffer) {
let c: Uint8Array = new Uint8Array(a, 0);
let d: Uint8Array = new Uint8Array(b, 0);
if (a.byteLength != b.byteLength) return false;
return equal8(c, d);
}
function equal8(a: Uint8Array, b: Uint8Array) {
const ua = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
const ub = new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
return compare(ua, ub);
}
function compare(a: Uint8Array, b: Uint8Array) {
for (let i = a.length; -1 < i; i -= 1) {
if (a[i] !== b[i]) return false;
}
return true;
}
const getAccessToken = async (
refreshToken: string,
showError: boolean = false
) => {
var response;
await axios
.post(
"https://red-formula-303406.ue.r.appspot.com/auth/obsidian/refresh-token",
{
refreshToken,
}
)
.then((res) => {
response = res.data;
})
.catch((err) => {
if ((err.code = "ERR_NETWORK") && showError) {
new Notice("Oops! Network error :(");
new Notice("Or maybe no refresh token provided?", 5000);
response = "network_error";
} else {
response = "error";
}
});
return response;
};
const { randomUUID } = new ShortUniqueId({ length: 6 });
interface driveValues {
refreshToken: string;
accessToken: string;
accessTokenExpiryTime: string;
validToken: Boolean;
vaultId: any;
vaultInit: boolean;
filesList: any[];
rootFolderId: any;
refresh: boolean;
refreshTime: string;
autoRefreshBinaryFiles: string;
errorLoggingToFile: boolean;
verboseLoggingToFile: boolean;
blacklistPaths: string[];
//writingFile: boolean;
//syncQueue: boolean;
}
const DEFAULT_SETTINGS: driveValues = {
refreshToken: "",
accessToken: "",
accessTokenExpiryTime: "",
validToken: false,
vaultId: "",
filesList: [],
vaultInit: false,
rootFolderId: "",
refresh: false,
refreshTime: "5",
autoRefreshBinaryFiles: "1",
errorLoggingToFile: false,
verboseLoggingToFile: false,
blacklistPaths: [],
//writingFile: false,
//syncQueue: false,
};
const metaPattern = /^---\n[\s\S]*---/;
const driveDataPattern = /\nlastSync:.*\n/;
interface pendingSyncItemInterface {
fileID?: string;
action: "UPLOAD" | "MODIFY" | "RENAME" | "DELETE";
timeStamp: string;
newFileName?: string;
isBinaryFile?: boolean;
}
export default class driveSyncPlugin extends Plugin {
settings: driveValues;
cloudFiles: string[] = [];
localFiles: string[] = [];
timer: any = null;
alreadyRefreshing: boolean = false;
writingFile: boolean = false;
syncQueue: string[] = [];
isUploadingCurrentFile: boolean = false;
latestContentThatWasSynced: ArrayBuffer | null = null;
currentlyUploading: string | null = null; // to mitigate the issue of deleting recently created file while its being uploaded and gets overlaped with the auto-trash function call
renamingList: string[] = [];
deletingList: string[] = [];
statusBarItem = this.addStatusBarItem().createEl("span", "sync_icon_still");
pendingSync: boolean = false;
connectedToInternet: boolean = false;
checkingForConnectivity: boolean = false;
pendingSyncItems: Array<pendingSyncItemInterface> = [];
renamedWhileOffline: Map<string, string> = new Map();
finalNamesForFileID: Map<string, string> = new Map();
completingPendingSync: boolean = false;
verboseLoggingForTheFirstTimeInThisSession: boolean = true;
errorLoggingForTheFirstTimeInThisSession: boolean = true;
lastErrorTime: Date = new Date(0);
totalErrorsWithinAMinute: number = 0;
haltAllOperations: boolean = false;
adapter: FileSystemAdapter;
attachmentTrackingInitializationComplete: boolean = false;
layoutReady: boolean = false;
completeAllPendingSyncs = async () => {
if (!this.app.workspace.layoutReady) {
// Workspace is still loading, do nothing
return;
}
if (this.haltAllOperations) {
return;
}
if (this.completingPendingSync) {
return;
}
/* files created when offline are assigned a dummy fileId
so the following Map keeps track of the dummy fielId to the actual fileId
which is retrieved when the file is uploadedf for the first time when online */
await this.writeToVerboseLogFile(
"LOG: Entering completeAllPendingSyncs"
);
let uuidToFileIdMap = new Map();
let pendingSyncFile = this.app.vault.getAbstractFileByPath(
PENDING_SYNC_FILE_NAME
);
pendingSyncFile instanceof TFile
? console.log(
JSON.parse(await this.app.vault.read(pendingSyncFile))
)
: console.log("No file");
let {
pendingSyncItems,
finalNamesForFileID,
}: {
pendingSyncItems: Array<pendingSyncItemInterface>;
finalNamesForFileID: Record<string, string>;
} =
pendingSyncFile instanceof TFile
? JSON.parse(await this.app.vault.read(pendingSyncFile))
: { pendingSyncItems: [], finalNamesForFileID: new Map() };
this.pendingSyncItems = [...pendingSyncItems];
this.finalNamesForFileID = objectToMap(finalNamesForFileID);
let finalNamesForFileIDMap = objectToMap(finalNamesForFileID);
console.log(pendingSyncItems, finalNamesForFileID);
if (pendingSyncItems.length) {
new Notice(
"ATTENTION: Syncing all pending changes since app was last online!"
);
new Notice(
"Please wait till the sync is complete before proceeding with anything else..."
);
}
try {
this.settings.filesList = await getFilesList(
this.settings.accessToken,
this.settings.vaultId
); // to get the last modifiedTimes
this.completingPendingSync = true;
for (var item of pendingSyncItems) {
let lastCloudUpdateTime = new Date(0);
let pendingSyncTime = new Date(item.timeStamp);
this.settings.filesList.forEach((file) => {
if (file.id == item.fileID) {
lastCloudUpdateTime = new Date(file.modifiedTime!);
}
});
switch (item.action) {
case "DELETE":
if (lastCloudUpdateTime < pendingSyncTime) {
await deleteFile(
this.settings.accessToken,
uuidToFileIdMap.get(item.fileID)
? uuidToFileIdMap.get(item.fileID)
: item.fileID
);
}
await this.writeToVerboseLogFile(
"LOG: Deleted file. [PS]"
);
break;
case "UPLOAD":
var fileName = finalNamesForFileIDMap.get(item.fileID!);
var file = this.app.vault.getAbstractFileByPath(
fileName!
);
let actualId;
if (file instanceof TFile) {
if (item.isBinaryFile) {
actualId = await this.uploadNewAttachment(file);
} else {
actualId = await this.uploadNewNotesFile(file);
}
}
uuidToFileIdMap.set(item.fileID, actualId);
finalNamesForFileIDMap.set(actualId, fileName!);
this.finalNamesForFileID.set(actualId, fileName!);
await this.writeToVerboseLogFile(
"LOG: Uploaded file. [PS]"
);
break;
case "MODIFY":
if (pendingSyncTime > lastCloudUpdateTime) {
let file = this.app.vault.getAbstractFileByPath(
finalNamesForFileIDMap.get(item.fileID!)!
);
if (file instanceof TFile) {
await this.updateLastSyncMetaTag(file);
var buffer = await this.app.vault.readBinary(
file
);
await modifyFile(
this.settings.accessToken,
uuidToFileIdMap.get(item.fileID)
? uuidToFileIdMap.get(item.fileID)
: item.fileID,
buffer
);
}
await this.writeToVerboseLogFile(
"LOG: Modified file. [PS]"
);
}
break;
case "RENAME":
if (pendingSyncTime > lastCloudUpdateTime) {
await renameFile(
this.settings.accessToken,
uuidToFileIdMap.get(item.fileID)
? uuidToFileIdMap.get(item.fileID)
: item.fileID,
finalNamesForFileIDMap.get(item.fileID!)
);
}
await this.writeToVerboseLogFile(
"LOG: Renamed file. [PS]"
);
break;
}
this.pendingSyncItems.shift();
await this.writeToPendingSyncFile();
new Notice(
`Synced ${pendingSyncItems.indexOf(item) + 1}/${
pendingSyncItems.length
} changes`
);
await this.writeToVerboseLogFile(
"LOG: completeAllPendingSyncs: Finished one operation"
);
}
} catch (err) {
if (err.message.includes("404")) {
this.pendingSyncItems.shift();
await this.writeToPendingSyncFile();
}
this.completingPendingSync = false;
await this.notifyError();
await this.checkForConnectivity();
await this.writeToErrorLogFile(err);
}
if (pendingSyncItems.length) {
new Notice("Sync complete!");
this.finalNamesForFileID.clear();
await this.writeToPendingSyncFile();
await this.writeToVerboseLogFile(
"LOG: completeAllPendingSyncs: Finished allpendingSyncs"
);
}
this.completingPendingSync = false;
this.pendingSync = false;
await this.refreshAll();
await this.writeToVerboseLogFile("LOG: Exited completeAllPendingSyncs");
};
checkForConnectivity = async () => {
if (this.haltAllOperations) {
return;
}
try {
await this.writeToVerboseLogFile(
"LOG: Entering checkForConnectivity"
);
await fetch("https://www.github.com/stravo1", {
mode: "no-cors",
});
if (!this.connectedToInternet) {
new Notice("Connectivity re-established!");
this.connectedToInternet = true;
this.checkingForConnectivity = false;
}
await this.completeAllPendingSyncs();
} catch (err) {
console.log("Checking for connectivity again after 5sec...");
if (this.connectedToInternet) {
console.log("error: " + err); // (currently fetch failed)
new Notice("Connection lost :(");
this.connectedToInternet = false;
await this.writeToErrorLogFile(err);
}
setTimeout(() => {
this.checkingForConnectivity = true;
this.checkForConnectivity();
}, 5000);
}
await this.writeToVerboseLogFile("LOG: Exited checkForConnectivity");
};
notifyError = async () => {
if (!this.app.workspace.layoutReady || !this.layoutReady) {
// Workspace is still loading, do nothing
return;
}
if (this.haltAllOperations) {
return;
}
if (!this.pendingSync) {
this.pendingSync = true;
new Notice("ERROR: Something went wrong! Sync might be paused!");
}
await this.writeToVerboseLogFile("LOG: Error occured");
// check if the time between this error and last error was less than a minute:
if (new Date().getTime() - this.lastErrorTime.getTime() < 60000) {
this.totalErrorsWithinAMinute++;
} else {
this.totalErrorsWithinAMinute = 0;
}
if (this.totalErrorsWithinAMinute > 5) {
this.haltAllOperations = true;
setTimeout(async () => {
await this.writeToErrorLogFile(
new Error("FATAL ERROR: Too many errors within a minute.")
);
await this.writeToVerboseLogFile(
"LOG: Too many errors within a minute. Halting all operations."
);
new Notice(
"FATAL ERROR: Too many errors within a minute. Please reload the plug-in. If error persists, check the Verbose and Error Logs (turn them on in plug-in settings).",
5000
);
new Notice(
"Report issue by attaching the log files at https://github.com/stravo1/obsidian-gdrive-sync/issues/new",
5000
);
}, 1500);
}
this.lastErrorTime = new Date();
};
cleanInstall = async () => {
if (this.haltAllOperations) {
return;
}
try {
await this.writeToVerboseLogFile("LOG: Enerting cleanInstall");
if (!this.settings.rootFolderId) {
await this.writeToErrorLogFile(
new Error("ERROR: Root folder does not exist")
);
new Notice(
"ERROR: Root folder does not exist. Please reload the plug-in."
);
new Notice(
"If this error persists, please check if there is a folder named 'obsidian' in your Google Drive."
);
new Notice(
"If there is one and you are still getting this error, consider joining the Discord server for help.",
3000
);
new Notice(
"If there is no folder named 'obsidian' in your Drive root, try using the 'Create root folder' button in Settings.",
4000
);
return;
}
new Notice("Creating vault in Google Drive...");
var res = await uploadFolder(
this.settings.accessToken,
this.app.vault.getName(),
this.settings.rootFolderId
);
this.settings.vaultId = res;
new Notice("Vault created!");
new Notice(
"Uploading files, this might take time. Please wait...",
6000
);
var filesList = this.app.vault.getFiles();
let noOfFiles = filesList.length;
let count = 0;
for (const file of filesList) {
const buffer: any = await this.app.vault.readBinary(file);
await uploadFile(
this.settings.accessToken,
file.path,
buffer,
this.settings.vaultId
);
count++;
new Notice("Uploaded " + count + "/" + noOfFiles + " files");
}
new Notice("Files uploaded!");
new Notice("Please reload the plug-in.", 5000);
} catch (err) {
new Notice("ERROR: Unable to initialize Vault in Google Drive");
await this.checkForConnectivity();
await this.writeToErrorLogFile(err);
}
await this.writeToVerboseLogFile("LOG: Exited cleanInstall");
};
refreshAll = async () => {
if (!this.app.workspace.layoutReady || !this.layoutReady) {
// Workspace is still loading, do nothing
return;
}
if (this.haltAllOperations) {
return;
}
await this.writeToVerboseLogFile("LOG: Entering refreshAll");
try {
if (!this.connectedToInternet) {
console.log("ERROR: Connectivity lost, not refreshing...");
return;
}
if (
new Date(this.settings.accessTokenExpiryTime).getTime() -
new Date().getTime() <
1800000
// half hour
) {
await this.writeToVerboseLogFile(
"LOG: Token will expire in 30mins, getting new token..."
);
var res: any = await getAccessToken(
this.settings.refreshToken,
false
);
if (res == "error") {
new Notice("ERROR: Couldn't fetch new accessToken :(");
await this.writeToErrorLogFile(
new Error("ERROR: Couldn't fetch new accessToken")
);
return;
}
this.settings.accessToken = res.access_token;
this.settings.accessTokenExpiryTime = res.expiry_date;
this.saveSettings();
}
if (this.pendingSync) {
console.log("PAUSED: Writing pending syncs, not refreshing...");
if (!this.checkingForConnectivity) {
setTimeout(() => {
this.checkForConnectivity();
}, 5000);
}
return;
}
if (this.alreadyRefreshing) {
return;
} else {
this.alreadyRefreshing = true;
}
await this.refreshFilesListInDriveAndStoreInSettings();
/* refresh both the files list */
this.cloudFiles = [];
this.localFiles = [];
this.settings.filesList.map((file) =>
this.cloudFiles.push(file.name)
);
this.app.vault
.getFiles()
.map((file) => this.localFiles.push(file.path));
var toDownload = this.cloudFiles.filter(
(file) =>
!this.localFiles.includes(file) && // is not currently in vault
!this.renamingList.includes(file) && // is not currently being renamed
!this.deletingList.includes(file) && // is not currently being deleted
!this.isInBlacklist(file) // is not in blacklist
);
await this.writeToVerboseLogFile(
"LOG: Deleting files in refreshAll"
);
/* delete tracked but not-in-drive-anymore files */
this.app.vault.getFiles().map(async (file) => {
if (
!this.cloudFiles.includes(file.path) &&
!this.renamingList.includes(file.path) &&
!this.deletingList.includes(file.path) &&
file.path != this.currentlyUploading
) {
if (file.extension != "md") {
if (await this.isAttachmentSynced(file.path)) {
this.app.vault.trash(file, false);
let convertedSafeFilename = file.path.replace(
/\//g,
"."
);
try {
await this.adapter.remove(
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${convertedSafeFilename}`
);
} catch (err) {
await this.writeToErrorLogFile(err);
await this.writeToVerboseLogFile(
"LOG: Could not delete " +
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${convertedSafeFilename}`
);
}
return;
}
}
var content = await this.app.vault.read(file);
if (driveDataPattern.test(content)) {
this.app.vault.trash(file, false);
}
}
});
await this.writeToVerboseLogFile(
"LOG: Downloading missing files in refreshAll"
);
/* download new files or files that were renamed */
if (toDownload.length) {
new Notice("Downloading missing files", 2500);
this.settings.refresh = true;
for (const dFile of toDownload) {
var id;
this.settings.filesList.map((file: any) => {
//console.log(file.name);
if (file.name == dFile) {
id = file.id;
}
});
//console.log(id, dFile);
var file = await getFile(this.settings.accessToken, id);
let isBinary =
file[0].split(".")[file[0].split(".").length - 1] !=
"md";
try {
await this.app.vault.createBinary(file[0], file[1]);
if (isBinary) {
let safeFilename = file[0].replace(/\//g, ".");
try {
await this.app.vault.create(
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${safeFilename}`,
""
);
} catch (err) {
await this.writeToVerboseLogFile(
`LOG: ${ATTACHMENT_TRACKING_FOLDER_NAME}/${safeFilename} could not be created`
);
await this.writeToErrorLogFile(err);
}
}
} catch (err) {
await this.writeToVerboseLogFile(
"LOG: Couldn't create file directly, trying to create folder first..."
);
var path = file[0].split("/").slice(0, -1).join("/");
// console.log(path);
try {
await this.app.vault.createFolder(path);
} catch (err) {
if (err.message.includes("Folder already exists")) {
await this.writeToVerboseLogFile(
"LOG: Caught: Folder exists"
);
}
}
try {
await this.app.vault.createBinary(file[0], file[1]);
} catch (err) {
await this.writeToVerboseLogFile(
"LOG: Couldn't create file and folder, details of path, file[0]: " +
path +
", " +
file[0]
);
await this.writeToErrorLogFile(err);
await this.notifyError();
}
}
new Notice(
`Downloaded ${toDownload.indexOf(dFile) + 1}/${
toDownload.length
} files`,
1000
);
}
new Notice("Download complete :)", 2500);
// new Notice(
// "Sorry to make you wait for so long. Please continue with your work",
// 5000
// );
this.settings.refresh = false;
}
if (!this.attachmentTrackingInitializationComplete) {
console.log("Initializing attachment tracking...");
for (const file of this.cloudFiles) {
if (file.slice(-3) == ".md") {
continue;
}
console.log("Trying to attachment tracking file: " + file);
let convertedSafeFilename = file.replace(/\//g, ".");
try {
await this.app.vault.create(
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${convertedSafeFilename}`,
""
);
} catch (err) {
if (err.message.includes("exist")) {
await this.writeToVerboseLogFile(
"LOG: Already tracked: " + file
);
} else {
await this.writeToErrorLogFile(err);
await this.writeToVerboseLogFile(
"LOG: Could not create " +
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${convertedSafeFilename}`
);
}
}
}
this.attachmentTrackingInitializationComplete = true;
}
this.getLatestContent(this.app.workspace.getActiveFile()!);
this.alreadyRefreshing = false;
//console.log("refreshing filelist...");
} catch (err) {
this.notifyError();
this.checkForConnectivity();
await this.writeToErrorLogFile(err);
this.alreadyRefreshing = false;
}
await this.writeToVerboseLogFile("LOG: Exited refreshAll");
};
uploadNewNotesFile = async (newFile: TFile) => {
if (this.haltAllOperations) {
return;
}
if (this.isInBlacklist(newFile)) {
new Notice(
"File in blacklist. It will be uploaded but not be synced/tracked automatically by the plugin."
);
}
try {
await this.writeToVerboseLogFile(
"LOG: Entering uploadNewNotesFile"
);
if (!this.connectedToInternet) {
console.log("ERROR: Connectivity lost, not uploading...");
return;
}
if (
newFile.extension != "md" ||
newFile.path == this.currentlyUploading
)
return; // skip binary files or the file which is already being uploaded
this.writingFile = true;
this.currentlyUploading = newFile.path;
new Notice("Uploading new file to Google Drive!");
var content = await this.app.vault.read(newFile);
var metaExists = metaPattern.test(content);
var driveDataExists = driveDataPattern.test(content);
if (!metaExists) {
await this.app.vault.modify(
newFile,
`---\nlastSync: ${new Date().toString()}\n---\n` + content
);
} else if (!driveDataExists) {
await this.app.vault.modify(
newFile,
content.replace(
/^---\n/g,
`---\nlastSync: ${new Date().toString()}\n`
)
);
}
var buffer: any = await this.app.vault.readBinary(newFile);
var id = await uploadFile(
this.settings.accessToken,
newFile.path,
buffer,
this.settings.vaultId
);
this.writingFile = false;
this.cloudFiles.push(newFile.path);
await this.refreshFilesListInDriveAndStoreInSettings();
this.currentlyUploading = null;
new Notice("Uploaded!");
await this.writeToVerboseLogFile("LOG: Exited uploadNewNotesFile");
return id;
} catch (err) {
await this.notifyError();
await this.checkForConnectivity();
await this.writeToErrorLogFile(err);
this.writingFile = false;
this.currentlyUploading = null;
await this.writeToVerboseLogFile("LOG: Exited uploadNewNotesFile");
}
};
getLatestContent = async (
file: TFile,
forced: "forced" | false = false
) => {
if (!this.app.workspace.layoutReady || !this.layoutReady) {
// Workspace is still loading, do nothing
return;
}
try {
if (this.haltAllOperations) {
return;
}
await this.writeToVerboseLogFile("LOG: Entering getLatestContent");
if (!this.connectedToInternet) {
console.log(
"ERROR: Connectivity lost, not fetching latest content..."
);
return;
}
if (
this.cloudFiles.includes(file?.path!) &&
!this.syncQueue.length
) {
var index = this.cloudFiles.indexOf(file?.path!);
var cloudDate = new Date(
this.settings.filesList[index].modifiedTime
);
var content: string;
var timeStamp: any;
var isBinaryFile: boolean = false;
if (file.extension != "md") {
isBinaryFile = true;
timeStamp = [file.stat.mtime];
} else {
content = await this.app.vault.cachedRead(file!);
timeStamp = content.match(/lastSync:.*/);
}
//console.log(cloudDate, new Date(timeStamp![0]));
if (
forced == "forced" ||
(timeStamp /* check if timeStamp is present */ &&
cloudDate.getTime() >
new Date(timeStamp![0]).getTime() +
(isBinaryFile
? 5000
: 3000)) /* allow 3sec/5sec (needs to be tested) delay in 'localDate' */
) {
if (
isBinaryFile &&
!parseInt(this.settings.autoRefreshBinaryFiles)
) {
return;
}
// new Notice("Downloading updated file!");
var id;
this.settings.filesList.map((fileItem: any) => {
if (fileItem.name == file.path) {
id = fileItem.id;
}
});
var res = await getFile(this.settings.accessToken, id);
// console.log("here", this.writingFile, res);
if (
this.syncQueue.length ||
// isBinaryFile ||
this.writingFile
)
return;
//console.log(this.syncQueue);
this.latestContentThatWasSynced = res[1];
await this.app.vault
.modifyBinary(file, res[1])
.catch(async () => {
var path = res[0].split("/").slice(0, -1).join("/");
//console.log(path);
await this.app.vault.createFolder(path);
await this.app.vault.modifyBinary(res[0], res[1]);
});
// new Notice("Sync complete :)");
}
}
} catch (err) {
await this.notifyError();
await this.checkForConnectivity();
await this.writeToErrorLogFile(err);
}
await this.writeToVerboseLogFile("LOG: Exited getLatestContent");
};
emptySyncQueue = async () => {
if (this.haltAllOperations) {
return;
}
await this.writeToVerboseLogFile("LOG: Entering emptySyncQueue");
let path = this.syncQueue.shift(); // this tells that, uptil this moment, all changes are being accounted for the 1st file in sync queue
this.isUploadingCurrentFile = true; // this ensures only one upload operation is going on at a time
let file = this.app.vault.getAbstractFileByPath(path!);
if (!(file instanceof TFile)) {
return;
}
var id;
this.settings.filesList.map((f: any) => {
if (f.name == file!.path) {
id = f.id;
}
});
if (file.extension == "md") await this.updateLastSyncMetaTag(file);
var buffer = await this.app.vault.readBinary(file);
await modifyFile(this.settings.accessToken, id, buffer);
await this.refreshFilesListInDriveAndStoreInSettings();
this.statusBarItem.classList.replace("sync_icon", "sync_icon_still");
setIcon(this.statusBarItem, "checkmark");
this.isUploadingCurrentFile = false;
await this.writeToVerboseLogFile("LOG: Exited emptySyncQueue");
};
checkAndEmptySyncQueue = async () => {
if (!this.app.workspace.layoutReady || !this.layoutReady) {
// Workspace is still loading, do nothing
return;
}
if (
this.haltAllOperations ||
this.completingPendingSync ||
!this.connectedToInternet
)
return;
await this.writeToVerboseLogFile(
"LOG: Entering checkAndEmptySyncQueue"
);
if (this.haltAllOperations) {
return;
}
if (this.syncQueue.length && !this.isUploadingCurrentFile) {
this.emptySyncQueue();
}
};
uploadNewAttachment = async (e: TFile) => {
if (this.haltAllOperations) {
return;
}
if (this.isInBlacklist(e)) {
new Notice(
"File is listed in blacklist. It will be uploaded but not be tracked by the plugin automatically."
);
}
try {
await this.writeToVerboseLogFile(
"LOG: Entering uploadNewAttachment"
);
new Notice("Uploading new attachment!");
var buffer: any = await this.app.vault.readBinary(e);
this.currentlyUploading = e.path;
this.cloudFiles.push(e.path);
try {
await this.app.vault.create(
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${e.path.replace(
/\//g,
"."
)}`,
""
);
} catch (err) {
await this.writeToErrorLogFile(err);
await this.writeToVerboseLogFile(
"LOG: Could not create attachment tracking file: " +
`${ATTACHMENT_TRACKING_FOLDER_NAME}/${e.path.replace(
/\//g,
"."
)}`
);
}
let id = await uploadFile(
this.settings.accessToken,
e.path,