forked from vrtmrz/diffzip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
991 lines (939 loc) · 39.5 KB
/
main.ts
File metadata and controls
991 lines (939 loc) · 39.5 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
import { Notice, Plugin, parseYaml, stringifyYaml } from "obsidian";
import * as fflate from "fflate";
import {
getStorageForBackup,
getStorageForVault,
getStorageTypeForBackupAccess,
getStorageTypeForVaultAccess,
} from "./src/storage.ts";
import { type StorageAccessor } from "./src/StorageAccessor/StorageAccessor.ts";
import { RestoreDialog } from "./src/RestoreView.ts";
import { confirmWithMessage, askSelectString } from "./src/dialog.ts";
import { Archiver, Extractor } from "./src/Archive.ts";
import { computeDigest, pieces, toArrayBuffer } from "./src/util.ts";
import {
AutoBackupType,
DEFAULT_SETTINGS,
InfoFile,
type DiffZipBackupSettings,
type FileInfo,
type FileInfos,
type NoticeWithTimer,
} from "./src/types.ts";
import { DiffZipSettingTab } from "./src/DiffZipSettingTab.ts";
import { ProgressFragment } from "./src/ProgressFragment.ts";
import { CombinedFragment } from "./src/CombinedFragment.ts";
export default class DiffZipBackupPlugin extends Plugin {
settings: DiffZipBackupSettings;
get isMobile(): boolean {
// @ts-ignore
return this.app.isMobile;
}
get isDesktopMode(): boolean {
return this.settings.desktopFolderEnabled && !this.isMobile;
}
get backupFolder(): string {
if (this.settings.bucketEnabled) return this.settings.backupFolderBucket;
return this.isDesktopMode ? this.settings.BackupFolderDesktop : this.settings.backupFolderMobile;
}
_backups: StorageAccessor;
get backups(): StorageAccessor {
const type = getStorageTypeForBackupAccess(this);
if (!this._backups || this._backups.type != type) {
this._backups = getStorageForBackup(this);
}
return this._backups;
}
_vaultAccess: StorageAccessor;
get vaultAccess(): StorageAccessor {
const type = getStorageTypeForVaultAccess(this);
if (!this._vaultAccess || this._vaultAccess.type != type) {
this._vaultAccess = getStorageForVault(this);
}
return this._vaultAccess;
}
get sep(): string {
//@ts-ignore
return this.isDesktopMode ? this.app.vault.adapter.path.sep : "/";
}
messages = {} as Record<string, NoticeWithTimer>;
logMessage(message: string, key?: string) {
this.logWrite(message, key);
if (!key) {
new Notice(message, 3000);
return;
}
let n: NoticeWithTimer | undefined = undefined;
if (key in this.messages) {
n = this.messages[key];
clearTimeout(n.timer);
if (!n.notice.noticeEl.isShown()) {
delete this.messages[key];
} else {
n.notice.setMessage(message);
}
}
if (!n || !(key in this.messages)) {
n = {
notice: new Notice(message, 0),
};
}
n.timer = setTimeout(() => {
n?.notice?.hide();
}, 5000);
this.messages[key] = n;
}
hideMessage(key: string) {
const n = this.messages[key];
if (n) {
clearTimeout(n.timer);
n.notice.hide();
delete this.messages[key];
}
}
logWrite(message: string, key?: string) {
const dt = new Date().toLocaleString();
console.log(`${dt}\t${message}`);
}
async getFiles(path: string, ignoreList: string[], progress: ProgressFragment) {
const pathPart = ellipsisMiddle(path);
progress.note = `Scanning ${pathPart}`;
const w = await this.app.vault.adapter.list(path);
progress.total += w.folders.length;
let files = [...w.files.filter((e) => !ignoreList.some((ee) => e.endsWith(ee)))];
L1: for (const v of w.folders) {
for (const ignore of ignoreList) {
if (v.endsWith(ignore)) {
progress.value++;
continue L1;
}
}
// files = files.concat([v]);
files = files.concat(await this.getFiles(v, ignoreList, progress));
progress.value++;
}
return files;
}
async loadTOC() {
let toc = {} as FileInfos;
const tocFilePath = this.backups.normalizePath(`${this.backupFolder}${this.sep}${InfoFile}`);
const tocExist = await this.backups.isFileExists(tocFilePath);
if (tocExist) {
this.logWrite(`Loading Backup information`, "proc-index");
try {
const tocBin = await this.backups.readTOC(tocFilePath);
if (tocBin == null || tocBin === false) {
this.logMessage(`LOAD ERROR: Could not read Backup information`, "proc-index");
return {};
}
const tocStr = new TextDecoder().decode(tocBin);
toc = parseYaml(tocStr.replace(/^```$/gm, ""));
if (toc == null) {
this.logMessage(`PARSE ERROR: Could not parse Backup information`, "proc-index");
toc = {};
} else {
this.logWrite(`Backup information has been loaded`, "proc-index");
}
} catch (ex) {
this.logMessage(`Something went wrong while parsing Backup information`, "proc-index");
console.warn(ex);
toc = {};
}
} else {
this.logMessage(`Backup information looks missing`, "proc-index");
}
return toc;
}
async getAllFiles() {
const ignores = [
"node_modules",
".git",
this.app.vault.configDir + "/trash",
this.app.vault.configDir + "/workspace.json",
this.app.vault.configDir + "/workspace-mobile.json",
];
if (this.settings.includeHiddenFolder) {
const progress = new ProgressFragment({
title: "Gathering Files",
value: 0,
total: 0,
onComplete: () => {
setTimeout(() => {
notice.hide();
}, 1000);
},
});
const notice = new Notice(progress.fragment, 0);
return (await this.getFiles("", ignores, progress)).filter((e) => !e.startsWith(".trash/"));
}
return this.app.vault.getFiles().map((e) => e.path);
}
async createZip(verbosity: boolean, skippableFiles: string[] = [], onlyNew = false, skipDeleted: boolean = false) {
const key = "proc-zip-process-" + Date.now();
const log = verbosity
? (msg: string, key?: string) => this.logWrite(msg, key)
: (msg: string, key?: string) => this.logMessage(msg, key);
const allFiles = await this.getAllFiles();
const toc = await this.loadTOC();
const today = new Date();
const secondsInDay = ~~(today.getTime() / 1000 - today.getTimezoneOffset() * 60) % 86400;
const newFileName = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}-${secondsInDay}.zip`;
// Find missing files
let missingFiles = 0;
let progressNotice: Notice | undefined;
let onProgress = () => {};
const fragmentOption = {
total: 0,
onComplete: () => onCloseProgress(),
onProgress: () => onProgress(),
} as const;
const missingFileProgress = new ProgressFragment({
title: "Checking file and TOC",
...fragmentOption,
});
const checkingProgress = new ProgressFragment({
title: "Check and Archiving Files",
...fragmentOption,
});
const fileProcessingProgress = new ProgressFragment({
title: "File Processing",
...fragmentOption,
});
const fileArchivedProgress = new ProgressFragment({
title: "Archiving Files",
...fragmentOption,
});
const uploadingProgress = new ProgressFragment({
title: "Committing ZIP Files",
...fragmentOption,
});
const combinedFragment = new CombinedFragment([
() => missingFileProgress.reconstructFragment(),
() => checkingProgress.reconstructFragment(),
() => fileProcessingProgress.reconstructFragment(),
() => fileArchivedProgress.reconstructFragment(),
() => uploadingProgress.reconstructFragment(),
]);
const isClosed = () => {
return progressNotice == undefined || !progressNotice.noticeEl.isShown();
};
onProgress = () => {
if (!isClosed()) return;
progressNotice = new Notice(combinedFragment.rebuildFragment(), 0);
};
const onCloseProgress = () => {
if (
[
missingFileProgress,
checkingProgress,
fileProcessingProgress,
fileArchivedProgress,
uploadingProgress,
].every((e) => e.isCompleted || e.isCancelled)
) {
setTimeout(() => {
progressNotice?.hide();
progressNotice = undefined;
}, 3000);
}
};
missingFileProgress.total = Object.keys(toc).length;
for (const [filename, fileInfo] of Object.entries(toc)) {
try {
if (fileInfo.missing) continue;
if (!(await this.vaultAccess.isFileExists(this.vaultAccess.normalizePath(filename)))) {
if (skipDeleted) continue;
fileInfo.missing = true;
fileInfo.digest = "";
fileInfo.mtime = today.getTime();
fileInfo.processed = today.getTime();
log(`File ${filename} is missing`);
fileInfo.history = [
...fileInfo.history,
{
zipName: newFileName,
modified: today.toISOString(),
missing: true,
processed: today.getTime(),
digest: "",
},
];
log(`History of ${filename} has been updated (Missing)`);
missingFiles++;
}
} finally {
missingFileProgress.value++;
}
}
const zip = new Archiver();
const normalFiles = allFiles
.filter(
(e) =>
!e.startsWith(this.backupFolder + this.sep) && !e.startsWith(this.settings.restoreFolder + this.sep)
)
.filter((e) => skippableFiles.indexOf(e) == -1);
checkingProgress.total = normalFiles.length;
let processed = 0;
let processedSize = 0;
let hasExtra = false;
const processedFiles = [] as string[];
let zipped = 0;
for (const path of normalFiles) {
try {
processedFiles.push(path);
processed++;
checkingProgress.note = `Processing ${ellipsisMiddle(path)}`;
const stat = await this.vaultAccess.stat(path);
if (!stat) {
this.logMessage(`Archiving: Could not read stat ${path}`);
continue;
}
// Check the file is in the skippable list
if (onlyNew && path in toc) {
const entry = toc[path];
const mtime = new Date(stat.mtime).getTime();
if (mtime <= entry.mtime) {
this.logWrite(`${path} older than the last backup, skipping`);
continue;
}
}
// Read the file content
const content = await this.vaultAccess.readBinary(path);
if (!content) {
this.logMessage(`Archiving: Could not read ${path}`);
continue;
}
// Check the file actually modified.
const f = new Uint8Array(content);
const digest = await computeDigest(f);
if (path in toc) {
const entry = toc[path];
if (entry.digest == digest) {
this.logWrite(`${path} Not changed`);
continue;
}
}
zipped++;
processedSize += content.byteLength;
// Update the file information
toc[path] = {
digest,
filename: path,
mtime: stat.mtime,
processed: today.getTime(),
history: [
...(toc[path]?.history ?? []),
{
zipName: newFileName,
modified: new Date(stat.mtime).toISOString(),
processed: today.getTime(),
digest,
},
],
};
fileArchivedProgress.total++;
fileArchivedProgress.note = `Archiving: ${ellipsisMiddle(path)}`;
zip.addFile(f, path, { mtime: stat.mtime }, (processed, total, finished) => {
if (!finished) {
fileProcessingProgress.note = `Archiving: ${ellipsisMiddle(path)}`;
fileProcessingProgress.total = total;
fileProcessingProgress.value = processed;
} else {
fileArchivedProgress.value++;
fileArchivedProgress.note = `Archived: ${ellipsisMiddle(path)}`;
fileProcessingProgress.note = "";
fileProcessingProgress.isCancelled = true;
fileProcessingProgress.total = 0;
fileProcessingProgress.value = 0;
}
});
if (this.settings.maxFilesInZip > 0 && zipped >= this.settings.maxFilesInZip) {
checkingProgress.total = zipped;
checkingProgress.note = `⚠️ Max files in a single ZIP`;
hasExtra = true;
break;
}
if (
this.settings.maxTotalSizeInZip > 0 &&
processedSize >= this.settings.maxTotalSizeInZip * 1024 * 1024
) {
checkingProgress.total = zipped;
checkingProgress.note = `⚠️ Max total size in a single ZIP`;
hasExtra = true;
break;
}
} finally {
checkingProgress.value++;
}
}
if (!hasExtra) {
checkingProgress.note = ``;
}
if (zipped == 0 && missingFiles == 0) {
fileProcessingProgress.isCancelled = true;
checkingProgress.isCancelled = true;
fileArchivedProgress.isCancelled = true;
uploadingProgress.note = `No files have been changed. \nSkipping ZIP generation...`;
uploadingProgress.isCancelled = true;
return;
}
const tocTimeStamp = new Date().getTime();
zip.addTextFile(`\`\`\`\n${stringifyYaml(toc)}\n\`\`\`\n`, InfoFile, { mtime: tocTimeStamp });
try {
const buf = await zip.finalize();
uploadingProgress.total = buf.byteLength;
// Writing a large file can cause the crash of Obsidian, and very heavy to synchronise.
// Hence, we have to split the file into a smaller size.
const step =
this.settings.maxSize / 1 == 0 ? buf.byteLength + 1 : (this.settings.maxSize / 1) * 1024 * 1024;
let pieceCount = 0;
// If the file size is smaller than the step, it will be a single file.
// Otherwise, it will be split into multiple files. (start from 001)
if (buf.byteLength > step) pieceCount = 1;
const chunks = pieces(buf, step);
for (const chunk of chunks) {
const outZipFile = this.backups.normalizePath(
`${this.backupFolder}${this.sep}${newFileName}${pieceCount == 0 ? "" : "." + `00${pieceCount}`.slice(-3)}`
);
pieceCount++;
uploadingProgress.note = `Committing ${ellipsisMiddle(outZipFile)}`;
const e = await this.backups.writeBinary(outZipFile, toArrayBuffer(chunk));
if (!e) {
throw new Error(`Creating ${outZipFile} has been failed!`);
}
uploadingProgress.value += chunk.byteLength;
}
const tocFilePath = this.backups.normalizePath(`${this.backupFolder}${this.sep}${InfoFile}`);
// Update TOC
if (
!(await this.backups.writeTOC(
tocFilePath,
toArrayBuffer(new TextEncoder().encode(`\`\`\`\n${stringifyYaml(toc)}\n\`\`\`\n`))
))
) {
throw new Error(`Updating TOC has been failed!`);
}
log(`Backup information has been updated`, key);
if (hasExtra && this.settings.performNextBackupOnMaxFiles) {
checkingProgress.isCancelled = true;
setTimeout(() => {
this.createZip(verbosity, [...skippableFiles, ...processedFiles], onlyNew, skipDeleted);
}, 10);
} else {
this.logMessage(
`${processed} of ${normalFiles.length} files have been processed, ${zipped} files have been zipped.`,
key
);
}
// } else {
// this.logMessage(`Backup has been aborted \n${processed} files, ${zipped} zip files`, "proc-zip-process");
// }
} catch (e) {
this.logMessage(`Something get wrong while processing ${processed} files, ${zipped} zip files`, key);
this.logWrite(e);
}
}
async extract(zipFile: string, extractFiles: string[]): Promise<void>;
async extract(zipFile: string, extractFiles: string, restoreAs: string): Promise<void>;
async extract(zipFile: string, extractFiles: string[], restoreAs: undefined, restorePrefix: string): Promise<void>;
async extract(
zipFile: string,
extractFiles: string | string[],
restoreAs: string | undefined = undefined,
restorePrefix: string = ""
): Promise<void> {
const hasMultipleSupplied = Array.isArray(extractFiles);
const zipPath = this.backups.normalizePath(`${this.backupFolder}${this.sep}${zipFile}`);
const zipF = await this.backups.isExists(zipPath);
let files = [] as string[];
if (zipF) {
files = [zipPath];
} else {
let hasNext = true;
let counter = 0;
do {
counter++;
const partialZipPath = zipPath + "." + `00${counter}`.slice(-3);
if (await this.backups.isExists(partialZipPath)) {
files.push(partialZipPath);
} else {
hasNext = false;
}
} while (hasNext);
}
if (files.length == 0) {
this.logMessage("Archived ZIP files were not found!");
}
const restored = [] as string[];
const extractor = new Extractor(
(file: fflate.UnzipFile) => {
if (hasMultipleSupplied) {
return extractFiles.indexOf(file.name) !== -1;
}
return file.name === extractFiles;
},
async (file: string, dat: Uint8Array<ArrayBuffer>) => {
const fileName = restoreAs ?? file;
const restoreTo = hasMultipleSupplied ? `${restorePrefix}${fileName}` : fileName;
if (await this.vaultAccess.writeBinary(restoreTo, toArrayBuffer(dat))) {
restored.push(restoreTo);
const files = restored.slice(-5).join("\n");
this.logMessage(`${restored.length} files have been restored! \n${files}\n...`, "proc-zip-extract");
} else {
this.logMessage(`Creating or Overwriting ${file} has been failed!`);
}
}
);
const size = 1024 * 1024;
for (const file of files) {
this.logMessage(`Processing ${file}...`, "proc-zip-export-processing");
const binary = await this.backups.readBinary(file);
if (binary == null || binary === false) {
this.logMessage(`Could not read ${file}`);
return;
}
const chunks = pieces(new Uint8Array(binary), size);
for await (const chunk of chunks) {
extractor.addZippedContent(chunk);
}
}
}
async selectAndRestore() {
const files = await this.loadTOC();
const filenames = Object.entries(files)
.sort((a, b) => b[1].mtime - a[1].mtime)
.map((e) => e[0]);
if (filenames.length == 0) {
return;
}
const selected = await askSelectString(this.app, "Select file", filenames);
if (!selected) {
return;
}
const revisions = files[selected].history;
const d = `\u{2063}`;
const revisionList = revisions.map((e) => `${e.zipName}${d} (${e.modified})`).reverse();
const selectedTimestamp = await askSelectString(this.app, "Select file", revisionList);
if (!selectedTimestamp) {
return;
}
const [filename] = selectedTimestamp.split(d);
const suffix = filename.replace(".zip", "");
// No cares about without extension
const extArr = selected.split(".");
const ext = extArr.pop();
const selectedWithoutExt = extArr.join(".");
const RESTORE_OVERWRITE = "Original place and okay to overwrite";
const RESTORE_TO_RESTORE_FOLDER = "Under the restore folder";
const RESTORE_WITH_SUFFIX = "Original place but with ZIP name suffix";
const restoreMethods = [RESTORE_TO_RESTORE_FOLDER, RESTORE_OVERWRITE, RESTORE_WITH_SUFFIX];
const howToRestore = await askSelectString(this.app, "Where to restore?", restoreMethods);
const restoreAs =
howToRestore == RESTORE_OVERWRITE
? selected
: howToRestore == RESTORE_TO_RESTORE_FOLDER
? this.vaultAccess.normalizePath(`${this.settings.restoreFolder}${this.sep}${selected}`)
: howToRestore == RESTORE_WITH_SUFFIX
? `${selectedWithoutExt}-${suffix}.${ext}`
: "";
if (!restoreAs) {
return;
}
await this.extract(filename, selected, restoreAs);
}
async pickRevisions(files: FileInfos, prefix = ""): Promise<string> {
const BACK = "[..]";
const timestamps = new Set<string>();
const all = Object.entries(files).filter((e) => e[0].startsWith(prefix));
for (const f of all) {
f[1].history.map((e) => e.modified).map((e) => timestamps.add(e));
}
const modifiedList = [...timestamps].sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).reverse();
modifiedList.unshift(BACK);
const selected = await askSelectString(this.app, "Until?", modifiedList);
if (!selected) {
return "";
}
return selected;
}
async selectAndRestoreFolder(filesSrc?: FileInfos, prefix = "") {
if (!filesSrc) filesSrc = await this.loadTOC();
const files = JSON.parse(JSON.stringify({ ...filesSrc })) as typeof filesSrc;
const level = prefix.split("/").filter((e) => !!e).length + 1;
const filenamesAll = Object.entries(files)
.sort((a, b) => b[1].mtime - a[1].mtime)
.map((e) => e[0]);
const filenamesFiltered = filenamesAll.filter((e) => e.startsWith(prefix));
const filenamesA = filenamesFiltered
.map((e) => {
const paths = e.split("/");
const name = paths.splice(0, level).join("/");
if (paths.length == 0 && name) return name;
return `${name}/`;
})
.sort((a, b) => {
const isDirA = a.endsWith("/");
const isDirB = b.endsWith("/");
if (isDirA && !isDirB) return -1;
if (!isDirA && isDirB) return 1;
if (isDirA && isDirB) return a.localeCompare(b);
return 0;
});
const filenames = [...new Set(filenamesA)];
if (filenames.length == 0) {
return;
}
const BACK = "[..]";
const ALL = "[ALL]";
filenames.unshift(ALL);
filenames.unshift(BACK);
const selected = await askSelectString(this.app, "Select file", filenames);
if (!selected) {
return;
}
if (selected == BACK) {
const p = prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
const parent = p.split("/").slice(0, -1).join("/");
await this.selectAndRestoreFolder(filesSrc, parent);
return;
}
if (selected == ALL) {
// Collect all files and timings
const selectedThreshold = await this.pickRevisions(files, prefix);
if (!selectedThreshold) {
return;
}
if (selectedThreshold == BACK) {
await this.selectAndRestoreFolder(filesSrc, prefix);
return;
}
const allFiles = Object.entries(files).filter((e) => e[0].startsWith(prefix));
const maxDate = new Date(selectedThreshold).getTime();
const fileMap = new Map<string, FileInfo["history"][0]>();
for (const [key, files] of allFiles) {
for (const fileInfo of files.history) {
//keep only the latest one
const fileModified = new Date(fileInfo.modified).getTime();
if (fileModified > maxDate) continue;
const info = fileMap.get(key);
if (!info) {
fileMap.set(key, fileInfo);
} else {
if (new Date(info.modified).getTime() < fileModified) {
fileMap.set(key, fileInfo);
}
}
}
}
const zipMap = new Map<string, string[]>();
for (const [filename, fileInfo] of fileMap) {
const path = fileInfo.zipName;
const arr = zipMap.get(path) ?? [];
arr.push(filename);
zipMap.set(path, arr);
}
// const fileMap = new Map<string, string>();
// for (const [zipName, fileInfo] of zipMap) {
// const path = fileInfo.zipName;
// fileMap.set(path, zipName);
// }
const zipList = [...zipMap.entries()].sort((a, b) => a[0].localeCompare(b[0]));
const filesCount = zipList.reduce((a, b) => a + b[1].length, 0);
if (
(await askSelectString(
this.app,
`Are you sure to restore(Overwrite) ${filesCount} files from ${zipList.length} ZIPs`,
["Y", "N"]
)) != "Y"
) {
this.logMessage(`Cancelled`);
return;
}
this.logMessage(`Extract ${zipList.length} ZIPs`);
let i = 0;
for (const [zipName, files] of zipList) {
i++;
this.logMessage(`Extract ${files.length} files from ${zipName} (${i}/${zipList.length})`);
await this.extract(zipName, files);
}
// console.dir(zipMap);
return;
}
if (selected.endsWith("/")) {
await this.selectAndRestoreFolder(filesSrc, selected);
return;
}
const revisions = files[selected].history;
const d = `\u{2063}`;
const revisionList = revisions.map((e) => `${e.zipName}${d} (${e.modified})`).reverse();
revisionList.unshift(BACK);
const selectedTimestamp = await askSelectString(this.app, "Select file", revisionList);
if (!selectedTimestamp) {
return;
}
if (selectedTimestamp == BACK) {
await this.selectAndRestoreFolder(filesSrc, prefix);
return;
}
const [filename] = selectedTimestamp.split(d);
const suffix = filename.replace(".zip", "");
// No cares about without extension
const extArr = selected.split(".");
const ext = extArr.pop();
const selectedWithoutExt = extArr.join(".");
const RESTORE_OVERWRITE = "Original place and okay to overwrite";
const RESTORE_TO_RESTORE_FOLDER = "Under the restore folder";
const RESTORE_WITH_SUFFIX = "Original place but with ZIP name suffix";
const restoreMethods = [RESTORE_TO_RESTORE_FOLDER, RESTORE_OVERWRITE, RESTORE_WITH_SUFFIX];
const howToRestore = await askSelectString(this.app, "Where to restore?", restoreMethods);
const restoreAs =
howToRestore == RESTORE_OVERWRITE
? selected
: howToRestore == RESTORE_TO_RESTORE_FOLDER
? this.vaultAccess.normalizePath(`${this.settings.restoreFolder}${this.sep}${selected}`)
: howToRestore == RESTORE_WITH_SUFFIX
? `${selectedWithoutExt}-${suffix}.${ext}`
: "";
if (!restoreAs) {
return;
}
await this.extract(filename, selected, restoreAs);
}
// _debugDialogue?: RestoreDialog;
async onLayoutReady() {
// if (this._debugDialogue) {
// this._debugDialogue.close();
// this._debugDialogue = undefined;
// }
if (this.settings.startBackupAtLaunch) {
const onlyNew =
this.settings.startBackupAtLaunchType == AutoBackupType.ONLY_NEW ||
this.settings.startBackupAtLaunchType == AutoBackupType.ONLY_NEW_AND_EXISTING;
const skipDeleted = this.settings.startBackupAtLaunchType == AutoBackupType.ONLY_NEW_AND_EXISTING;
this.createZip(false, [], onlyNew, skipDeleted);
}
}
// onunload(): void {
// this._debugDialogue?.close();
// }
async restoreVault(
onlyNew = true,
deleteMissing: boolean = false,
fileFilter: Record<string, number> | undefined = undefined,
prefix: string = ""
) {
this.logMessage(`Checking backup information...`);
const files = await this.loadTOC();
// const latestZipMap = new Map<string, string>();
const zipFileMap = new Map<string, string[]>();
const thisPluginDir = this.manifest.dir;
const deletingFiles = [] as string[];
let processFileCount = 0;
for (const [filename, fileInfo] of Object.entries(files)) {
if (fileFilter) {
const matched = Object.keys(fileFilter)
.filter((e) => (e.endsWith("*") ? filename.startsWith(e.slice(0, -1)) : e == filename))
.sort((a, b) => b.length - a.length);
if (matched.length == 0) {
this.logWrite(`${filename}: is not matched with supplied filter. Skipping...`);
continue;
}
const matchedFilter = matched[0];
// remove history after the filter
fileInfo.history = fileInfo.history.filter(
(e) => new Date(e.modified).getTime() <= fileFilter[matchedFilter]
);
}
if (thisPluginDir && fileInfo.filename.startsWith(thisPluginDir)) {
this.logWrite(`${filename} is a plugin file. Skipping on vault restoration`);
continue;
}
const history = fileInfo.history;
if (history.length == 0) {
this.logWrite(`${filename}: has no history. Skipping...`);
continue;
}
history.sort((a, b) => new Date(b.modified).getTime() - new Date(a.modified).getTime());
const latest = history[0];
const zipName = latest.zipName;
const localFileName = this.vaultAccess.normalizePath(`${prefix}${filename}`);
const localStat = await this.vaultAccess.stat(localFileName);
if (localStat) {
const content = await this.vaultAccess.readBinary(localFileName);
if (!content) {
this.logWrite(`${filename}: has been failed to read`);
continue;
}
const localDigest = await computeDigest(new Uint8Array(content));
if (localDigest == latest?.digest) {
this.logWrite(`${filename}: is as same as the backup. Skipping...`);
continue;
}
if (fileInfo.missing) {
if (!deleteMissing) {
this.logWrite(`${filename}: is marked as missing, but existing in the vault. Skipping...`);
continue;
} else {
// this.logWrite(`${filename}: is marked as missing. Deleting...`);
deletingFiles.push(filename);
//TODO: Delete the file
}
}
const localMtime = localStat.mtime;
const remoteMtime = new Date(latest.modified).getTime();
if (onlyNew && localMtime >= remoteMtime) {
this.logWrite(`${filename}: Ours is newer than the backup. Skipping...`);
continue;
}
} else {
if (fileInfo.missing) {
this.logWrite(`${filename}: is missing and not found in the vault. Skipping...`);
continue;
}
}
this.logWrite(`${filename}: will be restored from ${zipName}`);
if (!zipFileMap.has(zipName)) {
zipFileMap.set(zipName, []);
}
zipFileMap.get(zipName)?.push(filename);
processFileCount++;
// latestZipMap.set(filename, zipName);
}
if (processFileCount == 0 && deletingFiles.length == 0) {
this.logMessage(`Nothing to restore`);
return;
}
const detailFiles = `<details>
${[...zipFileMap.entries()]
.map((e) => `${e[1].map((ee) => `- ${ee} (${e[0]})`).join("\n")}\n`)
.sort((a, b) => a.localeCompare(b))
.join("")}
</details>`;
const detailDeletedFiles = `<details>
${deletingFiles.map((e) => `- ${e}`).join("\n")}
</details>`;
const deleteMessage =
deleteMissing && deletingFiles.length > 0
? `And ${deletingFiles.length} files will be deleted.\n${detailDeletedFiles}\n`
: "";
const message = `We have ${processFileCount} files to restore on ${zipFileMap.size} ZIPs. \n${detailFiles}\n${deleteMessage}Are you sure to proceed?`;
const RESTORE_BUTTON = "Yes, restore them!";
const CANCEL = "Cancel";
if (
(await confirmWithMessage(this, "Restore Confirmation", message, [RESTORE_BUTTON, CANCEL], CANCEL)) !=
RESTORE_BUTTON
) {
this.logMessage(`Cancelled`);
return;
}
for (const [zipName, files] of zipFileMap) {
this.logMessage(`Extracting ${zipName}...`);
await this.extract(zipName, files, undefined, prefix);
}
// console.dir(zipFileMap);
}
async onload() {
await this.loadSettings();
if ("backupFolder" in this.settings) {
this.settings.backupFolderMobile = this.settings.backupFolder as string;
delete this.settings.backupFolder;
}
this.app.workspace.onLayoutReady(() => this.onLayoutReady());
this.addCommand({
id: "a-find-from-backups",
name: "Restore from backups",
callback: async () => {
const d = new RestoreDialog(this.app, this);
d.open();
},
});
this.addCommand({
id: "find-from-backups-old",
name: "Restore from backups (previous behaviour)",
callback: async () => {
await this.selectAndRestore();
},
});
this.addCommand({
id: "find-from-backups-dir",
name: "Restore from backups per folder",
callback: async () => {
await this.selectAndRestoreFolder();
},
});
this.addCommand({
id: "b-create-diff-zip",
name: "Create Differential Backup",
callback: () => {
this.createZip(true);
},
});
this.addCommand({
id: "b-create-diff-zip-only-new",
name: "Create Differential Backup Only Newer Files",
callback: () => {
this.createZip(true, [], true);
},
});
this.addCommand({
id: "b-create-diff-zip-only-new-and-existing",
name: "Create Non-Destructive Differential Backup",
callback: () => {
this.createZip(true, [], false, true);
},
});
this.addCommand({
id: "b-create-diff-zip-only-new-and-existing-only-new",
name: "Create Non-Destructive Differential Backup Only Newer Files",
callback: () => {
this.createZip(true, [], true, true);
},
});
this.addCommand({
id: "vault-restore-from-backups-only-new",
name: "Fetch all new files from the backups",
callback: async () => {
await this.restoreVault(true, false);
},
});
this.addCommand({
id: "vault-restore-from-backups-with-deletion",
name: "⚠ Restore Vault from backups and delete with deletion",
callback: async () => {
await this.restoreVault(false, true);
},
});
this.addSettingTab(new DiffZipSettingTab(this.app, this));
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async resetToC() {
const toc = {} as FileInfos;
const tocFilePath = this.backups.normalizePath(`${this.backupFolder}${this.sep}${InfoFile}`);
// Update TOC
if (
await this.backups.writeTOC(
tocFilePath,
toArrayBuffer(new TextEncoder().encode(`\`\`\`\n${stringifyYaml(toc)}\n\`\`\`\n`))
)
) {
this.logMessage(`Backup information has been reset`);
} else {
this.logMessage(`Backup information cannot reset`);
}
}
async saveSettings() {
await this.saveData(this.settings);
}
}
function ellipsisMiddle(text: string, maxLength: number = 60) {
if (text.length <= maxLength) {
return text;
}
const ellipsis = "...";
const charsToShow = maxLength - ellipsis.length;
const start = Math.ceil(charsToShow / 2);
const end = text.length - Math.floor(charsToShow / 2);
return text.slice(0, start) + ellipsis + text.slice(end);
}