-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
3441 lines (3402 loc) · 470 KB
/
main.js
File metadata and controls
3441 lines (3402 loc) · 470 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
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => SecureWebdavImagesPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian4 = require("obsidian");
// secure-webdav-image-support.ts
var import_obsidian = require("obsidian");
var SECURE_PROTOCOL = "webdav-secure:";
var SECURE_CODE_BLOCK = "secure-webdav";
var SecureWebdavRenderChild = class extends import_obsidian.MarkdownRenderChild {
constructor(containerEl) {
super(containerEl);
}
onunload() {
}
};
var SecureWebdavImageSupport = class {
constructor(deps) {
this.deps = deps;
}
buildSecureImageMarkup(remoteUrl, alt) {
const remotePath = this.extractRemotePath(remoteUrl);
if (!remotePath) {
return ``;
}
return this.buildSecureImageCodeBlock(remotePath, alt);
}
buildSecureImageCodeBlock(remotePath, alt) {
const normalizedAlt = (alt || remotePath).replace(/\r?\n/g, " ").trim();
const normalizedPath = remotePath.replace(/\r?\n/g, "").trim();
return [`\`\`\`${SECURE_CODE_BLOCK}`, `path: ${normalizedPath}`, `alt: ${normalizedAlt}`, "```"].join("\n");
}
parseSecureImageBlock(source) {
const result = { path: "", alt: "" };
for (const rawLine of source.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) {
continue;
}
const separatorIndex = line.indexOf(":");
if (separatorIndex === -1) {
continue;
}
const key = line.slice(0, separatorIndex).trim().toLowerCase();
const value = line.slice(separatorIndex + 1).trim();
if (key === "path") {
result.path = value;
} else if (key === "alt") {
result.alt = value;
}
}
return result.path ? result : null;
}
async processSecureImages(el, ctx) {
const secureCodeBlocks = Array.from(el.querySelectorAll(`pre > code.language-${SECURE_CODE_BLOCK}`));
await Promise.all(
secureCodeBlocks.map(async (codeEl) => {
const pre = codeEl.parentElement;
if (!(pre instanceof HTMLElement) || pre.hasAttribute("data-secure-webdav-rendered")) {
return;
}
const parsed = this.parseSecureImageBlock(codeEl.textContent ?? "");
if (!parsed?.path) {
return;
}
pre.setAttribute("data-secure-webdav-rendered", "true");
await this.renderSecureImageIntoElement(pre, parsed.path, parsed.alt || parsed.path);
})
);
const secureNodes = Array.from(el.querySelectorAll("[data-secure-webdav]"));
await Promise.all(
secureNodes.map(async (node) => {
if (node instanceof HTMLImageElement) {
await this.swapImageSource(node);
return;
}
const remotePath = node.getAttribute("data-secure-webdav");
if (!remotePath) {
return;
}
const img = document.createElement("img");
img.alt = node.getAttribute("aria-label") ?? node.getAttribute("alt") ?? "Secure WebDAV image";
img.setAttribute("data-secure-webdav", remotePath);
img.classList.add("secure-webdav-image", "is-loading");
node.replaceWith(img);
await this.swapImageSource(img);
})
);
const secureLinks = Array.from(el.querySelectorAll(`img[src^="${SECURE_PROTOCOL}//"]`));
await Promise.all(secureLinks.map(async (img) => this.swapImageSource(img)));
ctx.addChild(new SecureWebdavRenderChild(el));
}
async processSecureCodeBlock(source, el, ctx) {
const parsed = this.parseSecureImageBlock(source);
if (!parsed?.path) {
el.createEl("div", {
text: this.deps.t("\u5B89\u5168\u56FE\u7247\u4EE3\u7801\u5757\u683C\u5F0F\u65E0\u6548\u3002", "Invalid secure image code block format.")
});
return;
}
await this.renderSecureImageIntoElement(el, parsed.path, parsed.alt || parsed.path);
ctx.addChild(new SecureWebdavRenderChild(el));
}
extractRemotePath(src) {
const prefix = `${SECURE_PROTOCOL}//`;
if (!src.startsWith(prefix)) {
return null;
}
return src.slice(prefix.length);
}
async renderSecureImageIntoElement(el, remotePath, alt) {
const img = document.createElement("img");
img.alt = alt;
img.setAttribute("data-secure-webdav", remotePath);
img.classList.add("secure-webdav-image", "is-loading");
el.empty();
el.appendChild(img);
await this.swapImageSource(img);
}
async swapImageSource(img) {
const remotePath = img.getAttribute("data-secure-webdav") ?? this.extractRemotePath(img.getAttribute("src") ?? "");
if (!remotePath) {
return;
}
img.classList.add("secure-webdav-image", "is-loading");
const originalAlt = img.alt;
img.alt = originalAlt || this.deps.t("\u52A0\u8F7D\u5B89\u5168\u56FE\u7247\u4E2D...", "Loading secure image...");
try {
const blobUrl = await this.deps.fetchSecureImageBlobUrl(remotePath);
img.src = blobUrl;
img.alt = originalAlt;
img.style.display = "block";
img.style.maxWidth = "100%";
img.classList.remove("is-loading", "is-error");
} catch (error) {
console.error("Secure WebDAV image load failed", error);
img.replaceWith(this.buildErrorElement(remotePath, error));
}
}
buildErrorElement(remotePath, error) {
const el = document.createElement("div");
el.className = "secure-webdav-image is-error";
const message = error instanceof Error ? error.message : String(error);
el.textContent = this.deps.t(
`\u5B89\u5168\u56FE\u7247\u52A0\u8F7D\u5931\u8D25\uFF1A${remotePath}\uFF08${message}\uFF09`,
`Secure image failed: ${remotePath} (${message})`
);
return el;
}
};
// secure-webdav-upload-queue.ts
var import_obsidian2 = require("obsidian");
var SecureWebdavUploadQueueSupport = class {
constructor(deps) {
this.deps = deps;
this.processingTaskIds = /* @__PURE__ */ new Set();
this.retryTimeouts = /* @__PURE__ */ new Map();
this.pendingTaskPromises = /* @__PURE__ */ new Map();
}
dispose() {
for (const timeoutId of this.retryTimeouts.values()) {
window.clearTimeout(timeoutId);
}
this.retryTimeouts.clear();
}
hasPendingWork() {
return this.deps.getQueue().length > 0 || this.processingTaskIds.size > 0 || this.pendingTaskPromises.size > 0;
}
async enqueueEditorImageUpload(noteFile, editor, imageFile, fileName) {
try {
const arrayBuffer = await imageFile.arrayBuffer();
const task = this.createUploadTask(
noteFile.path,
arrayBuffer,
imageFile.type || this.deps.getMimeTypeFromFileName(fileName),
fileName
);
this.insertPlaceholder(editor, task.placeholder);
this.deps.setQueue([...this.deps.getQueue(), task]);
await this.deps.savePluginState();
void this.processPendingTasks();
new import_obsidian2.Notice(this.deps.t("\u5DF2\u52A0\u5165\u56FE\u7247\u81EA\u52A8\u4E0A\u4F20\u961F\u5217\u3002", "Image added to the auto-upload queue."));
} catch (error) {
console.error("Failed to queue secure image upload", error);
new import_obsidian2.Notice(
this.deps.describeError(
this.deps.t("\u52A0\u5165\u56FE\u7247\u81EA\u52A8\u4E0A\u4F20\u961F\u5217\u5931\u8D25", "Failed to queue image for auto-upload"),
error
),
8e3
);
}
}
createUploadTask(notePath, binary, mimeType, fileName) {
const id = `secure-webdav-task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
return {
id,
notePath,
placeholder: this.buildPendingPlaceholder(id, fileName),
mimeType,
fileName,
dataBase64: this.deps.arrayBufferToBase64(binary),
attempts: 0,
createdAt: Date.now()
};
}
buildPendingPlaceholder(taskId, fileName) {
const safeName = this.deps.escapeHtml(fileName);
return `<span class="secure-webdav-pending" data-secure-webdav-task="${taskId}" aria-label="${safeName}">${this.deps.escapeHtml(this.deps.t(`\u3010\u56FE\u7247\u4E0A\u4F20\u4E2D\uFF5C${fileName}\u3011`, `[Uploading image | ${fileName}]`))}</span>`;
}
buildFailedPlaceholder(fileName, message) {
const safeName = this.deps.escapeHtml(fileName);
const safeMessage = this.deps.escapeHtml(message ?? this.deps.t("\u672A\u77E5\u9519\u8BEF", "Unknown error"));
const label = this.deps.escapeHtml(this.deps.t(`\u3010\u56FE\u7247\u4E0A\u4F20\u5931\u8D25\uFF5C${fileName}\u3011`, `[Image upload failed | ${fileName}]`));
return `<span class="secure-webdav-failed" aria-label="${safeName}">${label}: ${safeMessage}</span>`;
}
async processPendingTasks() {
const running = [];
for (const task of this.deps.getQueue()) {
if (this.processingTaskIds.has(task.id)) {
continue;
}
running.push(this.startPendingTask(task));
}
await Promise.allSettled(running);
}
startPendingTask(task) {
const existing = this.pendingTaskPromises.get(task.id);
if (existing) {
return existing;
}
const promise = this.processTask(task).finally(() => {
this.pendingTaskPromises.delete(task.id);
});
this.pendingTaskPromises.set(task.id, promise);
return promise;
}
async processTask(task) {
this.processingTaskIds.add(task.id);
try {
const binary = this.deps.base64ToArrayBuffer(task.dataBase64);
const prepared = await this.deps.prepareUploadPayload(
binary,
task.mimeType || this.deps.getMimeTypeFromFileName(task.fileName),
task.fileName
);
const remoteName = await this.deps.buildRemoteFileNameFromBinary(prepared.fileName, prepared.binary);
const remotePath = this.deps.buildRemotePath(remoteName);
const response = await this.deps.requestUrl({
url: this.deps.buildUploadUrl(remotePath),
method: "PUT",
headers: {
Authorization: this.deps.buildAuthHeader(),
"Content-Type": prepared.mimeType
},
body: prepared.binary
});
if (response.status < 200 || response.status >= 300) {
throw new Error(`Upload failed with status ${response.status}`);
}
const replaced = await this.replacePlaceholder(
task.notePath,
task.id,
task.placeholder,
this.deps.buildSecureImageMarkup(`webdav-secure://${remotePath}`, prepared.fileName)
);
if (!replaced) {
throw new Error(
this.deps.t(
"\u4E0A\u4F20\u6210\u529F\uFF0C\u4F46\u6CA1\u6709\u5728\u7B14\u8BB0\u4E2D\u627E\u5230\u53EF\u66FF\u6362\u7684\u5360\u4F4D\u7B26\u3002",
"Upload succeeded, but no matching placeholder was found in the note."
)
);
}
this.deps.setQueue(this.deps.getQueue().filter((item) => item.id !== task.id));
await this.deps.savePluginState();
this.deps.schedulePriorityNoteSync(task.notePath, "image-add");
new import_obsidian2.Notice(this.deps.t("\u56FE\u7247\u4E0A\u4F20\u6210\u529F\u3002", "Image uploaded successfully."));
} catch (error) {
console.error("Secure WebDAV queued upload failed", error);
task.attempts += 1;
task.lastError = error instanceof Error ? error.message : String(error);
await this.deps.savePluginState();
if (task.attempts >= this.deps.settings().maxRetryAttempts) {
await this.replacePlaceholder(
task.notePath,
task.id,
task.placeholder,
this.buildFailedPlaceholder(task.fileName, task.lastError)
);
this.deps.setQueue(this.deps.getQueue().filter((item) => item.id !== task.id));
await this.deps.savePluginState();
new import_obsidian2.Notice(this.deps.describeError(this.deps.t("\u56FE\u7247\u4E0A\u4F20\u6700\u7EC8\u5931\u8D25", "Image upload failed permanently"), error), 8e3);
} else {
this.scheduleRetry(task);
}
} finally {
this.processingTaskIds.delete(task.id);
}
}
scheduleRetry(task) {
const existing = this.retryTimeouts.get(task.id);
if (existing) {
window.clearTimeout(existing);
}
const delay = Math.max(1, this.deps.settings().retryDelaySeconds) * 1e3 * task.attempts;
const timeoutId = window.setTimeout(() => {
this.retryTimeouts.delete(task.id);
void this.startPendingTask(task);
}, delay);
this.retryTimeouts.set(task.id, timeoutId);
}
insertPlaceholder(editor, placeholder) {
editor.replaceSelection(`${placeholder}
`);
}
async replacePlaceholder(notePath, taskId, placeholder, replacement) {
const replacedInEditor = this.replacePlaceholderInOpenEditors(notePath, taskId, placeholder, replacement);
if (replacedInEditor) {
return true;
}
const file = this.deps.app.vault.getAbstractFileByPath(notePath);
if (!(file instanceof import_obsidian2.TFile)) {
return false;
}
const content = await this.deps.app.vault.read(file);
if (content.includes(placeholder)) {
const updated = content.replace(placeholder, replacement);
if (updated !== content) {
await this.deps.app.vault.modify(file, updated);
return true;
}
}
const pattern = new RegExp(
`<span[^>]*data-secure-webdav-task="${this.deps.escapeRegExp(taskId)}"[^>]*>.*?<\\/span>`,
"s"
);
if (pattern.test(content)) {
const updated = content.replace(pattern, replacement);
if (updated !== content) {
await this.deps.app.vault.modify(file, updated);
return true;
}
}
return false;
}
replacePlaceholderInOpenEditors(notePath, taskId, placeholder, replacement) {
let replaced = false;
const leaves = this.deps.app.workspace.getLeavesOfType("markdown");
for (const leaf of leaves) {
const view = leaf.view;
if (!(view instanceof import_obsidian2.MarkdownView)) {
continue;
}
if (!view.file || view.file.path !== notePath) {
continue;
}
const editor = view.editor;
const content = editor.getValue();
let updated = content;
if (content.includes(placeholder)) {
updated = content.replace(placeholder, replacement);
} else {
const pattern = new RegExp(
`<span[^>]*data-secure-webdav-task="${this.deps.escapeRegExp(taskId)}"[^>]*>.*?<\\/span>`,
"s"
);
updated = content.replace(pattern, replacement);
}
if (updated !== content) {
editor.setValue(updated);
replaced = true;
}
}
return replaced;
}
};
// secure-webdav-sync-support.ts
var import_obsidian3 = require("obsidian");
var SecureWebdavSyncSupport = class {
constructor(deps) {
this.deps = deps;
}
isExcludedSyncPath(path) {
const normalizedPath = (0, import_obsidian3.normalizePath)(path).replace(/^\/+/, "").replace(/\/+$/, "");
if (!normalizedPath) {
return false;
}
const folders = this.deps.getExcludedSyncFolders?.() ?? [];
return folders.some((folder) => {
const normalizedFolder = (0, import_obsidian3.normalizePath)(folder).replace(/^\/+/, "").replace(/\/+$/, "");
return normalizedFolder.length > 0 && (normalizedPath === normalizedFolder || normalizedPath.startsWith(`${normalizedFolder}/`));
});
}
shouldSkipContentSyncPath(path) {
const normalizedPath = (0, import_obsidian3.normalizePath)(path);
if (this.isExcludedSyncPath(normalizedPath) || normalizedPath.startsWith(".obsidian/") || normalizedPath.startsWith(".trash/") || normalizedPath.startsWith(".git/") || normalizedPath.startsWith("node_modules/") || normalizedPath.startsWith("_plugin_packages/") || normalizedPath.startsWith(".tmp-") || normalizedPath.startsWith(".obsidian/plugins/secure-webdav-images/") || normalizedPath.includes(".sync-conflict-")) {
return true;
}
return /\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(normalizedPath);
}
shouldSkipDirectorySyncPath(dirPath) {
const p = (0, import_obsidian3.normalizePath)(dirPath);
return this.isExcludedSyncPath(p) || p.startsWith(".obsidian") || p.startsWith(".trash") || p.startsWith(".git") || p.startsWith("node_modules") || p.startsWith("_plugin_packages") || p.startsWith(".tmp-");
}
collectLocalSyncedDirectories() {
const dirs = /* @__PURE__ */ new Set();
for (const f of this.deps.app.vault.getAllFolders()) {
if (f instanceof import_obsidian3.TFolder && !f.isRoot() && !this.shouldSkipDirectorySyncPath(f.path)) {
dirs.add((0, import_obsidian3.normalizePath)(f.path));
}
}
return dirs;
}
collectVaultContentFiles() {
return this.deps.app.vault.getFiles().filter((file) => !this.shouldSkipContentSyncPath(file.path)).sort((a, b) => a.path.localeCompare(b.path));
}
buildSyncSignature(file) {
return `${file.stat.mtime}:${file.stat.size}`;
}
buildRemoteSyncSignature(remote) {
return `${remote.lastModified}:${remote.size}`;
}
isLegacySignature(sig) {
if (typeof sig !== "string" || !sig) return true;
const parts = sig.split(":");
if (parts.length === 2 && parts.every((p) => /^\d+$/.test(p))) return false;
if (parts.length === 3 && /^\d+$/.test(parts[0]) && /^\d+$/.test(parts[1]) && /^[a-f0-9]{16}$/.test(parts[2])) return false;
return true;
}
buildVaultSyncRemotePath(vaultPath) {
return `${this.normalizeFolder(this.deps.getVaultSyncRemoteFolder())}${vaultPath}`;
}
buildRemoteEventFolder() {
return `${this.normalizeFolder(this.deps.getVaultSyncRemoteFolder()).replace(/\/$/, "")}${this.deps.eventFolderSuffix}`;
}
remotePathToVaultPath(remotePath) {
const root = this.normalizeFolder(this.deps.getVaultSyncRemoteFolder());
if (!remotePath.startsWith(root)) {
return null;
}
return remotePath.slice(root.length).replace(/^\/+/, "");
}
normalizeFolder(input) {
return normalizeFolder(input);
}
};
function normalizeFolder(input) {
return input.replace(/^\/+/, "").replace(/\/+$/, "") + "/";
}
// main.ts
var DEFAULT_SETTINGS = {
webdavUrl: "",
username: "",
password: "",
remoteFolder: "/remote-images/",
vaultSyncRemoteFolder: "/vault-sync/",
excludedSyncFolders: ["kb"],
namingStrategy: "hash",
language: "auto",
autoSyncIntervalMinutes: 0,
maxRetryAttempts: 5,
retryDelaySeconds: 5,
compressImages: true,
compressThresholdKb: 300,
maxImageDimension: 2200,
jpegQuality: 82,
autoUpdateCheckIntervalHours: 24
};
var MIME_MAP = {
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
gif: "image/gif",
webp: "image/webp",
svg: "image/svg+xml",
bmp: "image/bmp",
"image/jpeg": "jpg",
"image/png": "png",
"image/gif": "gif",
"image/webp": "webp",
"image/bmp": "bmp",
"image/svg+xml": "svg"
};
// ── v2.0.0 Entity / MixedEntity data models ──
// Entity: a file's state snapshot at one point in time
class SyncEntity {
constructor(opts = {}) {
this.key = opts.key ?? ""; // vaultPath
this.mtimeCli = opts.mtimeCli ?? 0; // local mtime (ms)
this.mtimeSvr = opts.mtimeSvr ?? 0; // remote Last-Modified (ms)
this.size = opts.size ?? 0; // file size (bytes)
this.hash = opts.hash ?? ""; // SHA-256 first 16 hex chars (content-based)
this.remotePath = opts.remotePath ?? ""; // WebDAV path
this.syncTime = opts.syncTime ?? 0; // timestamp when this snapshot was recorded
}
signature() {
if (this.hash) return `${this.mtimeCli}:${this.size}:${this.hash}`;
return `${this.mtimeCli}:${this.size}`;
}
}
// 4-bit state enum for the decision matrix
const LOCAL_UNCHANGED = 0, LOCAL_MODIFIED = 1, LOCAL_DELETED = 2, LOCAL_NEW = 3;
const REMOTE_UNCHANGED = 0, REMOTE_MODIFIED = 1, REMOTE_DELETED = 2, REMOTE_NEW = 3;
// MixedEntity: merged three-way view for one file path
class MixedEntity {
constructor(key) {
this.key = key; // vaultPath
this.local = null; // SyncEntity | null
this.prevSync = null; // SyncEntity | null (from localforage)
this.remote = null; // SyncEntity | null
this.decision = "skip"; // skip | pull | push | deleteLocal | deleteRemote | conflict | cleanHistory
this.decisionBranch = 0; // 0-15 (localState<<2 | remoteState)
}
}
// Determine local state relative to prevSync record
function classifyLocalState(local, prevSync) {
if (!prevSync) {
return local ? LOCAL_NEW : LOCAL_UNCHANGED;
}
if (!local) {
return LOCAL_DELETED;
}
const localSig = local.signature();
const prevSig = prevSync.signature();
if (localSig === prevSig) return LOCAL_UNCHANGED;
// If prevSync lacks a content hash (stored from a pull where we only know
// server mtime+size), compare only mtime:size so a freshly-downloaded file
// isn't falsely flagged as locally modified.
const prevParts = prevSig.split(":");
if (prevParts.length === 2 && /^\d+$/.test(prevParts[0]) && /^\d+$/.test(prevParts[1])) {
const localTrimmed = localSig.split(":").slice(0, 2).join(":");
if (localTrimmed === prevSig) return LOCAL_UNCHANGED;
}
return LOCAL_MODIFIED;
}
// Determine remote state relative to prevSync record
function classifyRemoteState(remote, prevSync) {
if (!prevSync) {
return remote ? REMOTE_NEW : REMOTE_UNCHANGED;
}
if (!remote) {
return REMOTE_DELETED;
}
// Remote entities (from PROPFIND) never carry a content hash.
// Use mtimeSvr (server-confirmed mtime) when available; otherwise
// fall back to mtimeCli from prevSync.
const remoteSig = remote.signature();
const prevMtime = prevSync.mtimeSvr || prevSync.mtimeCli;
const prevSigForRemote = `${prevMtime}:${prevSync.size}`;
if (remoteSig !== prevSigForRemote) {
return REMOTE_MODIFIED;
}
return REMOTE_UNCHANGED;
}
function parseStoredSyncSignature(sig) {
if (typeof sig !== "string" || !sig) {
return { mtime: 0, size: 0, hash: "", valid: false };
}
const parts = sig.split(":");
if (parts.length !== 2 && parts.length !== 3) {
return { mtime: 0, size: 0, hash: "", valid: false };
}
const mtime = Number(parts[0]);
const size = Number(parts[1]);
if (!Number.isFinite(mtime) || !Number.isFinite(size)) {
return { mtime: 0, size: 0, hash: "", valid: false };
}
const hash = parts.length === 3 ? parts[2] : "";
return { mtime, size, hash, valid: true };
}
// 4×4 decision matrix (based on remotely-save V3)
//
// remote: unchanged modified deleted new
// local unchanged: skip pull deleteLocal pull
// local modified: push conflict push conflict
// local deleted: deleteRemote pull cleanHistory skip-or-pull
// local new: push conflict push conflict
//
// * [unchanged, deleted]: file in prevSync but not on remote → deleteLocal.
// Three-way comparison gives us confidence the deletion is authoritative.
//
// Extra rules:
// - conflict + local.hash === remote.hash → skip (content identical)
// - conflict + remote.hash matches another local file → skip (content dedup)
function computeDecision(mixed, localContentIndex = null) {
const localState = classifyLocalState(mixed.local, mixed.prevSync);
const remoteState = classifyRemoteState(mixed.remote, mixed.prevSync);
mixed.decisionBranch = (localState << 2) | remoteState;
if (localState === LOCAL_UNCHANGED) {
if (remoteState === REMOTE_UNCHANGED) { mixed.decision = "skip"; }
else if (remoteState === REMOTE_MODIFIED) { mixed.decision = "pull"; }
else if (remoteState === REMOTE_DELETED) { mixed.decision = "deleteLocal"; }
else if (remoteState === REMOTE_NEW) { mixed.decision = "pull"; }
} else if (localState === LOCAL_MODIFIED) {
if (remoteState === REMOTE_UNCHANGED) { mixed.decision = "push"; }
else if (remoteState === REMOTE_MODIFIED) { mixed.decision = "conflict"; }
else if (remoteState === REMOTE_DELETED) { mixed.decision = "push"; }
else if (remoteState === REMOTE_NEW) { mixed.decision = "conflict"; }
} else if (localState === LOCAL_DELETED) {
if (remoteState === REMOTE_UNCHANGED) { mixed.decision = "deleteRemote"; }
else if (remoteState === REMOTE_MODIFIED) { mixed.decision = "pull"; }
else if (remoteState === REMOTE_DELETED) { mixed.decision = "cleanHistory"; }
else if (remoteState === REMOTE_NEW) {
// Local deleted, remote new — could be a rename from another path, or a genuine new file
mixed.decision = "pull";
}
} else if (localState === LOCAL_NEW) {
if (remoteState === REMOTE_UNCHANGED) { mixed.decision = "push"; }
else if (remoteState === REMOTE_MODIFIED) { mixed.decision = "conflict"; }
else if (remoteState === REMOTE_DELETED) { mixed.decision = "push"; }
else if (remoteState === REMOTE_NEW) { mixed.decision = "conflict"; }
}
// Content-based conflict resolution
if (mixed.decision === "conflict" && mixed.local && mixed.remote) {
// Same content hash → no real conflict
if (mixed.local.hash && mixed.remote.hash && mixed.local.hash === mixed.remote.hash) {
mixed.decision = "skip";
}
// Remote content matches another local file → content-aware dedup
else if (localContentIndex && mixed.remote.hash) {
const matchingPaths = localContentIndex.get(mixed.remote.hash);
if (matchingPaths && matchingPaths.size > 0) {
// Remote content exists locally at another path → skip, let that path handle it
mixed.decision = "skip";
}
}
}
return mixed;
}
var SecureWebdavImagesPlugin = class extends import_obsidian4.Plugin {
constructor() {
super(...arguments);
this.settings = DEFAULT_SETTINGS;
this.queue = [];
this.blobUrls = /* @__PURE__ */ new Set();
this.maxBlobUrls = 100;
this.noteRemoteRefs = /* @__PURE__ */ new Map();
this.syncIndex = /* @__PURE__ */ new Map();
this.syncedDirectories = /* @__PURE__ */ new Set();
this.pendingVaultSyncPaths = /* @__PURE__ */ new Set();
this.pendingVaultDeletionPaths = /* @__PURE__ */ new Map();
this.pendingVaultRenamePaths = /* @__PURE__ */ new Map();
this.pendingVaultMutationPromises = /* @__PURE__ */ new Set();
this.lastVaultSyncAt = 0;
this.lastVaultSyncStatus = "";
this.syncInProgress = false;
this.autoSyncTickInProgress = false;
this.eventFolderSuffix = ".__secure-webdav-events__/";
this.clientId = "";
this.recentVaultMutations = [];
this.lastAutoUpdateCheckAt = 0;
this.localDB = null; // v2.0.0: localforage instance for prevSyncRecords
this.localControlRoot = "";
this.localDeviceStateLoaded = false;
this.suppressedVaultEventPaths = /* @__PURE__ */ new Map();
this.autoSyncIntervalId = null;
this.autoUpdateIntervalId = null;
}
// ── v2.0.0: prevSyncRecords storage via localStorage ──
// Obsidian plugins run in Electron renderer; localStorage is available.
// We use it directly instead of localforage to avoid an external dependency
// that can't be required/imported in the single-file plugin bundle.
getLocalDB() {
if (!this._localDB) {
const PREV = "swdi_prev:";
const META = "swdi_meta:";
this._localDB = {
async getPrevSyncRecord(key) {
const v = localStorage.getItem(PREV + key);
return v ? JSON.parse(v) : null;
},
async setPrevSyncRecord(key, entity) {
localStorage.setItem(PREV + key, JSON.stringify(entity));
},
async deletePrevSyncRecord(key) {
localStorage.removeItem(PREV + key);
},
async getAllPrevSyncRecords() {
const result = new Map();
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && k.startsWith(PREV)) {
result.set(k.slice(PREV.length), JSON.parse(localStorage.getItem(k)));
}
}
return result;
},
async clearPrevSyncRecords() {
const keys = [];
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
if (k && k.startsWith(PREV)) keys.push(k);
}
keys.forEach((k) => localStorage.removeItem(k));
},
async getPluginMeta(key) {
const v = localStorage.getItem(META + key);
return v ? JSON.parse(v) : null;
},
async setPluginMeta(key, value) {
localStorage.setItem(META + key, JSON.stringify(value));
},
async deletePluginMeta(key) {
localStorage.removeItem(META + key);
},
};
}
return this._localDB;
}
initializeSupportModules() {
this.imageSupport = new SecureWebdavImageSupport({
t: this.t.bind(this),
fetchSecureImageBlobUrl: this.fetchSecureImageBlobUrl.bind(this)
});
this.uploadQueue = new SecureWebdavUploadQueueSupport({
app: this.app,
t: this.t.bind(this),
settings: () => this.settings,
getQueue: () => this.queue,
setQueue: (queue) => {
this.queue = queue;
},
savePluginState: this.savePluginState.bind(this),
schedulePriorityNoteSync: this.schedulePriorityNoteSync.bind(this),
requestUrl: this.requestUrl.bind(this),
buildUploadUrl: this.buildUploadUrl.bind(this),
buildAuthHeader: this.buildAuthHeader.bind(this),
prepareUploadPayload: this.prepareUploadPayload.bind(this),
buildRemoteFileNameFromBinary: this.buildRemoteFileNameFromBinary.bind(this),
buildRemotePath: this.buildRemotePath.bind(this),
buildSecureImageMarkup: this.imageSupport.buildSecureImageMarkup.bind(this.imageSupport),
getMimeTypeFromFileName: this.getMimeTypeFromFileName.bind(this),
arrayBufferToBase64: this.arrayBufferToBase64.bind(this),
base64ToArrayBuffer: this.base64ToArrayBuffer.bind(this),
escapeHtml: this.escapeHtml.bind(this),
escapeRegExp: this.escapeRegExp.bind(this),
describeError: this.describeError.bind(this)
});
this.syncSupport = new SecureWebdavSyncSupport({
app: this.app,
getVaultSyncRemoteFolder: () => this.settings.vaultSyncRemoteFolder,
getExcludedSyncFolders: () => this.settings.excludedSyncFolders ?? []
});
}
async onload() {
await this.loadPluginState();
await this.ensureLocalControlReady();
await this.loadLocalDeviceState();
this.initializeSupportModules();
// v2.0.0: initialize localforage for prevSyncRecords
this.localDB = this.getLocalDB();
this.addSettingTab(new SecureWebdavSettingTab(this.app, this));
this.addCommand({
id: "upload-current-note-local-images",
name: this.t("上传当前笔记中的本地图片到 WebDAV", "Upload local images in current note to WebDAV"),
checkCallback: (checking) => {
const file = this.app.workspace.getActiveFile();
if (!file) {
return false;
}
if (!checking) {
void this.uploadImagesInNote(file);
}
return true;
}
});
this.addCommand({
id: "test-webdav-connection",
name: this.t("测试 WebDAV 连接", "Test WebDAV connection"),
callback: () => {
void this.runConnectionTest(true);
}
});
this.addCommand({
id: "sync-vault-content-to-webdav",
name: this.t("同步内容到 WebDAV", "Sync vault content to WebDAV"),
callback: () => {
void this.runSync();
}
});
const syncRibbon = this.addRibbonIcon("refresh-cw", this.t("\u540C\u6B65\u5230 WebDAV", "Sync to WebDAV"), () => {
void this.runSync();
});
syncRibbon.addClass("secure-webdav-sync-ribbon");
this.registerMarkdownPostProcessor((el, ctx) => {
void this.imageSupport.processSecureImages(el, ctx);
});
try {
this.registerMarkdownCodeBlockProcessor(SECURE_CODE_BLOCK, (source, el, ctx) => {
void this.imageSupport.processSecureCodeBlock(source, el, ctx);
});
} catch {
console.warn("[secure-webdav-images] code block processor already registered, skipping");
}
this.registerEvent(
this.app.workspace.on("editor-paste", (evt, editor, info) => {
void this.handleEditorPaste(evt, editor, info);
})
);
this.registerEvent(
this.app.workspace.on("editor-drop", (evt, editor, info) => {
void this.handleEditorDrop(evt, editor, info);
})
);
await this.rebuildReferenceIndex();
this.restartBackgroundSchedulers();
void this.uploadQueue.processPendingTasks();
this.register(() => {
for (const blobUrl of this.blobUrls) {
URL.revokeObjectURL(blobUrl);
}
this.blobUrls.clear();
this.uploadQueue.dispose();
});
}
onunload() {
this.stopAutoSync();
this.stopAutoUpdateCheck();
for (const blobUrl of this.blobUrls) {
URL.revokeObjectURL(blobUrl);
}
this.blobUrls.clear();
this.uploadQueue?.dispose();
}
async loadPluginState() {
const loaded = await this.loadData();
if (!loaded || typeof loaded !== "object") {
this.settings = { ...DEFAULT_SETTINGS };
this.queue = [];
this.syncIndex = /* @__PURE__ */ new Map();
this.syncedDirectories = /* @__PURE__ */ new Set();
this.pendingVaultSyncPaths = /* @__PURE__ */ new Set();
this.pendingVaultRenamePaths = /* @__PURE__ */ new Map();
this.clientId = this.generateClientId();
this.lastAutoUpdateCheckAt = 0;
return;
}
const candidate = loaded;
if ("settings" in candidate || "queue" in candidate) {
this.settings = { ...DEFAULT_SETTINGS, ...candidate.settings ?? {} };
this.queue = Array.isArray(candidate.queue) ? candidate.queue : [];
this.pendingVaultSyncPaths = new Set(
Array.isArray(candidate.pendingVaultSyncPaths) ? candidate.pendingVaultSyncPaths.filter((path) => typeof path === "string") : []
);
for (const [path, rawEntry] of Object.entries(candidate.pendingVaultDeletionPaths ?? {})) {
if (!rawEntry || typeof rawEntry !== "object") {
continue;
}
const entry = rawEntry;
const remotePath = typeof entry.remotePath === "string" && entry.remotePath.length > 0 ? entry.remotePath : `${this.normalizeFolder(this.settings.vaultSyncRemoteFolder)}${path}`;
const remoteSignature = typeof entry.remoteSignature === "string" ? entry.remoteSignature : void 0;
const creationTime = typeof entry.creationTime === "number" ? entry.creationTime : 0;
const recordedAt = typeof entry.recordedAt === "number" ? entry.recordedAt : 0;
this.pendingVaultDeletionPaths.set(path, { remotePath, remoteSignature, creationTime, recordedAt });
}
this.pendingVaultRenamePaths = /* @__PURE__ */ new Map();
for (const [oldPath, rawEntry] of Object.entries(candidate.pendingVaultRenamePaths ?? {})) {
if (!rawEntry || typeof rawEntry !== "object") {
continue;
}
const entry = rawEntry;
const newPath = typeof entry.newPath === "string" ? entry.newPath : "";
if (!newPath) {
continue;
}
const oldRemotePath = typeof entry.oldRemotePath === "string" && entry.oldRemotePath.length > 0 ? entry.oldRemotePath : `${this.normalizeFolder(this.settings.vaultSyncRemoteFolder)}${oldPath}`;
const oldRemoteSignature = typeof entry.oldRemoteSignature === "string" ? entry.oldRemoteSignature : void 0;
const recordedAt = typeof entry.recordedAt === "number" ? entry.recordedAt : Date.now();
this.pendingVaultRenamePaths.set(oldPath, {
oldPath,
newPath,
oldRemotePath,
oldRemoteSignature,
recordedAt
});
}
this.syncIndex = /* @__PURE__ */ new Map();
for (const [path, rawEntry] of Object.entries(candidate.syncIndex ?? {})) {
const normalized = this.normalizeSyncIndexEntry(path, rawEntry);
if (normalized) {
this.syncIndex.set(path, normalized);
}
}
this.lastVaultSyncAt = typeof candidate.lastVaultSyncAt === "number" ? candidate.lastVaultSyncAt : 0;
this.lastVaultSyncStatus = typeof candidate.lastVaultSyncStatus === "string" ? candidate.lastVaultSyncStatus : "";
this.syncedDirectories = new Set(
Array.isArray(candidate.syncedDirectories) ? candidate.syncedDirectories : []
);
this.clientId = typeof candidate.clientId === "string" && candidate.clientId.length > 0 ? candidate.clientId : this.generateClientId();
this.lastAutoUpdateCheckAt = typeof candidate.lastAutoUpdateCheckAt === "number" ? candidate.lastAutoUpdateCheckAt : 0;
this.normalizeEffectiveSettings();
return;
}
this.settings = { ...DEFAULT_SETTINGS, ...candidate };
this.queue = [];
this.syncIndex = /* @__PURE__ */ new Map();
this.syncedDirectories = /* @__PURE__ */ new Set();
this.pendingVaultSyncPaths = /* @__PURE__ */ new Set();
this.pendingVaultDeletionPaths = /* @__PURE__ */ new Map();
this.pendingVaultRenamePaths = /* @__PURE__ */ new Map();
this.lastVaultSyncAt = 0;
this.lastVaultSyncStatus = "";
this.clientId = this.generateClientId();
this.recentVaultMutations = [];
this.lastAutoUpdateCheckAt = 0;
this.normalizeEffectiveSettings();
}
normalizeEffectiveSettings() {
delete this.settings.deleteLocalAfterUpload;
delete this.settings.deleteRemoteWhenUnreferenced;
this.settings.autoSyncIntervalMinutes = Math.max(0, Math.floor(this.settings.autoSyncIntervalMinutes || 0));
this.settings.autoUpdateCheckIntervalHours = Math.max(0, Math.min(168, Math.floor(this.settings.autoUpdateCheckIntervalHours ?? 24)));
const rawExcluded = this.settings.excludedSyncFolders;
const excluded = Array.isArray(rawExcluded) ? rawExcluded : typeof rawExcluded === "string" ? rawExcluded.split(/[,\n]/) : DEFAULT_SETTINGS.excludedSyncFolders;
this.settings.excludedSyncFolders = [
...new Set(
excluded.map((value) => (0, import_obsidian4.normalizePath)(String(value).trim()).replace(/^\/+/, "").replace(/\/+$/, "")).filter((value) => value.length > 0)
)
];
}
normalizeFolder(input) {
return normalizeFolder(input);
}
generateClientId() {
let hostname = "unknown";
try {
const os = require("os");
hostname = os.hostname().toLowerCase().replace(/[^a-z0-9-]/g, "-");
} catch (_) {}
return `${hostname}-kim`;
}
getPluginInstallDir() {
let basePath;
try {
basePath = this.app.vault.adapter.basePath;
} catch {
basePath = this.app.vault.getRoot().vault.adapter.basePath;
}
return `${basePath}/.obsidian/plugins/${this.manifest.id}/`;
}
getRuntimePluginVersion() {
return this.manifest.version || "0.0.0";
}
readInstalledPluginVersion() {
try {
const fs = require("fs");
const path = require("path");
const manifestPath = path.join(this.getPluginInstallDir(), "manifest.json");
const raw = fs.readFileSync(manifestPath, "utf8");
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.version === "string" && parsed.version.length > 0) {
return parsed.version;
}
} catch (_) {
}
const cached = this.app.plugins?.manifests?.[this.manifest.id]?.version;
return typeof cached === "string" && cached.length > 0 ? cached : this.getRuntimePluginVersion();
}
hasPendingPluginReload() {
return this.compareSemver(this.readInstalledPluginVersion(), this.getRuntimePluginVersion()) > 0;
}