-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1189 lines (1170 loc) · 45.7 KB
/
main.js
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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
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 __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => main_default
});
module.exports = __toCommonJS(main_exports);
// src/core/main.ts
var import_obsidian7 = require("obsidian");
// src/models/settings.ts
var DEFAULT_SETTINGS = {
storageProvider: "cloudflare_worker" /* CLOUDFLARE_WORKER */,
workerSettings: {
workerUrl: "",
apiKey: "",
bucketName: "",
folderName: "",
customDomain: ""
},
enableAutoPaste: false
};
// src/services/worker-service.ts
var import_obsidian2 = require("obsidian");
var path = __toESM(require("path"));
// src/utils/logger.ts
var import_obsidian = require("obsidian");
var Logger = class _Logger {
/**
* 私有构造函数,防止直接实例化
*/
constructor() {
this.logLevel = 1 /* INFO */;
}
/**
* 获取日志实例
*/
static getInstance() {
if (!_Logger.instance) {
_Logger.instance = new _Logger();
}
return _Logger.instance;
}
/**
* 设置日志级别
*/
setLogLevel(level) {
this.logLevel = level;
}
/**
* 调试日志
*/
debug(message, ...args) {
if (this.logLevel <= 0 /* DEBUG */) {
console.debug(`[DEBUG] ${message}`, ...args);
}
}
/**
* 信息日志
*/
info(message, ...args) {
if (this.logLevel <= 1 /* INFO */) {
console.info(`[INFO] ${message}`, ...args);
}
}
/**
* 警告日志
*/
warn(message, ...args) {
if (this.logLevel <= 2 /* WARN */) {
console.warn(`[WARN] ${message}`, ...args);
}
}
/**
* 错误日志
*/
error(message, ...args) {
if (this.logLevel <= 3 /* ERROR */) {
console.error(`[ERROR] ${message}`, ...args);
}
}
/**
* 向用户显示通知
*/
notify(message, timeout = 3e3) {
new import_obsidian.Notice(message, timeout);
}
};
// src/services/worker-service.ts
var CloudflareWorkerService = class {
/**
* 构造函数
*/
constructor(settings) {
this.settings = settings;
this.logger = Logger.getInstance();
}
/**
* 获取提供者类型
*/
getType() {
return "cloudflare_worker" /* CLOUDFLARE_WORKER */;
}
/**
* 上传文件到Cloudflare Worker
*/
async uploadFile(filePath, fileContent) {
try {
const { workerUrl, apiKey, bucketName, folderName, customDomain } = this.settings.workerSettings;
if (!workerUrl || !apiKey) {
throw new Error("Worker URL\u6216API Key\u672A\u914D\u7F6E");
}
const fileName = path.basename(filePath);
const getMimeType = (fileName2) => {
const extension = path.extname(fileName2).toLowerCase().replace(".", "");
const mimeTypes = {
"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"webp": "image/webp",
"pdf": "application/pdf",
"txt": "text/plain",
"doc": "application/msword",
"docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"xls": "application/vnd.ms-excel",
"xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};
return mimeTypes[extension] || "application/octet-stream";
};
const mimeType = getMimeType(fileName);
this.logger.info(`\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B: ${mimeType}, \u6587\u4EF6\u540D: ${fileName}`);
const formData = new FormData();
const blob = new Blob([fileContent], { type: mimeType });
formData.append("file", blob, fileName);
if (folderName) {
formData.append("folder", folderName);
}
this.logger.info(`\u5F00\u59CB\u4E0A\u4F20\u6587\u4EF6\u5230Worker: ${fileName}`);
const response = await fetch(workerUrl + `/api/v1/buckets/${bucketName}/files`, {
method: "POST",
headers: {
"Authorization": `Bearer ${apiKey}`
},
body: formData
});
const json = await response.json();
if (response.ok && json.success) {
if (json.path) {
const fileIdentifier = json.path;
let imageUrl;
if (customDomain && customDomain.trim() !== "") {
const domainBase = customDomain.startsWith("http") ? customDomain : `https://${customDomain}`;
const formattedDomain = domainBase.endsWith("/") ? domainBase : `${domainBase}/`;
imageUrl = `${formattedDomain}${fileIdentifier.startsWith("/") ? fileIdentifier.substring(1) : fileIdentifier}`;
} else {
const baseUrl = new URL(workerUrl);
imageUrl = `${baseUrl.origin}/${fileIdentifier.startsWith("/") ? fileIdentifier.substring(1) : fileIdentifier}`;
}
this.logger.info(`\u6587\u4EF6\u4E0A\u4F20\u6210\u529F: ${fileName}, URL: ${imageUrl}`);
return {
success: true,
localPath: filePath,
imageId: imageUrl
};
} else {
this.logger.error(`\u4E0A\u4F20\u6587\u4EF6\u6210\u529F\u4F46\u7F3A\u5C11URL\u4FE1\u606F: ${fileName}`);
new import_obsidian2.Notice(`\u4E0A\u4F20\u6587\u4EF6\u6210\u529F\u4F46\u7F3A\u5C11URL\u4FE1\u606F: ${fileName}`, 3e3);
return {
success: false,
localPath: filePath,
error: "\u4E0A\u4F20\u6210\u529F\u4F46\u65E0\u6CD5\u83B7\u53D6URL"
};
}
} else {
const errorMessage = json.error || "\u672A\u77E5\u9519\u8BEF";
this.logger.error(`\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25 ${filePath}: ${errorMessage}`);
new import_obsidian2.Notice(`\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25: ${fileName}`, 3e3);
return {
success: false,
localPath: filePath,
error: errorMessage
};
}
} catch (error) {
this.logger.error(`\u5904\u7406\u6587\u4EF6\u65F6\u51FA\u9519 ${filePath}:`, error);
new import_obsidian2.Notice(`\u5904\u7406\u6587\u4EF6\u51FA\u9519: ${path.basename(filePath)}`, 3e3);
return {
success: false,
localPath: filePath,
error: error.message
};
}
}
/**
* 获取文件URL
* 由于构建的imageId已经是完整URL,所以直接返回
*/
getFileUrl(imageId) {
return imageId;
}
};
// src/services/image-service.ts
var import_obsidian3 = require("obsidian");
var path2 = __toESM(require("path"));
var ImageService = class {
/**
* 构造函数
*/
constructor(app, storageProvider) {
this.app = app;
this.storageProvider = storageProvider;
this.retryConfig = {
maxRetries: 3,
delayMs: 1e3
};
this.logger = Logger.getInstance();
}
/**
* 解析图片路径
*/
resolveAbsolutePath(notePath, imagePath) {
if (imagePath.startsWith("/")) {
return imagePath.substring(1);
} else {
const noteDir = path2.dirname(notePath);
return path2.join(noteDir, imagePath);
}
}
/**
* 延迟函数 - 用于重试间隔
*/
delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* 带重试机制的上传单个图片
*/
async uploadImageWithRetry(imagePath, fileContent, retryCount = 0) {
try {
const result = await this.storageProvider.uploadFile(imagePath, fileContent);
if (result.success && result.imageId) {
const imageUrl = this.storageProvider.getFileUrl(result.imageId);
return { success: true, imageUrl };
} else {
if (retryCount >= this.retryConfig.maxRetries) {
this.logger.warn(`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${imagePath}`);
return { success: false };
}
this.logger.info(`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25\uFF0C\u5C06\u8FDB\u884C\u7B2C ${retryCount + 1} \u6B21\u91CD\u8BD5: ${imagePath}`);
await this.delay(this.retryConfig.delayMs);
return this.uploadImageWithRetry(imagePath, fileContent, retryCount + 1);
}
} catch (error) {
if (retryCount >= this.retryConfig.maxRetries) {
this.logger.error(`\u56FE\u7247\u4E0A\u4F20\u51FA\u9519\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${imagePath}`, error);
return { success: false };
}
this.logger.info(`\u56FE\u7247\u4E0A\u4F20\u51FA\u9519\uFF0C\u5C06\u8FDB\u884C\u7B2C ${retryCount + 1} \u6B21\u91CD\u8BD5: ${imagePath}`);
await this.delay(this.retryConfig.delayMs);
return this.uploadImageWithRetry(imagePath, fileContent, retryCount + 1);
}
}
/**
* 查找笔记中的图片
*/
async findImagesToUpload() {
const markdownFiles = this.app.vault.getMarkdownFiles();
const imagePathsToUpload = /* @__PURE__ */ new Set();
for (const file of markdownFiles) {
const content = await this.app.vault.cachedRead(file);
const regex = /!\[([^\]]*)\]\(([^)]*)\)/g;
let match;
while ((match = regex.exec(content)) !== null) {
const imagePath = match[2];
if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
continue;
}
const absolutePath = this.resolveAbsolutePath(file.path, imagePath);
if (await this.app.vault.adapter.exists(absolutePath)) {
imagePathsToUpload.add(absolutePath);
} else {
this.logger.warn(`\u56FE\u7247\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${absolutePath}`);
}
}
}
return imagePathsToUpload;
}
/**
* 上传图片到存储服务
*/
async uploadImages(paths) {
if (paths.length === 0) {
return {};
}
const uploadResults = {};
let successCount = 0;
let failCount = 0;
let currentIndex = 0;
const totalImages = paths.length;
const updateProgress = () => {
const percentage = Math.round(currentIndex / totalImages * 100);
new import_obsidian3.Notice(`\u4E0A\u4F20\u8FDB\u5EA6: ${percentage}% (${currentIndex}/${totalImages})`, 1e3);
};
updateProgress();
for (const imagePath of paths) {
try {
currentIndex++;
const fileContent = await this.app.vault.adapter.readBinary(imagePath);
const result = await this.uploadImageWithRetry(imagePath, fileContent);
if (result.success && result.imageUrl) {
uploadResults[imagePath] = result.imageUrl;
successCount++;
} else {
failCount++;
}
if (currentIndex % Math.max(1, Math.floor(totalImages / 10)) === 0 || currentIndex === totalImages) {
updateProgress();
}
} catch (error) {
this.logger.error(`\u5904\u7406\u56FE\u7247\u65F6\u51FA\u9519 ${imagePath}:`, error);
new import_obsidian3.Notice(`\u5904\u7406\u56FE\u7247\u51FA\u9519: ${path2.basename(imagePath)}`, 3e3);
failCount++;
currentIndex++;
}
}
if (successCount > 0) {
new import_obsidian3.Notice(`\u6210\u529F\u4E0A\u4F20 ${successCount} \u5F20\u56FE\u7247`, 3e3);
}
if (failCount > 0) {
new import_obsidian3.Notice(`\u6709 ${failCount} \u5F20\u56FE\u7247\u4E0A\u4F20\u5931\u8D25`, 3e3);
}
return uploadResults;
}
/**
* 更新笔记中的图片链接
*/
async updateNotes(uploadResults) {
const markdownFiles = this.app.vault.getMarkdownFiles();
let updatedCount = 0;
for (const file of markdownFiles) {
let content = await this.app.vault.cachedRead(file);
let modified = false;
const regex = /!\[([^\]]*)\]\(([^)]*)\)/g;
let match;
let lastIndex = 0;
let newContent = "";
while ((match = regex.exec(content)) !== null) {
const fullMatch = match[0];
const altText = match[1];
const imagePath = match[2];
if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
continue;
}
const absolutePath = this.resolveAbsolutePath(file.path, imagePath);
if (uploadResults[absolutePath]) {
const newImageUrl = uploadResults[absolutePath];
newContent += content.substring(lastIndex, match.index);
newContent += ``;
lastIndex = match.index + fullMatch.length;
modified = true;
}
}
if (modified) {
newContent += content.substring(lastIndex);
await this.app.vault.modify(file, newContent);
updatedCount++;
}
}
if (updatedCount > 0) {
new import_obsidian3.Notice(`\u5DF2\u66F4\u65B0 ${updatedCount} \u4E2A\u7B14\u8BB0\u6587\u4EF6`, 3e3);
}
}
};
// src/services/paste-handler.ts
var import_obsidian4 = require("obsidian");
// node_modules/uuid/dist/esm-browser/stringify.js
var byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
// node_modules/uuid/dist/esm-browser/rng.js
var getRandomValues;
var rnds8 = new Uint8Array(16);
function rng() {
if (!getRandomValues) {
if (typeof crypto === "undefined" || !crypto.getRandomValues) {
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
}
getRandomValues = crypto.getRandomValues.bind(crypto);
}
return getRandomValues(rnds8);
}
// node_modules/uuid/dist/esm-browser/native.js
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
var native_default = { randomUUID };
// node_modules/uuid/dist/esm-browser/v4.js
function v4(options, buf, offset) {
if (native_default.randomUUID && !buf && !options) {
return native_default.randomUUID();
}
options = options || {};
const rnds = options.random ?? options.rng?.() ?? rng();
if (rnds.length < 16) {
throw new Error("Random bytes length must be >= 16");
}
rnds[6] = rnds[6] & 15 | 64;
rnds[8] = rnds[8] & 63 | 128;
if (buf) {
offset = offset || 0;
if (offset < 0 || offset + 16 > buf.length) {
throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
}
for (let i = 0; i < 16; ++i) {
buf[offset + i] = rnds[i];
}
return buf;
}
return unsafeStringify(rnds);
}
var v4_default = v4;
// src/services/paste-handler.ts
var PasteHandler = class {
/**
* 构造函数
*/
constructor(app, storageProvider, plugin) {
this.app = app;
this.storageProvider = storageProvider;
this.plugin = plugin;
this.eventRefs = [];
this.logger = Logger.getInstance();
this.handlePasteEvent = this.handlePasteEvent.bind(this);
}
/**
* 注册粘贴事件处理
*/
registerPasteEvent() {
this.unregisterPasteEvent();
try {
const handler = this.handlePasteEvent;
const eventName = "editor-paste";
const eventRef = this.app.workspace.on(eventName, handler);
this.plugin.registerEvent(eventRef);
this.eventRefs.push(eventRef);
this.logger.info("\u5DF2\u6CE8\u518C\u7C98\u8D34\u4E8B\u4EF6\u5904\u7406");
} catch (error) {
this.logger.error("\u6CE8\u518C\u7C98\u8D34\u4E8B\u4EF6\u5931\u8D25", error);
}
}
/**
* 取消注册粘贴事件
*/
unregisterPasteEvent() {
this.eventRefs.forEach((ref) => {
if (ref) {
this.app.workspace.offref(ref);
}
});
this.eventRefs = [];
this.logger.info("\u5DF2\u53D6\u6D88\u6CE8\u518C\u7C98\u8D34\u4E8B\u4EF6");
}
/**
* 处理粘贴事件
*/
async handlePasteEvent(evt, editor, view) {
if (!evt.clipboardData || !evt.clipboardData.items) {
return;
}
const items = evt.clipboardData.items;
let hasImages = false;
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (!item.type.startsWith("image/")) {
continue;
}
hasImages = true;
const file = item.getAsFile();
if (!file) {
continue;
}
await this.processImageUpload(file, editor, item.type);
}
if (hasImages) {
evt.preventDefault();
}
}
/**
* 处理图片上传
*/
async processImageUpload(file, editor, mimeType) {
try {
this.logger.info("\u5F00\u59CB\u4E0A\u4F20\u7C98\u8D34\u7684\u56FE\u7247...");
new import_obsidian4.Notice("\u6B63\u5728\u4E0A\u4F20\u56FE\u7247...", 2e3);
const ext = this.getExtensionFromMime(mimeType);
const filename = `pasted-image-${v4_default()}${ext}`;
const arrayBuffer = await file.arrayBuffer();
const placeholder = ``;
const cursor = editor.getCursor();
editor.replaceSelection(placeholder);
const result = await this.storageProvider.uploadFile(filename, arrayBuffer);
if (result.success && result.imageId) {
const imageUrl = this.storageProvider.getFileUrl(result.imageId);
const markdownText = ``;
const content = editor.getValue();
const newContent = content.replace(placeholder, markdownText);
editor.setValue(newContent);
editor.setCursor(cursor);
this.logger.info(`\u7C98\u8D34\u56FE\u7247\u4E0A\u4F20\u6210\u529F: ${filename}`);
new import_obsidian4.Notice("\u56FE\u7247\u4E0A\u4F20\u6210\u529F!", 2e3);
} else {
this.logger.error(`\u7C98\u8D34\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${filename}`, result.error);
new import_obsidian4.Notice(`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25: ${result.error}`, 5e3);
}
} catch (error) {
this.logger.error("\u5904\u7406\u7C98\u8D34\u56FE\u7247\u65F6\u51FA\u9519", error);
new import_obsidian4.Notice("\u5904\u7406\u7C98\u8D34\u56FE\u7247\u65F6\u51FA\u9519: " + error.message, 5e3);
}
}
/**
* 从MIME类型获取文件扩展名
*/
getExtensionFromMime(mime) {
const mimeMap = {
"image/png": ".png",
"image/jpeg": ".jpg",
"image/jpg": ".jpg",
"image/gif": ".gif",
"image/webp": ".webp",
"image/bmp": ".bmp",
"image/svg+xml": ".svg"
};
return mimeMap[mime] || ".png";
}
/**
* 调试方法:检查服务是否正常运行
*/
debugStatus() {
console.log("PasteHandler\u72B6\u6001\u68C0\u67E5:");
console.log("- \u4E8B\u4EF6\u5F15\u7528\u6570\u91CF:", this.eventRefs.length);
console.log("- \u5B58\u50A8\u63D0\u4F9B\u8005:", this.storageProvider ? "\u5DF2\u52A0\u8F7D" : "\u672A\u52A0\u8F7D");
new import_obsidian4.Notice("PasteHandler\u72B6\u6001\u68C0\u67E5\u5B8C\u6210\uFF0C\u8BF7\u67E5\u770B\u63A7\u5236\u53F0", 3e3);
this.logger.info("\u6267\u884C\u4E86\u72B6\u6001\u68C0\u67E5");
}
};
// src/services/current-file-uploader.ts
var import_obsidian5 = require("obsidian");
var path3 = __toESM(require("path"));
var CurrentFileUploader = class {
/**
* 构造函数
*/
constructor(app, storageProvider) {
this.app = app;
this.storageProvider = storageProvider;
this.retryConfig = {
maxRetries: 3,
delayMs: 1e3
};
this.logger = Logger.getInstance();
}
/**
* 处理当前活动文件中的图片
* @returns 处理结果,包含图片总数、成功数、失败数和新的映射记录
*/
async processCurrentFile() {
const activeFile = this.app.workspace.getActiveFile();
if (!activeFile || activeFile.extension !== "md") {
new import_obsidian5.Notice("\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A Markdown \u7B14\u8BB0\u6587\u4EF6", 3e3);
return null;
}
try {
this.logger.info(`\u5F00\u59CB\u5904\u7406\u5F53\u524D\u7B14\u8BB0\u6587\u4EF6\uFF1A${activeFile.path}`);
new import_obsidian5.Notice(`\u5F00\u59CB\u5904\u7406\u7B14\u8BB0\u6587\u4EF6\uFF1A${activeFile.basename}`, 2e3);
const imagesToUpload = await this.findImagesInFile(activeFile);
if (imagesToUpload.size === 0) {
this.logger.info("\u5F53\u524D\u7B14\u8BB0\u4E2D\u6CA1\u6709\u9700\u8981\u4E0A\u4F20\u7684\u56FE\u7247");
new import_obsidian5.Notice("\u5F53\u524D\u7B14\u8BB0\u4E2D\u6CA1\u6709\u627E\u5230\u9700\u8981\u4E0A\u4F20\u7684\u56FE\u7247", 3e3);
return {
totalImages: 0,
successCount: 0,
failureCount: 0,
newMappings: {}
};
}
this.logger.info(`\u627E\u5230 ${imagesToUpload.size} \u5F20\u56FE\u7247\u9700\u8981\u4E0A\u4F20.`);
this.logger.info("\u56FE\u7247\u5730\u5740\u5217\u8868:");
Array.from(imagesToUpload).forEach((imagePath, index) => {
this.logger.info(`[${index + 1}] ${imagePath}`);
});
new import_obsidian5.Notice(`\u627E\u5230 ${imagesToUpload.size} \u5F20\u56FE\u7247\u9700\u8981\u4E0A\u4F20`, 2e3);
const { newMappings, successCount, failCount } = await this.uploadImages(Array.from(imagesToUpload));
await this.updateFileLinks(activeFile, newMappings);
this.logger.info("\u5F53\u524D\u7B14\u8BB0\u56FE\u7247\u5904\u7406\u5B8C\u6210");
return {
totalImages: imagesToUpload.size,
successCount,
failureCount: failCount,
newMappings
};
} catch (error) {
this.logger.error("\u5904\u7406\u5F53\u524D\u7B14\u8BB0\u56FE\u7247\u65F6\u51FA\u9519", error);
new import_obsidian5.Notice(`\u5904\u7406\u56FE\u7247\u65F6\u51FA\u9519: ${error.message}`, 5e3);
return null;
}
}
/**
* 在文件中查找需要上传的图片
*/
async findImagesInFile(file) {
const imagePathsToUpload = /* @__PURE__ */ new Set();
const tmpImgPaths = /* @__PURE__ */ new Set();
const content = await this.app.vault.cachedRead(file);
const standardRegex = /!\[([^\]]*)\]\(([^)]*)\)/g;
let standardMatch;
while ((standardMatch = standardRegex.exec(content)) !== null) {
const imagePath = standardMatch[2];
if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
continue;
}
tmpImgPaths.add(imagePath);
}
const obsidianRegex = /!\[\[([^\]]+)\]\]/g;
let obsidianMatch;
while ((obsidianMatch = obsidianRegex.exec(content)) !== null) {
const imagePath = obsidianMatch[1];
tmpImgPaths.add(imagePath);
}
for (const imagePath of tmpImgPaths) {
let absolutePath = await this.resolveAbsolutePath(file.path, imagePath);
if (absolutePath === "") {
this.logger.warn(`\u65E0\u6CD5\u89E3\u6790\u56FE\u7247\u8DEF\u5F84: ${imagePath}`);
continue;
}
imagePathsToUpload.add(absolutePath);
this.logger.info(`\u627E\u5230\u56FE\u7247\uFF1A${absolutePath}`);
}
return imagePathsToUpload;
}
/**
* 延迟函数 - 用于重试间隔
*/
delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* 带重试机制的上传单个图片
*/
async uploadImageWithRetry(imagePath, fileContent, retryCount = 0) {
try {
const result = await this.storageProvider.uploadFile(imagePath, fileContent);
if (result.success && result.imageId) {
const imageUrl = this.storageProvider.getFileUrl(result.imageId);
return { success: true, imageUrl };
} else {
if (retryCount >= this.retryConfig.maxRetries) {
this.logger.warn(`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${imagePath}`);
return { success: false };
}
this.logger.info(`\u56FE\u7247\u4E0A\u4F20\u5931\u8D25\uFF0C\u5C06\u8FDB\u884C\u7B2C ${retryCount + 1} \u6B21\u91CD\u8BD5: ${imagePath}`);
await this.delay(this.retryConfig.delayMs);
return this.uploadImageWithRetry(imagePath, fileContent, retryCount + 1);
}
} catch (error) {
if (retryCount >= this.retryConfig.maxRetries) {
this.logger.error(`\u56FE\u7247\u4E0A\u4F20\u51FA\u9519\uFF0C\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570: ${imagePath}`, error);
return { success: false };
}
this.logger.info(`\u56FE\u7247\u4E0A\u4F20\u51FA\u9519\uFF0C\u5C06\u8FDB\u884C\u7B2C ${retryCount + 1} \u6B21\u91CD\u8BD5: ${imagePath}`);
await this.delay(this.retryConfig.delayMs);
return this.uploadImageWithRetry(imagePath, fileContent, retryCount + 1);
}
}
/**
* 上传图片到存储服务
*/
async uploadImages(paths) {
if (paths.length === 0) {
return { newMappings: {}, successCount: 0, failCount: 0 };
}
const newMappings = {};
let successCount = 0;
let failCount = 0;
let currentIndex = 0;
const totalImages = paths.length;
const updateProgress = () => {
const percentage = Math.round(currentIndex / totalImages * 100);
new import_obsidian5.Notice(`\u4E0A\u4F20\u8FDB\u5EA6: ${percentage}% (${currentIndex}/${totalImages})`, 1e3);
};
updateProgress();
for (const imagePath of paths) {
try {
currentIndex++;
const fileContent = await this.app.vault.adapter.readBinary(imagePath);
const result = await this.uploadImageWithRetry(imagePath, fileContent);
if (result.success && result.imageUrl) {
newMappings[imagePath] = result.imageUrl;
successCount++;
} else {
failCount++;
}
if (currentIndex % Math.max(1, Math.floor(totalImages / 10)) === 0 || currentIndex === totalImages) {
updateProgress();
}
} catch (error) {
this.logger.error(`\u5904\u7406\u56FE\u7247\u65F6\u51FA\u9519 ${imagePath}:`, error);
new import_obsidian5.Notice(`\u5904\u7406\u56FE\u7247\u51FA\u9519: ${path3.basename(imagePath)}`, 3e3);
failCount++;
currentIndex++;
}
}
if (successCount > 0) {
new import_obsidian5.Notice(`\u6210\u529F\u4E0A\u4F20 ${successCount} \u5F20\u56FE\u7247`, 3e3);
}
if (failCount > 0) {
new import_obsidian5.Notice(`\u6709 ${failCount} \u5F20\u56FE\u7247\u4E0A\u4F20\u5931\u8D25`, 3e3);
}
return { newMappings, successCount, failCount };
}
/**
* 更新当前文件中的图片链接
*/
async updateFileLinks(file, uploadResults) {
const content = await this.app.vault.cachedRead(file);
let modified = false;
let newContent = content;
const standardRegex = /!\[([^\]]*)\]\(([^)]*)\)/g;
let standardMatch;
let lastIndex = 0;
let standardNewContent = "";
while ((standardMatch = standardRegex.exec(content)) !== null) {
const fullMatch = standardMatch[0];
const altText = standardMatch[1];
const imagePath = standardMatch[2];
if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
continue;
}
const absolutePath = await this.resolveAbsolutePath(file.path, imagePath);
if (absolutePath === "") {
this.logger.warn(`\u65E0\u6CD5\u89E3\u6790\u56FE\u7247\u8DEF\u5F84: ${imagePath}`);
continue;
}
const newImageUrl = uploadResults[absolutePath];
if (newImageUrl) {
standardNewContent += content.substring(lastIndex, standardMatch.index);
standardNewContent += ``;
lastIndex = standardMatch.index + fullMatch.length;
modified = true;
}
}
if (modified) {
standardNewContent += content.substring(lastIndex);
newContent = standardNewContent;
}
modified = false;
const obsidianRegex = /!\[\[([^\]]+)\]\]/g;
let obsidianMatch;
lastIndex = 0;
let obsidianNewContent = "";
while ((obsidianMatch = obsidianRegex.exec(newContent)) !== null) {
const fullMatch = obsidianMatch[0];
const imagePath = obsidianMatch[1];
const absolutePath = await this.resolveAbsolutePath(file.path, imagePath);
if (absolutePath === "") {
this.logger.warn(`\u65E0\u6CD5\u89E3\u6790\u56FE\u7247\u8DEF\u5F84: ${imagePath}`);
continue;
}
const newImageUrl = uploadResults[absolutePath];
if (newImageUrl) {
obsidianNewContent += newContent.substring(lastIndex, obsidianMatch.index);
obsidianNewContent += ``;
lastIndex = obsidianMatch.index + fullMatch.length;
modified = true;
}
}
if (modified) {
obsidianNewContent += newContent.substring(lastIndex);
newContent = obsidianNewContent;
}
if (newContent !== content) {
await this.app.vault.modify(file, newContent);
}
}
/**
* 将图片的相对路径解析为绝对路径
*
* 1. 如果图片路径已经是绝对路径,直接返回
* 2. 如果图片路径是相对路径,尝试从当前文件所在的目录下查找
* 3. 如果当前文件所在的目录下没有找到,尝试从 vault 根目录下查找
* 4. 如果 vault 根目录下也没有找到,返回空字符串
*
* @param filePath 当前文件的路径
* @param imagePath 图片的路径(可能是相对路径或绝对路径)
* @returns 图片的绝对路径
*/
async resolveAbsolutePath(filePath, imagePath) {
if (path3.isAbsolute(imagePath)) {
this.logger.info(`\u56FE\u7247\u8DEF\u5F84\u5DF2\u7ECF\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF1A${imagePath}`);
const exists2 = await this.app.vault.adapter.exists(imagePath);
if (exists2) {
this.logger.info(`\u627E\u5230\u56FE\u7247\uFF1A${imagePath}`);
return imagePath;
}
}
let fileDir = path3.dirname(filePath);
let absolutePath = path3.normalize(path3.join(fileDir, imagePath));
this.logger.info(`\u5C1D\u8BD5\u4ECE\u5F53\u524D\u6587\u4EF6\u6240\u5728\u7684\u76EE\u5F55\u4E0B\u67E5\u627E\u56FE\u7247\uFF1A${absolutePath}`);
let exists = await this.app.vault.adapter.exists(absolutePath);
if (exists) {
this.logger.info(`\u627E\u5230\u56FE\u7247\uFF1A${absolutePath}`);
return absolutePath;
}
let vaultPath = this.app.vault.getRoot();
absolutePath = path3.normalize(path3.join(vaultPath.path, imagePath));
this.logger.info(`\u5C1D\u8BD5\u4ECE vault \u6839\u76EE\u5F55\u4E0B\u67E5\u627E\u56FE\u7247\uFF1A${absolutePath}`);
exists = await this.app.vault.adapter.exists(absolutePath);
if (exists) {
this.logger.info(`\u627E\u5230\u56FE\u7247\uFF1A${absolutePath}`);
return absolutePath;
}
this.logger.warn(`\u56FE\u7247\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${imagePath}`);
return "";
}
};
// src/ui/settings-tab.ts
var import_obsidian6 = require("obsidian");
var wrapTextWithPasswordHide = (text) => {
const hider = text.inputEl.insertAdjacentElement(
"beforebegin",
createSpan()
);
if (!hider) {
return;
}
(0, import_obsidian6.setIcon)(hider, "eye-off");
hider.addEventListener("click", () => {
const isText = text.inputEl.getAttribute("type") === "text";
if (isText) {
(0, import_obsidian6.setIcon)(hider, "eye-off");
text.inputEl.setAttribute("type", "password");
} else {
(0, import_obsidian6.setIcon)(hider, "eye");
text.inputEl.setAttribute("type", "text");
}
text.inputEl.focus();
});
text.inputEl.setAttribute("type", "password");
return text;
};
var SettingsTab = class extends import_obsidian6.PluginSettingTab {
/**
* 构造函数
*/
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
/**
* 显示设置界面
*/
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Cloudflare \u56FE\u7247\u4E0A\u4F20\u5668\u8BBE\u7F6E" });
new import_obsidian6.Setting(containerEl).setName("\u542F\u7528\u81EA\u52A8\u7C98\u8D34\u4E0A\u4F20").setDesc("\u7C98\u8D34\u56FE\u7247\u65F6\u81EA\u52A8\u4E0A\u4F20\u5230Cloudflare\u5E76\u66FF\u6362\u4E3A\u94FE\u63A5").addToggle((toggle) => {
toggle.setValue(this.plugin.settings.enableAutoPaste).onChange(async (value) => {
this.plugin.settings.enableAutoPaste = value;
await this.plugin.saveSettings();
});
});
this.displayCloudflareWorkerSettings(containerEl);
}
/**
* 显示Cloudflare Worker设置
*/
displayCloudflareWorkerSettings(containerEl) {
containerEl.createEl("h3", { text: "Cloudflare R2 Worker \u914D\u7F6E" });
new import_obsidian6.Setting(containerEl).setName("Worker URL").setDesc("\u60A8\u90E8\u7F72\u7684 Cloudflare R2 Worker \u7684 URL").addText(
(text) => text.setPlaceholder("https://your-worker.your-subdomain.workers.dev").setValue(this.plugin.settings.workerSettings.workerUrl).onChange(async (value) => {
const domainRegex = /^https:\/\/[-a-zA-Z0-9.]+$/;
const trimmedValue = value.trim();
if (!trimmedValue) {
new import_obsidian6.Notice("Worker URL \u4E0D\u80FD\u4E3A\u7A7A");
text.setValue(this.plugin.settings.workerSettings.workerUrl);
return;
}
if (domainRegex.test(trimmedValue)) {
this.plugin.settings.workerSettings.workerUrl = trimmedValue;
await this.plugin.saveSettings();
} else {
new import_obsidian6.Notice("\u8BF7\u8F93\u5165\u6709\u6548\u7684 Worker URL \u5730\u5740\uFF0C\u4F8B\u5982: https://your-worker.your-subdomain.workers.dev");
text.setValue(this.plugin.settings.workerSettings.workerUrl);
}
})
);
new import_obsidian6.Setting(containerEl).setName("API Key").setDesc("Worker \u8BA4\u8BC1\u6240\u9700\u7684 API Key").addText((text) => {
wrapTextWithPasswordHide(text);
text.setPlaceholder("\u8F93\u5165\u60A8\u7684 API Key").setValue(this.plugin.settings.workerSettings.apiKey).onChange(async (value) => {
const apiKeyRegex = /^[a-zA-Z0-9_\-]+$/;
const trimmedValue = value.trim();
if (!trimmedValue) {
new import_obsidian6.Notice("API Key \u4E0D\u80FD\u4E3A\u7A7A");
text.setValue(this.plugin.settings.workerSettings.apiKey);
return;
}
if (apiKeyRegex.test(trimmedValue)) {
this.plugin.settings.workerSettings.apiKey = trimmedValue;
await this.plugin.saveSettings();
} else {
new import_obsidian6.Notice("\u8BF7\u8F93\u5165\u6709\u6548\u7684 API Key\uFF0C\u4EC5\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u77ED\u6A2A\u7EBF");
text.setValue(this.plugin.settings.workerSettings.apiKey);
}
});
});
new import_obsidian6.Setting(containerEl).setName("\u5B58\u50A8\u6876\u540D\u79F0").setDesc("\u4E0A\u4F20\u6587\u4EF6\u7684\u76EE\u6807\u5B58\u50A8\u6876").addText(
(text) => text.setPlaceholder("\u8F93\u5165\u60A8\u7684\u5B58\u50A8\u6876\u540D\u79F0").setValue(this.plugin.settings.workerSettings.bucketName).onChange(async (value) => {
const bucketNameRegex = /^[a-z0-9][a-z0-9\-.]{2,61}[a-z0-9]$/;
const trimmedValue = value.trim();
if (!trimmedValue) {
new import_obsidian6.Notice("\u5B58\u50A8\u6876\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A");
text.setValue(this.plugin.settings.workerSettings.bucketName);
return;
}
if (bucketNameRegex.test(trimmedValue)) {
this.plugin.settings.workerSettings.bucketName = trimmedValue;
await this.plugin.saveSettings();
} else {
new import_obsidian6.Notice("\u5B58\u50A8\u6876\u540D\u79F0\u683C\u5F0F\u65E0\u6548\uFF0C\u53EA\u80FD\u5305\u542B\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\u548C\u70B9\uFF0C\u957F\u5EA6\u5728 3-63 \u4E2A\u5B57\u7B26\u4E4B\u95F4\uFF0C\u4E14\u4E0D\u80FD\u4EE5\u8FDE\u5B57\u7B26\u6216\u70B9\u5F00\u5934\u6216\u7ED3\u5C3E");
text.setValue(this.plugin.settings.workerSettings.bucketName);
}
})
);
new import_obsidian6.Setting(containerEl).setName("\u6587\u4EF6\u5939\u540D\u79F0\uFF08\u53EF\u9009\uFF09").setDesc("\u4E0A\u4F20\u6587\u4EF6\u7684\u76EE\u6807\u6587\u4EF6\u5939\uFF0C\u5982\u4E0D\u586B\u5219\u9ED8\u8BA4\u5B58\u50A8\u5230\u5B58\u50A8\u6876\u7684\u4E00\u7EA7\u76EE\u5F55\u4E0B").addText(
(text) => text.setPlaceholder("\u8BF7\u8F93\u5165\u4E0A\u4F20\u7684\u6587\u4EF6\u5939\u540D\u79F0").setValue(this.plugin.settings.workerSettings.folderName || "").onChange(async (value) => {
const trimmedValue = value.trim();
if (!trimmedValue) {
this.plugin.settings.workerSettings.folderName = void 0;
await this.plugin.saveSettings();
return;
}
const folderNameRegex = /^[a-zA-Z0-9_\-\/]+$/;
if (folderNameRegex.test(trimmedValue)) {
this.plugin.settings.workerSettings.folderName = trimmedValue;
await this.plugin.saveSettings();
} else {
new import_obsidian6.Notice("\u6587\u4EF6\u5939\u540D\u79F0\u683C\u5F0F\u65E0\u6548\uFF0C\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u3001\u8FDE\u5B57\u7B26\u548C\u659C\u6760");
text.setValue(this.plugin.settings.workerSettings.folderName || "");
}
})
);
new import_obsidian6.Setting(containerEl).setName("R2 Bucket \u81EA\u5B9A\u4E49\u57DF\u540D\uFF08\u53EF\u9009\uFF09").setDesc("\u60A8\u4E3A R2 Bucket \u914D\u7F6E\u7684\u81EA\u5B9A\u4E49\u57DF\u540D\uFF0C\u5C06\u66FF\u4EE3\u9ED8\u8BA4\u7684 Cloudflare \u57DF\u540D").addText(