-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmain.js
More file actions
5545 lines (5509 loc) · 219 KB
/
main.js
File metadata and controls
5545 lines (5509 loc) · 219 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
/*
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 __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: () => FeishuUploaderPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian4 = require("obsidian");
// feishu-api.ts
var import_obsidian = require("obsidian");
// svg-converter.ts
var SvgConverter = class {
// 4x for better quality
/**
* 将SVG内容转换为PNG格式的base64字符串
* @param svgContent SVG文件内容
* @param options 转换选项
* @returns Promise<string> PNG格式的base64字符串
*/
static async convertSvgToPng(svgContent, options = {}) {
return new Promise((resolve, reject) => {
try {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error("\u65E0\u6CD5\u521B\u5EFACanvas\u4E0A\u4E0B\u6587");
}
const svgDimensions = this.parseSvgDimensions(svgContent);
const width = options.width || svgDimensions.width || this.DEFAULT_WIDTH;
const height = options.height || svgDimensions.height || this.DEFAULT_HEIGHT;
const scale = options.scale || this.DEFAULT_SCALE;
canvas.width = width * scale;
canvas.height = height * scale;
if (options.backgroundColor) {
ctx.fillStyle = options.backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const img = new Image();
img.onload = () => {
try {
const imgWidth = img.naturalWidth || img.width;
const imgHeight = img.naturalHeight || img.height;
const actualWidth = imgWidth > 0 ? imgWidth : width;
const actualHeight = imgHeight > 0 ? imgHeight : height;
canvas.width = actualWidth * scale;
canvas.height = actualHeight * scale;
if (options.backgroundColor) {
ctx.fillStyle = options.backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
ctx.scale(scale, scale);
ctx.drawImage(img, 0, 0, actualWidth, actualHeight);
const dataUrl = canvas.toDataURL("image/png", 1);
const base64Data = dataUrl.split(",")[1];
if (base64Data) {
resolve(base64Data);
} else {
reject(new Error("\u65E0\u6CD5\u751F\u6210PNG\u6570\u636E"));
}
} catch (error) {
reject(new Error(`\u7ED8\u5236SVG\u5230Canvas\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`));
} finally {
URL.revokeObjectURL(svgUrl);
}
};
img.onerror = () => {
reject(new Error("\u52A0\u8F7DSVG\u56FE\u7247\u5931\u8D25"));
URL.revokeObjectURL(svgUrl);
};
const svgBlob = new Blob([svgContent], { type: "image/svg+xml;charset=utf-8" });
const svgUrl = URL.createObjectURL(svgBlob);
img.src = svgUrl;
} catch (error) {
reject(new Error(`SVG\u8F6C\u6362\u521D\u59CB\u5316\u5931\u8D25: ${error instanceof Error ? error.message : String(error)}`));
}
});
}
/**
* 解析SVG内容中的尺寸信息
* @param svgContent SVG内容
* @returns 尺寸信息
*/
static parseSvgDimensions(svgContent) {
try {
const widthMatch = svgContent.match(/width\s*=\s*["']?(\d+(?:\.\d+)?)(?:px|pt|pc|mm|cm|in)?["']?/i);
const heightMatch = svgContent.match(/height\s*=\s*["']?(\d+(?:\.\d+)?)(?:px|pt|pc|mm|cm|in)?["']?/i);
let width;
let height;
if (widthMatch && widthMatch[1]) {
width = parseFloat(widthMatch[1]);
}
if (heightMatch && heightMatch[1]) {
height = parseFloat(heightMatch[1]);
}
if (!width || !height) {
const viewBoxMatch = svgContent.match(/viewBox\s*=\s*["']?([^"']*?)["']?/i);
if (viewBoxMatch && viewBoxMatch[1]) {
const viewBoxValues = viewBoxMatch[1].trim().split(/\s+/);
if (viewBoxValues.length >= 4 && viewBoxValues[2] && viewBoxValues[3]) {
const vbWidth = parseFloat(viewBoxValues[2]);
const vbHeight = parseFloat(viewBoxValues[3]);
if (!isNaN(vbWidth) && !isNaN(vbHeight)) {
width = width || vbWidth;
height = height || vbHeight;
}
}
}
}
const result = {};
if (width !== void 0 && width > 0)
result.width = width;
if (height !== void 0 && height > 0)
result.height = height;
return result;
} catch (error) {
return {};
}
}
/**
* 检查文件是否为SVG格式
* @param fileName 文件名
* @param content 文件内容(可选)
* @returns boolean
*/
static isSvgFile(fileName, content) {
const hasValidExtension = fileName.toLowerCase().endsWith(".svg");
if (content) {
const hasValidContent = content.trim().startsWith("<svg") || content.includes("<svg");
return hasValidExtension && hasValidContent;
}
return hasValidExtension;
}
/**
* 生成转换后的PNG文件名
* @param originalFileName 原始SVG文件名
* @returns PNG文件名
*/
static generatePngFileName(originalFileName) {
const baseName = originalFileName.replace(/\.svg$/i, "");
return `${baseName}_converted.png`;
}
/**
* 获取推荐的转换选项
* @param svgContent SVG内容
* @returns 推荐的转换选项
*/
static getRecommendedOptions(svgContent) {
const dimensions = this.parseSvgDimensions(svgContent);
const defaultOptions = {
width: 800,
height: 600,
scale: 1,
backgroundColor: "transparent"
};
if (dimensions.width && dimensions.height) {
defaultOptions.width = dimensions.width;
defaultOptions.height = dimensions.height;
const maxDimension = Math.max(dimensions.width, dimensions.height);
if (maxDimension <= 100) {
defaultOptions.scale = 8;
} else if (maxDimension <= 200) {
defaultOptions.scale = 6;
} else if (maxDimension <= 400) {
defaultOptions.scale = 4;
} else if (maxDimension <= 800) {
defaultOptions.scale = 2;
} else {
const maxSize = 2e3;
if (dimensions.width > maxSize || dimensions.height > maxSize) {
const scale = Math.min(maxSize / dimensions.width, maxSize / dimensions.height);
defaultOptions.scale = scale;
} else {
defaultOptions.scale = 1;
}
}
}
const result = {};
if (dimensions.width !== void 0) {
result.width = dimensions.width;
} else {
result.width = defaultOptions.width;
}
if (dimensions.height !== void 0) {
result.height = dimensions.height;
} else {
result.height = defaultOptions.height;
}
result.scale = defaultOptions.scale;
result.backgroundColor = defaultOptions.backgroundColor;
return result;
}
};
SvgConverter.DEFAULT_WIDTH = 800;
SvgConverter.DEFAULT_HEIGHT = 600;
SvgConverter.DEFAULT_SCALE = 4;
// feishu-api.ts
var getErrorMeta = (error) => {
if (typeof error !== "object" || error === null) {
return {};
}
const meta = error;
const result = {};
if ("status" in meta) {
const status = meta.status;
if (typeof status === "number") {
result.status = status;
}
}
if ("statusText" in meta) {
const statusText = meta.statusText;
if (typeof statusText === "string") {
result.statusText = statusText;
}
}
if ("response" in meta) {
result.response = meta.response;
}
if ("json" in meta) {
result.json = meta.json;
}
if ("headers" in meta) {
result.headers = meta.headers;
}
return result;
};
var isRecord = (value) => {
return typeof value === "object" && value !== null;
};
var parseErrorResult = (value) => {
if (!isRecord(value)) {
return null;
}
const code = value["code"];
const msg = value["msg"];
if (typeof code !== "number" || typeof msg !== "string") {
return null;
}
return { code, msg };
};
var parseTenantAccessTokenResponse = (value) => {
const result = {};
if (!isRecord(value)) {
return result;
}
const tenantAccessToken = value["tenant_access_token"];
if (typeof tenantAccessToken === "string") {
result.tenant_access_token = tenantAccessToken;
}
const expire = value["expire"];
if (typeof expire === "number") {
result.expire = expire;
}
const code = value["code"];
if (typeof code === "number") {
result.code = code;
}
const msg = value["msg"];
if (typeof msg === "string") {
result.msg = msg;
}
return result;
};
var getAdapterBasePath = (adapter) => {
if (!isRecord(adapter)) {
return void 0;
}
const basePath = adapter["basePath"];
return typeof basePath === "string" ? basePath : void 0;
};
var isImportTaskQueryResponse = (value) => {
return typeof value === "object" && value !== null && "job_status" in value;
};
var _FeishuApiClient = class {
// 每次删除请求间隔350ms,确保不超过每秒3次
constructor(appId, appSecret, app, apiCallCountCallback) {
this.accessToken = null;
this.tokenExpireTime = 0;
this.tokenRefreshPromise = null;
// 飞书API基础URL
this.baseUrl = "https://open.feishu.cn/open-apis";
// 限速相关属性
this.deleteRequestQueue = [];
this.isProcessingDeleteQueue = false;
this.lastDeleteRequestTime = 0;
this.DELETE_REQUEST_INTERVAL = 350;
this.appId = appId;
this.appSecret = appSecret;
this.app = app;
this.apiCallCountCallback = apiCallCountCallback;
}
static setDebugEnabled(enabled) {
this.debugEnabled = enabled;
}
debug(...args) {
if (_FeishuApiClient.debugEnabled) {
console.debug(...args);
}
}
static debug(...args) {
if (_FeishuApiClient.debugEnabled) {
console.debug(...args);
}
}
static logError(summary, error, details) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(summary, errorMessage);
_FeishuApiClient.debug(`${summary} \u8BE6\u60C5:`, {
...details,
error,
errorMessage,
errorStack: error instanceof Error ? error.stack : void 0
});
}
logError(summary, error, details) {
_FeishuApiClient.logError(summary, error, details);
}
/**
* 处理删除请求队列,确保不超过频率限制
*/
async processDeleteQueue() {
if (this.isProcessingDeleteQueue || this.deleteRequestQueue.length === 0) {
return;
}
this.isProcessingDeleteQueue = true;
while (this.deleteRequestQueue.length > 0) {
const now = Date.now();
const timeSinceLastRequest = now - this.lastDeleteRequestTime;
if (timeSinceLastRequest < this.DELETE_REQUEST_INTERVAL) {
const waitTime = this.DELETE_REQUEST_INTERVAL - timeSinceLastRequest;
await new Promise((resolve) => setTimeout(resolve, waitTime));
}
const request = this.deleteRequestQueue.shift();
if (request) {
this.lastDeleteRequestTime = Date.now();
try {
await request();
} catch (error) {
this.logError("[\u98DE\u4E66API] \u5220\u9664\u8BF7\u6C42\u6267\u884C\u5931\u8D25:", error);
throw error;
}
}
}
this.isProcessingDeleteQueue = false;
}
/**
* 将删除请求添加到队列中
*/
async queueDeleteRequest(request) {
return new Promise((resolve, reject) => {
const wrappedRequest = async () => {
try {
const result = await request();
resolve(result);
} catch (error) {
reject(error instanceof Error ? error : new Error(String(error)));
}
};
this.deleteRequestQueue.push(wrappedRequest);
void this.processDeleteQueue().catch((error) => {
reject(error instanceof Error ? error : new Error(String(error)));
});
});
}
/**
* 获取访问令牌
*/
async getAccessToken() {
const now = Date.now();
if (this.accessToken && now < this.tokenExpireTime - 30 * 60 * 1e3) {
return this.accessToken;
}
if (this.tokenRefreshPromise) {
return await this.tokenRefreshPromise;
}
this.tokenRefreshPromise = this.performTokenRefresh();
try {
const token = await this.tokenRefreshPromise;
return token;
} finally {
this.tokenRefreshPromise = null;
}
}
/**
* 执行实际的token刷新操作
*/
async performTokenRefresh() {
var _a;
const now = Date.now();
const url = `${this.baseUrl}/auth/v3/tenant_access_token/internal`;
const requestParam = {
url,
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({
app_id: this.appId,
app_secret: this.appSecret
})
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = parseTenantAccessTokenResponse(response.json);
if (!result.tenant_access_token) {
console.error("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11tenant_access_token\u5B57\u6BB5");
this.debug("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11tenant_access_token\u5B57\u6BB5\uFF0C\u5B8C\u6574\u54CD\u5E94:", result);
throw new Error(`API\u54CD\u5E94\u683C\u5F0F\u9519\u8BEF: \u7F3A\u5C11tenant_access_token\u5B57\u6BB5`);
}
if (result.code !== 0) {
throw new Error(`\u83B7\u53D6\u8BBF\u95EE\u4EE4\u724C\u5931\u8D25: ${result.msg}`);
}
this.accessToken = result.tenant_access_token;
this.tokenExpireTime = now + (result.expire || 0) * 1e3;
return result.tenant_access_token;
} catch (error) {
this.logError("[\u98DE\u4E66API] \u83B7\u53D6\u8BBF\u95EE\u4EE4\u724C\u5931\u8D25:", error);
if (error instanceof TypeError && error.message.includes("Failed to fetch")) {
console.error("[\u98DE\u4E66API] \u7F51\u7EDC\u8FDE\u63A5\u5931\u8D25");
this.debug("[\u98DE\u4E66API] \u7F51\u7EDC\u8FDE\u63A5\u9519\u8BEF\uFF0C\u53EF\u80FD\u539F\u56E0:");
this.debug("1. \u7F51\u7EDC\u8FDE\u63A5\u4E0D\u7A33\u5B9A\u6216\u65AD\u5F00");
this.debug("2. \u9632\u706B\u5899\u6216\u4EE3\u7406\u963B\u6B62\u4E86\u8BF7\u6C42");
this.debug("3. \u98DE\u4E66API\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528");
this.debug("4. DNS\u89E3\u6790\u95EE\u9898");
throw new Error("\u7F51\u7EDC\u8FDE\u63A5\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5\u540E\u91CD\u8BD5");
}
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`\u83B7\u53D6\u8BBF\u95EE\u4EE4\u724C\u5931\u8D25: ${errorMessage}`);
}
}
/**
* 上传文件到飞书云空间
* 使用 drive/v1/files/upload_all 接口将文件上传到飞书云空间
* @param fileName 文件名(需包含扩展名)
* @param fileContent 文件内容(base64编码)
* @param folderToken 目标文件夹token(可选)
* @returns 返回上传后的文件token
*/
async uploadFile(fileName, fileContent, folderToken) {
var _a;
const token = await this.getAccessToken();
const url = `https://open.feishu.cn/open-apis/drive/v1/files/upload_all`;
const binaryData = Uint8Array.from(atob(fileContent), (c) => c.charCodeAt(0));
const boundary = "feishu-file-boundary-" + Math.random().toString(36).substring(2, 15);
const encoder = new TextEncoder();
const parts = [];
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="file_name"\r
\r
`));
parts.push(encoder.encode(`${fileName}\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="parent_type"\r
\r
`));
parts.push(encoder.encode(`explorer\r
`));
if (folderToken) {
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="parent_node"\r
\r
`));
parts.push(encoder.encode(`${folderToken}\r
`));
}
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="size"\r
\r
`));
parts.push(encoder.encode(`${binaryData.length.toString()}\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
const fileNameWithoutExt = fileName.replace(/\.[^/.]+$/, "");
parts.push(encoder.encode(`Content-Disposition: form-data; name="file"; filename="${fileNameWithoutExt}"\r
`));
parts.push(encoder.encode(`Content-Type: application/octet-stream\r
\r
`));
parts.push(binaryData);
parts.push(encoder.encode(`\r
`));
parts.push(encoder.encode(`--${boundary}--\r
`));
const totalLength = parts.reduce((sum, part) => sum + part.length, 0);
const body = new Uint8Array(totalLength);
let offset = 0;
for (const part of parts) {
body.set(part, offset);
offset += part.length;
}
const requestParam = {
url,
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": `multipart/form-data; boundary=${boundary}`
},
body: body.buffer
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = response.json;
if (result.code !== 0) {
console.error("[\u98DE\u4E66API] \u4E0A\u4F20\u6587\u4EF6\u5931\u8D25:", result.msg);
this.debug("[\u98DE\u4E66API] \u4E0A\u4F20\u6587\u4EF6\u5931\u8D25\uFF0C\u9519\u8BEF\u8BE6\u60C5:", {
code: result.code,
msg: result.msg,
fullResult: result
});
throw new Error(`\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25: [${result.code}] ${result.msg}`);
}
if (!result.data || !result.data.file_token) {
console.error("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11file_token");
this.debug("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11file_token:", result);
throw new Error("\u4E0A\u4F20\u6210\u529F\u4F46\u672A\u8FD4\u56DEfile_token");
}
return result.data.file_token;
} catch (error) {
this.logError("[\u98DE\u4E66API] \u4E0A\u4F20\u6587\u4EF6\u5230\u98DE\u4E66\u5931\u8D25:", error, {
requestUrl: url,
hasToken: !!token
});
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25: ${errorMessage}`);
}
}
/**
* 上传图片素材到飞书云文档
* 使用 drive/v1/medias/upload_all 接口将图片素材上传到指定云文档中
* @param fileName 图片文件名(需包含扩展名)
* @param fileContent 图片文件内容(base64编码)
* @param documentId 目标飞书文档的document_id
* @param blockId 目标图片块的block_id
* @returns 返回上传后的文件token
*/
async uploadImageMaterial(fileName, fileContent, documentId, blockId) {
var _a;
const token = await this.getAccessToken();
const url = `https://open.feishu.cn/open-apis/drive/v1/medias/upload_all`;
const binaryData = Uint8Array.from(atob(fileContent), (c) => c.charCodeAt(0));
const boundary = "feishu-image-boundary-" + Math.random().toString(36).substring(2, 15);
const encoder = new TextEncoder();
const parts = [];
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="file_name"\r
\r
`));
parts.push(encoder.encode(`${fileName}\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="parent_type"\r
\r
`));
parts.push(encoder.encode(`docx_image\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="parent_node"\r
\r
`));
parts.push(encoder.encode(`${blockId}\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="size"\r
\r
`));
parts.push(encoder.encode(`${binaryData.length.toString()}\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="extra"\r
\r
`));
const extraData = JSON.stringify({ "drive_route_token": documentId });
parts.push(encoder.encode(`${extraData}\r
`));
parts.push(encoder.encode(`--${boundary}\r
`));
parts.push(encoder.encode(`Content-Disposition: form-data; name="file"; filename="${fileName}"\r
`));
parts.push(encoder.encode(`Content-Type: application/octet-stream\r
\r
`));
parts.push(binaryData);
parts.push(encoder.encode(`\r
`));
parts.push(encoder.encode(`--${boundary}--\r
`));
const totalLength = parts.reduce((sum, part) => sum + part.length, 0);
const body = new Uint8Array(totalLength);
let offset = 0;
for (const part of parts) {
body.set(part, offset);
offset += part.length;
}
const requestParam = {
url,
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": `multipart/form-data; boundary=${boundary}`
},
body: body.buffer
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = response.json;
if (result.code !== 0) {
console.error("[\u98DE\u4E66API] \u4E0A\u4F20\u56FE\u7247\u7D20\u6750\u5931\u8D25:", result.msg);
this.debug("[\u98DE\u4E66API] \u4E0A\u4F20\u56FE\u7247\u7D20\u6750\u5931\u8D25\uFF0C\u9519\u8BEF\u8BE6\u60C5:", {
code: result.code,
msg: result.msg,
fullResult: result
});
throw new Error(`\u4E0A\u4F20\u56FE\u7247\u7D20\u6750\u5931\u8D25: [${result.code}] ${result.msg}`);
}
if (!result.data || !result.data.file_token) {
console.error("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11file_token");
this.debug("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11file_token:", result);
throw new Error("\u4E0A\u4F20\u6210\u529F\u4F46\u672A\u8FD4\u56DEfile_token");
}
return result.data.file_token;
} catch (error) {
this.logError("[\u98DE\u4E66API] \u4E0A\u4F20\u56FE\u7247\u7D20\u6750\u5230\u98DE\u4E66\u5931\u8D25:", error, {
requestUrl: url,
hasToken: !!token
});
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`\u4E0A\u4F20\u56FE\u7247\u7D20\u6750\u5931\u8D25: ${errorMessage}`);
}
}
/**
* 创建导入任务
* @param fileName 文件名
* @param fileToken 文件token(从上传文件接口获取)
* @param folderToken 目标文件夹token(可选)
*/
async createImportTask(fileName, fileToken, folderToken) {
var _a, _b;
const token = await this.getAccessToken();
const url = `${this.baseUrl}/drive/v1/import_tasks`;
const lastDotIndex = fileName.lastIndexOf(".");
let pureFileName;
let fileExtension;
if (lastDotIndex > 0 && fileName.substring(lastDotIndex + 1).toLowerCase() === "md") {
pureFileName = fileName.substring(0, lastDotIndex);
fileExtension = "md";
} else {
pureFileName = fileName;
fileExtension = "md";
}
const requestBody = {
file_extension: fileExtension,
// Markdown文件扩展名
file_name: pureFileName,
// 纯文件名(不含扩展名)
type: "docx",
// 导入为飞书文档
file_token: fileToken
};
if (folderToken) {
requestBody.point = {
mount_type: 1,
// 1表示文件夹
mount_key: folderToken
};
}
const requestParam = {
url,
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(requestBody)
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = response.json;
if (result.code === 0) {
if (!((_b = result.data) == null ? void 0 : _b.ticket)) {
console.error("[\u98DE\u4E66API] \u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u6210\u529F\u4F46\u7F3A\u5C11ticket");
throw new Error("\u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u6210\u529F\u4F46\u8FD4\u56DE\u6570\u636E\u4E2D\u7F3A\u5C11ticket");
}
return result.data.ticket;
} else {
console.error("[\u98DE\u4E66API] \u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25:", result.msg);
this.debug("[\u98DE\u4E66API] \u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25\uFF0C\u9519\u8BEF\u8BE6\u60C5:", {
code: result.code,
msg: result.msg,
fullResult: result
});
throw new Error(`\u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25 (\u9519\u8BEF\u7801: ${result.code}): ${result.msg}`);
}
} catch (error) {
const errorMeta = getErrorMeta(error);
if (errorMeta.status === 400 && errorMeta.json) {
console.error("[\u98DE\u4E66API] \u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25 (HTTP 400)");
this.debug("[\u98DE\u4E66API] HTTP 400\u9519\u8BEF\uFF0C\u8BE6\u7EC6\u54CD\u5E94:", {
status: errorMeta.status,
responseBody: errorMeta.json,
headers: errorMeta.headers
});
const errorResult = parseErrorResult(errorMeta.json);
if (errorResult) {
throw new Error(`\u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25 (\u9519\u8BEF\u7801: ${errorResult.code}): ${errorResult.msg}`);
}
}
this.logError("[\u98DE\u4E66API] \u521B\u5EFA\u98DE\u4E66\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25:", error, {
requestUrl: url,
hasToken: !!token,
status: errorMeta.status || "unknown",
responseBody: errorMeta.json || "no response body"
});
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`\u521B\u5EFA\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25: ${errorMessage}`);
}
}
/**
* 查询导入任务状态
* @param ticket 任务票据
*/
async queryImportTask(ticket) {
var _a;
const token = await this.getAccessToken();
const url = `${this.baseUrl}/drive/v1/import_tasks/${ticket}`;
const requestParam = {
url,
method: "GET",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json; charset=utf-8"
}
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = response.json;
if (result.code !== 0) {
console.error("[\u98DE\u4E66API] \u67E5\u8BE2\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25:", result.msg);
this.debug("[\u98DE\u4E66API] \u67E5\u8BE2\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25\uFF0C\u9519\u8BEF\u8BE6\u60C5:", {
code: result.code,
msg: result.msg,
fullResult: result
});
throw new Error(`\u67E5\u8BE2\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25: [${result.code}] ${result.msg}`);
}
let taskResult;
if (typeof result.data === "object" && result.data !== null && "result" in result.data) {
taskResult = result.data.result;
} else if (isImportTaskQueryResponse(result.data)) {
taskResult = result.data;
}
if (!taskResult) {
throw new Error("\u5BFC\u5165\u4EFB\u52A1\u7ED3\u679C\u4E3A\u7A7A");
}
return taskResult;
} catch (error) {
this.logError("[\u98DE\u4E66API] \u67E5\u8BE2\u5BFC\u5165\u4EFB\u52A1\u5F02\u5E38:", error, {
requestUrl: url,
hasToken: !!token
});
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`\u67E5\u8BE2\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25: ${errorMessage}`);
}
}
/**
* 等待导入任务完成(支持递增重试间隔)
* @param ticket 任务票据
* @param onProgress 进度回调
* @param maxRetries 最大重试次数(默认5次)
*/
async waitForImportTask(ticket, onProgress, maxRetries = 5) {
let retryCount = 0;
while (retryCount <= maxRetries) {
try {
const result = await this.queryImportTask(ticket);
if (result.job_status === 0) {
if (!result.token || !result.url) {
console.error("[\u98DE\u4E66API] \u274C \u5BFC\u5165\u4EFB\u52A1\u5B8C\u6210\u4F46\u7F3A\u5C11\u5FC5\u8981\u4FE1\u606F");
this.debug("[\u98DE\u4E66API] \u274C \u5BFC\u5165\u4EFB\u52A1\u5B8C\u6210\u4F46\u7F3A\u5C11\u5FC5\u8981\u4FE1\u606F:", result);
throw new Error("\u5BFC\u5165\u4EFB\u52A1\u5B8C\u6210\u4F46\u672A\u8FD4\u56DE\u6587\u6863\u4FE1\u606F");
}
const formattedUrl = this.formatDocumentUrl(result.url, result.token);
return {
token: result.token,
url: formattedUrl
};
} else if (result.job_status === 1 || result.job_status === 2) {
retryCount++;
onProgress == null ? void 0 : onProgress("\u6587\u6863\u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7A0D\u5019...");
if (retryCount > maxRetries) {
console.error(`[\u98DE\u4E66API] \u5BFC\u5165\u4EFB\u52A1\u5904\u7406\u8D85\u65F6\uFF0C\u5DF2\u91CD\u8BD5${maxRetries}\u6B21`);
throw new Error("\u5BFC\u5165\u4EFB\u52A1\u5904\u7406\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u624B\u52A8\u68C0\u67E5\u98DE\u4E66\u4E91\u6587\u6863");
}
let waitTime = 3e3;
if (retryCount >= 3) {
waitTime = 6e3;
}
await new Promise((resolve) => setTimeout(resolve, waitTime));
continue;
} else {
console.error("[\u98DE\u4E66API] \u5BFC\u5165\u4EFB\u52A1\u72B6\u6001\u672A\u77E5");
this.debug("[\u98DE\u4E66API] \u5BFC\u5165\u4EFB\u52A1\u72B6\u6001\u672A\u77E5:", {
job_status: result.job_status,
job_error_msg: result.job_error_msg,
fullResult: result
});
const errorMsg = result.job_error_msg || `\u672A\u77E5\u7684\u4EFB\u52A1\u72B6\u6001: ${result.job_status}`;
throw new Error(`\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25: ${errorMsg}`);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
if (errorMessage.includes("\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25") || errorMessage.includes("\u5BFC\u5165\u4EFB\u52A1\u5DF2\u63D0\u4EA4")) {
throw error;
}
retryCount++;
if (retryCount > maxRetries) {
console.error(`[\u98DE\u4E66API] \u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570 (${maxRetries})\uFF0C\u505C\u6B62\u91CD\u8BD5`);
throw error;
}
let waitTime = 3e3;
if (retryCount >= 3) {
waitTime = 6e3;
}
await new Promise((resolve) => setTimeout(resolve, waitTime));
}
}
throw new Error("\u5BFC\u5165\u4EFB\u52A1\u5931\u8D25\uFF1A\u5DF2\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570");
}
/**
* 获取文档所有块
* @param documentId 文档ID
*/
async getDocumentBlocks(documentId) {
var _a;
const token = await this.getAccessToken();
const url = `${this.baseUrl}/docx/v1/documents/${documentId}/blocks`;
const requestParam = {
url,
method: "GET",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json; charset=utf-8"
}
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = response.json;
if (result.code !== 0) {
console.error("[\u98DE\u4E66API] \u83B7\u53D6\u6587\u6863\u5757\u5931\u8D25:", result.msg);
this.debug("[\u98DE\u4E66API] \u83B7\u53D6\u6587\u6863\u5757\u5931\u8D25\uFF0C\u9519\u8BEF\u8BE6\u60C5:", {
code: result.code,
msg: result.msg,
fullResult: result
});
throw new Error(`\u83B7\u53D6\u6587\u6863\u5757\u5931\u8D25: [${result.code}] ${result.msg}`);
}
if (!result.data || !result.data.items) {
console.error("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11items");
this.debug("[\u98DE\u4E66API] \u54CD\u5E94\u4E2D\u7F3A\u5C11items:", result);
throw new Error("\u83B7\u53D6\u6210\u529F\u4F46\u672A\u8FD4\u56DE\u6587\u6863\u5757\u6570\u636E");
}
return result.data.items;
} catch (error) {
this.logError("[\u98DE\u4E66API] \u83B7\u53D6\u6587\u6863\u5757\u5931\u8D25:", error, {
requestUrl: url,
hasToken: !!token
});
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`\u83B7\u53D6\u6587\u6863\u5757\u5931\u8D25: ${errorMessage}`);
}
}
/**
* 更新文档块
* @param documentId 文档ID
* @param blockId 块ID
* @param imageToken 图片token(file_token)
*/
async updateDocumentBlock(documentId, blockId, imageToken, imageInfo) {
var _a;
const token = await this.getAccessToken();
const url = `${this.baseUrl}/docx/v1/documents/${documentId}/blocks/${blockId}?document_revision_id=-1`;
let width = 800;
let height = 600;
if (imageInfo) {
try {
if (typeof imageInfo.width === "number" && imageInfo.width > 0 && typeof imageInfo.height === "number" && imageInfo.height > 0) {
width = imageInfo.width;
height = imageInfo.height;
} else if (imageInfo.svgConvertOptions) {
width = imageInfo.svgConvertOptions.originalWidth * imageInfo.svgConvertOptions.scale;
height = imageInfo.svgConvertOptions.originalHeight * imageInfo.svgConvertOptions.scale;
this.debug(`[DEBUG] SVG\u8F6C\u6362\u56FE\u7247\u5C3A\u5BF8: originalWidth=${imageInfo.svgConvertOptions.originalWidth}, originalHeight=${imageInfo.svgConvertOptions.originalHeight}, scale=${imageInfo.svgConvertOptions.scale}, finalWidth=${width}, finalHeight=${height}`);
} else {
const dimensions = await this.getImageDimensions(imageInfo.path);
if (dimensions) {
width = dimensions.width;
height = dimensions.height;
}
}
const aspectRatio = width / height;
let maxWidth;
let maxHeight;
this.debug(`[DEBUG] \u98DE\u4E66\u4E0A\u4F20\u524D\u5C3A\u5BF8: width=${width}, height=${height}, aspectRatio=${aspectRatio}`);
if (aspectRatio > 4) {
maxWidth = 2400;
maxHeight = 600;
} else if (aspectRatio > 2) {
maxWidth = 2e3;
maxHeight = 800;
} else if (aspectRatio < 0.8) {
maxWidth = 1e3;
maxHeight = 2500;
} else {
maxWidth = 1200;
maxHeight = 800;
}
if (width > maxWidth || height > maxHeight) {
const ratio = Math.min(maxWidth / width, maxHeight / height);
this.debug(`[DEBUG] \u9700\u8981\u7F29\u653E: maxWidth=${maxWidth}, maxHeight=${maxHeight}, ratio=${ratio}`);
width = Math.round(width * ratio);
height = Math.round(height * ratio);
this.debug(`[DEBUG] \u7F29\u653E\u540E\u5C3A\u5BF8: width=${width}, height=${height}`);
} else {
this.debug(`[DEBUG] \u65E0\u9700\u7F29\u653E: maxWidth=${maxWidth}, maxHeight=${maxHeight}`);
}
} catch (error) {
}
}
const requestBody = {
replace_image: {
token: imageToken,
width,
height,
align: 2
}
};
const requestBody_str = JSON.stringify(requestBody);
const requestParam = {
url,
method: "PATCH",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
},
body: requestBody_str
};
try {
const response = await (0, import_obsidian.requestUrl)(requestParam);
(_a = this.apiCallCountCallback) == null ? void 0 : _a.call(this);
const result = response.json;
if (result.code !== 0) {
console.error("[\u98DE\u4E66API] \u66F4\u65B0\u6587\u6863\u5757\u5931\u8D25:", result.msg);
this.debug("[\u98DE\u4E66API] \u66F4\u65B0\u6587\u6863\u5757\u5931\u8D25\uFF0C\u9519\u8BEF\u8BE6\u60C5:", {
code: result.code,
msg: result.msg,
fullResult: result
});
throw new Error(`\u66F4\u65B0\u6587\u6863\u5757\u5931\u8D25: [${result.code}] ${result.msg}`);
}