-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathmain.ts
More file actions
2380 lines (2011 loc) · 82.2 KB
/
main.ts
File metadata and controls
2380 lines (2011 loc) · 82.2 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
import { App, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting, TFile, MarkdownRenderer, Component } from 'obsidian';
import { FeishuApiClient, ImageInfo, createFeishuClient } from './feishu-api';
import { CryptoUtils } from './crypto-utils';
import { CalloutConverter, CalloutInfo } from './callout-converter';
import { YamlProcessor, YamlInfo } from './yaml-processor';
import { LinkProcessor, UploadResult } from './link-processor';
import { MermaidConverter, MermaidInfo, MermaidConversionResult } from './mermaid-converter';
// 通知管理器
class NotificationManager {
private activeNotifications = new Set<string>();
private notificationTimeouts = new Map<string, NodeJS.Timeout>();
/**
* 显示通知,防止重复
* @param message 通知消息
* @param duration 显示时长(毫秒)
* @param type 通知类型,用于去重
*/
showNotice(message: string, duration: number = 4000, type?: string): void {
const noticeKey = type || message;
// 如果相同类型的通知已存在,则不显示新通知
if (this.activeNotifications.has(noticeKey)) {
return;
}
// 标记通知为活跃状态
this.activeNotifications.add(noticeKey);
// 显示通知
new Notice(message, duration);
// 设置定时器清除通知状态
const timeout = setTimeout(() => {
this.activeNotifications.delete(noticeKey);
this.notificationTimeouts.delete(noticeKey);
}, duration);
this.notificationTimeouts.set(noticeKey, timeout);
}
/**
* 清除所有通知状态
*/
clearAll(): void {
this.notificationTimeouts.forEach(timeout => clearTimeout(timeout));
this.activeNotifications.clear();
this.notificationTimeouts.clear();
}
}
// 上传历史记录接口
interface UploadHistoryItem {
title: string;
url: string;
uploadTime: string; // 格式: YYYY-MM-DD HH:mm
docToken: string; // 文件的token
permissions?: {
isPublic: boolean;
allowCopy: boolean;
allowCreateCopy: boolean;
}; // 权限设置
referencedDocuments?: Array<{
title: string;
docToken: string;
url: string;
}>; // 引用文档列表
isReferencedDocument?: boolean; // 标识是否为引用文档
}
// 插件设置接口
interface FeishuUploaderSettings {
appId: string;
appSecret: string;
folderToken: string;
userId: string;
uploadHistory: UploadHistoryItem[];
uploadCount: number;
agreedToTerms: boolean; // 用户是否已同意用户协议
apiCallCount: number; // 本月API调用次数
lastResetDate: string; // 上次重置日期(YYYY-MM格式)
enableDoubleLinkMode: boolean; // 是否启用双链模式
debugLoggingEnabled: boolean; // 是否启用调试日志
}
// 默认设置
const DEFAULT_SETTINGS: FeishuUploaderSettings = {
appId: '',
appSecret: '',
folderToken: '',
userId: '',
uploadHistory: [],
uploadCount: 0,
agreedToTerms: false,
apiCallCount: 0,
lastResetDate: new Date().toISOString().substring(0, 7), // 当前年月
enableDoubleLinkMode: true, // 默认启用双链模式
debugLoggingEnabled: false
}
type SensitiveField = keyof Pick<FeishuUploaderSettings, 'appId' | 'appSecret' | 'folderToken' | 'userId'>;
type PermissionSettings = {
isPublic: boolean;
allowCopy: boolean;
allowCreateCopy: boolean;
allowPrintDownload: boolean;
copyEntity?: string;
securityEntity?: string;
};
type RegularImageInfo = {
fileName: string;
path: string;
alt?: string;
title?: string;
originalSyntax: 'obsidian' | 'markdown';
};
type CollectedImageInfo =
| { type: 'regular'; position: number; info: RegularImageInfo; originalMatch: string }
| { type: 'mermaid'; position: number; info: MermaidInfo; originalMatch: string };
type LinkProcessResult = { processedContent: string; uploadResults: Map<string, UploadResult> };
export default class FeishuUploaderPlugin extends Plugin {
settings!: FeishuUploaderSettings;
// 飞书客户端实例
public feishuClient: FeishuApiClient | null = null;
// 飞书富文本客户端实例
public feishuRichClient: FeishuApiClient | null = null;
// 通知管理器
public notificationManager = new NotificationManager();
// 上次保存的敏感数据哈希,用于检测变化
private lastSensitiveDataHash: string | null = null;
applyDebugLoggingSetting(): void {
FeishuApiClient.setDebugEnabled(this.settings.debugLoggingEnabled);
MermaidConverter.setDebugEnabled(this.settings.debugLoggingEnabled);
CalloutConverter.setDebugEnabled(this.settings.debugLoggingEnabled);
YamlProcessor.setDebugEnabled(this.settings.debugLoggingEnabled);
LinkProcessor.setDebugEnabled(this.settings.debugLoggingEnabled);
CryptoUtils.setDebugEnabled(this.settings.debugLoggingEnabled);
}
override async onload() {
await this.loadSettings();
this.applyDebugLoggingSetting();
// 检查用户是否已同意协议
if (!this.settings.agreedToTerms) {
const termsModal = new UserAgreementModal(this.app, this);
termsModal.open();
return; // 等待用户同意协议后再继续初始化
}
// 如果用户已同意协议,直接完成初始化
this.completeInitialization();
}
// 完成插件初始化(用户同意协议后调用)
completeInitialization() {
// 初始化飞书客户端
this.initializeFeishuClient();
// 添加命令:分享当前文档到飞书
this.addCommand({
id: 'publish-current-document',
name: '分享当前文档到飞书',
callback: () => {
void this.uploadCurrentDocument();
}
});
// 添加右键菜单
this.registerEvent(
this.app.workspace.on('file-menu', (menu, file) => {
if (file instanceof TFile && file.extension === 'md') {
menu.addItem((item) => {
item
.setTitle('分享该页面')
.setIcon('share')
.onClick(() => {
void this.uploadFile(file);
});
});
}
})
);
// 添加ribbon按钮
this.addRibbonIcon('share', '分享当前页面', (evt: MouseEvent) => {
void this.uploadCurrentDocument();
});
// 添加设置选项卡
this.addSettingTab(new FeishuUploaderSettingTab(this.app, this));
}
/**
* 初始化飞书API客户端
*/
private initializeFeishuClient(): void {
if (this.settings.appId && this.settings.appSecret) {
// 创建异步回调包装函数
const asyncCallback = () => {
void this.incrementApiCallCount().catch(error => {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`[飞书插件] API调用计数更新失败: ${errorMessage}`);
if (this.settings.debugLoggingEnabled) {
console.debug('[飞书插件] API调用计数更新失败详情:', error);
}
});
};
// 如果客户端已存在,更新凭据而不是重新创建
if (this.feishuClient) {
this.feishuClient.updateCredentials(this.settings.appId, this.settings.appSecret);
} else {
this.feishuClient = createFeishuClient(this.settings.appId, this.settings.appSecret, this.app, asyncCallback);
}
if (this.feishuRichClient) {
this.feishuRichClient.updateCredentials(this.settings.appId, this.settings.appSecret);
} else {
this.feishuRichClient = createFeishuClient(this.settings.appId, this.settings.appSecret, this.app, asyncCallback);
}
} else {
this.feishuClient = null;
this.feishuRichClient = null;
}
}
override onunload() {
// 清理通知管理器
this.notificationManager.clearAll();
// 清理资源
}
async loadSettings() {
const loadedData = await this.loadData();
const loadedSettings: Partial<FeishuUploaderSettings> = typeof loadedData === 'object' && loadedData !== null ? loadedData : {};
this.settings = Object.assign({}, DEFAULT_SETTINGS, loadedSettings);
// 检查是否有明文敏感数据需要加密
const sensitiveFields: SensitiveField[] = ['appId', 'appSecret', 'folderToken', 'userId'];
let hasPlaintextData = false;
for (const field of sensitiveFields) {
const value = loadedSettings[field];
if (value && typeof value === 'string' && !CryptoUtils.isEncryptedData(value)) {
hasPlaintextData = true;
break;
}
}
// 解密敏感设置数据
this.settings = await CryptoUtils.decryptSensitiveSettings(this.settings);
// 初始化敏感数据哈希
const sensitiveData = sensitiveFields.map(field => this.settings[field] || '').join('|');
this.lastSensitiveDataHash = await this.simpleHash(sensitiveData);
// 如果检测到明文数据,自动加密保存
if (hasPlaintextData) {
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
}
// 向后兼容性处理:为现有历史记录添加默认docToken
if (this.settings.uploadHistory) {
this.settings.uploadHistory.forEach(item => {
if (!item.docToken) {
item.docToken = '未知';
}
});
}
}
async saveSettings() {
// 加密敏感数据后保存
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
// 保存设置后重新初始化客户端
this.initializeFeishuClient();
this.applyDebugLoggingSetting();
}
/**
* 优化的保存方法:只在必要时进行加密
*/
private async saveDataOptimized(): Promise<void> {
// 计算当前敏感数据的哈希
const sensitiveFields: SensitiveField[] = ['appId', 'appSecret', 'folderToken', 'userId'];
const sensitiveData = sensitiveFields.map(field => this.settings[field] || '').join('|');
const currentHash = await this.simpleHash(sensitiveData);
// 如果敏感数据没有变化,直接保存原始数据
if (this.lastSensitiveDataHash === currentHash) {
await this.saveData(this.settings);
return;
}
// 敏感数据有变化,需要加密
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
this.lastSensitiveDataHash = currentHash;
}
/**
* 简单哈希函数
*/
private async simpleHash(data: string): Promise<string> {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
/**
* 统一收集文档中所有类型的图片信息(包括普通图片、SVG、Mermaid)
* @param content 文档内容
* @returns 按原文档位置排序的图片信息数组
*/
private collectAllImageInfos(content: string): CollectedImageInfo[] {
const allImages: CollectedImageInfo[] = [];
// 1. 收集Mermaid图表信息
if (MermaidConverter.hasMermaidCharts(content)) {
const mermaidInfos = MermaidConverter.extractMermaidCharts(content);
mermaidInfos.forEach(mermaidInfo => {
const mermaidPattern = new RegExp(`\`\`\`mermaid[\\s\\S]*?\`\`\``, 'g');
let match;
while ((match = mermaidPattern.exec(content)) !== null) {
// 检查这个匹配是否对应当前的mermaidInfo
const matchContent = match[0].replace(/```mermaid\s*\n?/, '').replace(/\n?\s*```$/, '').trim();
if (matchContent === mermaidInfo.content.trim()) {
allImages.push({
type: 'mermaid',
position: match.index,
info: mermaidInfo,
originalMatch: match[0]
});
break;
}
}
});
}
// 2. 收集普通图片信息(Obsidian语法和标准Markdown语法)
// Obsidian图片语法: ![[image.png]]
const obsidianImageRegex = /!\[\[([^\]]+)\]\]/g;
let match;
while ((match = obsidianImageRegex.exec(content)) !== null) {
const fileName = match[1];
if (!fileName) {
continue;
}
const info: RegularImageInfo = {
fileName,
path: fileName,
originalSyntax: 'obsidian'
};
allImages.push({
type: 'regular',
position: match.index,
info,
originalMatch: match[0]
});
}
// 标准Markdown图片语法: 
const markdownImageRegex = /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/g;
while ((match = markdownImageRegex.exec(content)) !== null) {
const alt = match[1] ?? '';
const path = match[2];
const title = match[3];
if (!path) continue;
// 对路径进行解码,处理URL编码的字符(如空格变为%20)
const decodedPath = decodeURI(path);
const fileName = decodedPath.split('/').pop() || decodedPath;
const info: RegularImageInfo = {
fileName,
path: decodedPath,
alt,
originalSyntax: 'markdown',
...(title !== undefined ? { title } : {})
};
allImages.push({
type: 'regular',
position: match.index,
info,
originalMatch: match[0]
});
}
// 3. 按位置排序
allImages.sort((a, b) => a.position - b.position);
return allImages;
}
/**
* 上传当前文档
*/
async uploadCurrentDocument(): Promise<void> {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeView) {
this.notificationManager.showNotice('请先打开一个Markdown文档', 4000, 'no-markdown-doc');
return;
}
const file = activeView.file;
if (!file) {
this.notificationManager.showNotice('无法获取当前文档', 4000, 'no-current-doc');
return;
}
await this.uploadFile(file);
}
/**
* 转换当前文档中的 Callout 为飞书高亮块
*/
/**
* 上传指定文件
*/
async uploadFile(file: TFile): Promise<void> {
// 根据上传模式选择客户端
const client = this.feishuClient;
if (!client) {
console.error('[飞书插件] 上传失败:客户端未初始化');
this.notificationManager.showNotice('请先在设置中配置飞书应用凭证', 5000, 'missing-credentials');
return;
}
if (!this.settings.folderToken) {
console.error('[飞书插件] 上传失败:文件夹 token 未配置');
this.notificationManager.showNotice('请先在设置中配置飞书文件夹 token', 5000, 'missing-folder-token');
return;
}
// 读取文件内容
let content = await this.app.vault.read(file);
const title = file.basename;
// 创建并显示进度条弹窗
const progressModal = new UploadProgressModal(this.app);
progressModal.open();
try {
// 步骤1: 准备上传 (0-10%)
progressModal.updateProgress(5, '正在读取文档内容...');
// 步骤2: 分析文档 (10-15%)
progressModal.updateProgress(10, '正在分析文档格式...');
// 处理双链引用(在YAML处理之后,其他处理之前)(15-35%)
let linkProcessor: LinkProcessor | null = null;
let linkResult: LinkProcessResult | null = null;
if (this.settings.enableDoubleLinkMode && this.feishuClient) {
linkProcessor = new LinkProcessor(this.app, this.feishuClient, this);
linkResult = await linkProcessor.processWikiLinks(content, (status) => {
// 双链处理占用15%-35%的进度区间,共20%
const baseProgress = 15;
const maxProgress = 35;
// 根据状态估算进度
let currentProgress = baseProgress;
if (status.includes('正在上传引用的文档')) {
currentProgress = baseProgress + 5; // 20%
} else if (status.includes('正在处理引用文档')) {
// 根据处理进度动态计算
const match = status.match(/(\d+)\/(\d+)/);
if (match && match[1] && match[2]) {
const current = parseInt(match[1]);
const total = parseInt(match[2]);
const progressRatio = current / total;
currentProgress = baseProgress + 5 + (progressRatio * 10); // 20%-30%
} else {
currentProgress = baseProgress + 8; // 23%
}
} else if (status.includes('正在替换双链为飞书链接')) {
currentProgress = maxProgress - 2; // 33%
}
progressModal.updateProgress(Math.min(currentProgress, maxProgress), status);
});
content = linkResult.processedContent;
}
// 检测并缓存YAML frontmatter(必须在移除之前进行)
let cachedYaml: YamlInfo | null = null;
if (this.feishuClient) {
const yamlProcessor = new YamlProcessor(this.feishuClient);
cachedYaml = yamlProcessor.extractYaml(content);
if (cachedYaml) {
// 从内容中移除YAML frontmatter
content = yamlProcessor.removeYamlFrontmatter(content);
}
}
// 统一收集所有图片信息(包括Mermaid、普通图片、SVG)
progressModal.updateProgress(30, '正在分析文档中的图片...');
const allImageInfos = this.collectAllImageInfos(content);
const hasImages = allImageInfos.length > 0;
// 按顺序处理所有图片
let processedContent = content;
let cachedMermaidInfos: MermaidInfo[] = [];
if (hasImages) {
progressModal.updateProgress(35, '正在处理图片...');
try {
// 按原文档顺序处理每个图片
for (let i = 0; i < allImageInfos.length; i++) {
const imageInfo = allImageInfos[i];
if (!imageInfo) continue;
// 图片处理进度:35% + (当前图片索引 / 总图片数) * 20%
const progress = 35 + (i / allImageInfos.length) * 20;
if (imageInfo.type === 'mermaid') {
progressModal.updateProgress(progress, `正在渲染Mermaid图表 ${i + 1}/${allImageInfos.length}...`);
const mermaidInfo = imageInfo.info;
// 获取推荐的转换选项
const options = MermaidConverter.getRecommendedOptions(mermaidInfo.content);
// 转换Mermaid为PNG
const conversionResult: MermaidConversionResult = await MermaidConverter.convertMermaidToPng(this.app, mermaidInfo.content, options);
// 创建临时图片文件(在内存中)
const tempFileName = `temp_${mermaidInfo.fileName}`;
// 将base64数据和实际尺寸信息添加到FeishuApiClient的缓存中
const svgConvertOptions = {
originalWidth: conversionResult.originalWidth,
originalHeight: conversionResult.originalHeight,
scale: conversionResult.scale
};
FeishuApiClient.addMermaidImageToCache(tempFileName, conversionResult.pngBase64, svgConvertOptions);
FeishuApiClient.addMermaidImageToCache(mermaidInfo.fileName, conversionResult.pngBase64, svgConvertOptions);
// 将Mermaid信息存储起来,在图片处理阶段使用
mermaidInfo.pngBase64 = conversionResult.pngBase64;
mermaidInfo.tempFileName = tempFileName;
cachedMermaidInfos.push(mermaidInfo);
// 替换当前Mermaid图表为图片引用
const imageReference = ``;
if (imageInfo.originalMatch) {
processedContent = processedContent.replace(imageInfo.originalMatch, imageReference);
}
}
}
// 更新content为处理后的内容
content = processedContent;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`[图片处理] 处理图片失败: ${errorMessage}`);
if (this.settings.debugLoggingEnabled) {
console.debug('[图片处理] 处理图片失败详情:', error);
}
this.notificationManager.showNotice(`图片处理失败: ${errorMessage}`, 6000);
// 继续处理,不中断上传流程
}
}
// 检测并缓存Callout内容
let cachedCallouts: CalloutInfo[] = [];
if (this.feishuClient) {
const calloutConverter = new CalloutConverter(this.feishuClient);
cachedCallouts = calloutConverter.extractCallouts(content);
}
// 步骤3: 构建正确顺序的图片信息数组
let orderedImageInfos: ImageInfo[] = [];
if (hasImages) {
// 按照allImageInfos的顺序构建ImageInfo数组
for (const imageInfo of allImageInfos) {
if (imageInfo.type === 'mermaid') {
// Mermaid图片使用生成的文件名
const mermaidInfo = imageInfo.info;
orderedImageInfos.push({
path: mermaidInfo.fileName,
fileName: mermaidInfo.fileName,
position: orderedImageInfos.length
});
} else {
// 普通图片
orderedImageInfos.push({
path: imageInfo.info.path,
fileName: imageInfo.info.fileName,
position: orderedImageInfos.length
});
}
}
}
// 步骤4: 正常上传流程 (55-85%)
progressModal.updateProgress(55, '正在上传文档到飞书...');
const result = await this.performNormalUpload(file, content, hasImages, orderedImageInfos, progressModal);
// 步骤4: 处理YAML和Callout (75-90%)
let processStep = 80;
// 处理YAML frontmatter
if (cachedYaml) {
progressModal.updateProgress(processStep, '正在处理文档信息块...');
await this.autoProcessYaml(result.token, cachedYaml);
processStep = 85;
}
// 处理Callout
if (cachedCallouts.length > 0) {
progressModal.updateProgress(processStep, '正在处理标注块...');
// 自动处理 Callout 转换(使用缓存的Callout内容)
await this.autoConvertCallouts(result.token, cachedCallouts);
processStep = 90;
}
// 步骤5: 完成上传 (90-100%)
progressModal.updateProgress(95, '正在保存上传记录...');
const referencedDocs = this.settings.enableDoubleLinkMode && linkProcessor && linkResult && linkResult.uploadResults.size > 0 ?
Array.from(linkResult.uploadResults.values()).map((result) => ({
title: result.title,
docToken: result.token,
url: result.url
})) : undefined;
await this.addUploadHistory(title, result.url, result.token, undefined, referencedDocs);
if (this.settings.enableDoubleLinkMode && referencedDocs && referencedDocs.length > 0) {
for (const refDoc of referencedDocs) {
await this.addUploadHistory(
refDoc.title,
refDoc.url,
refDoc.docToken,
undefined,
undefined,
true // 标识为引用文档
);
}
}
// 步骤6: 完成上传
progressModal.complete();
new DocumentPermissionModal(this.app, result.token, result.url, title, this, false).open();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`[飞书插件] 上传失败: ${errorMessage}`);
if (this.settings.debugLoggingEnabled) {
console.debug('[飞书插件] 上传失败详情:', error);
}
let userMessage = '';
// 根据错误类型提供不同的用户提示
if (errorMessage.includes('导入任务处理超时')) {
// 任务处理超时
userMessage = '文档处理时间较长,请稍后手动检查飞书云文档中的新文档。';
progressModal.complete(); // 超时也算完成
new Notice(userMessage, 10000);
return; // 不显示错误对话框,因为这不是真正的错误
} else if (errorMessage.includes('网络连接失败')) {
userMessage = '网络连接失败,请检查以下项目:\n1. 确保网络连接正常\n2. 检查防火墙设置\n3. 尝试重新连接网络后重试';
} else if (errorMessage.includes('获取访问令牌失败')) {
userMessage = 'API 认证失败,请检查:\n1. app ID 和 app secret 是否正确\n2. 应用权限是否配置正确\n3. 网络是否能访问飞书 API';
} else if (errorMessage.includes('文件夹')) {
userMessage = '文件夹配置错误,请检查:\n1. 文件夹 token 是否正确\n2. 是否有文件夹写入权限';
} else if (errorMessage.includes('查询导入任务失败,已重试')) {
userMessage = '查询导入状态失败,已重试2次。文档可能已成功上传,请手动检查飞书云文档。';
} else {
userMessage = `上传失败: ${errorMessage}`;
}
// 显示错误状态
progressModal.showError(userMessage);
new Notice(userMessage, 8000);
// 如果是网络错误,提供重试选项
if (errorMessage.includes('网络连接失败')) {
this.showRetryDialog(file);
}
} finally {
// 清理Mermaid图片缓存
FeishuApiClient.clearMermaidImageCache();
}
}
/**
* 执行正常的文档上传流程
* @param file 文件对象
* @param content 文档内容
* @param hasImages 是否包含图片
* @param orderedImageInfos 图片信息数组
* @param progressModal 进度模态框
* @returns 上传结果
*/
private async performNormalUpload(
file: TFile,
content: string,
hasImages: boolean,
orderedImageInfos: ImageInfo[],
progressModal: UploadProgressModal
): Promise<{ token: string; url: string }> {
let result: { token: string; url: string };
if (hasImages) {
// 有图片:使用富文本模式,传递正确顺序的图片信息
result = await this.feishuRichClient!.uploadDocumentWithImageInfos(
file.name, // 完整文件名(包含扩展名)用于上传到云空间
content,
this.settings.folderToken,
(status: string) => {
// 主文档上传占用55%-85%的进度区间,共30%
let currentProgress = 55;
if (status.includes('创建导入任务')) {
currentProgress = 60;
} else if (status.includes('等待处理') || status.includes('正在处理')) {
currentProgress = 65;
} else if (status.includes('处理中') || status.includes('转换')) {
currentProgress = 75;
} else if (status.includes('处理图片')) {
currentProgress = 80;
} else if (status.includes('完成')) {
currentProgress = 85;
}
progressModal.updateProgress(currentProgress, status);
},
orderedImageInfos
);
} else {
// 无图片:使用简单模式
result = await this.feishuClient!.uploadDocument(
file.name, // 完整文件名(包含扩展名)用于上传到云空间
content,
this.settings.folderToken,
(status: string) => {
// 主文档上传占用55%-85%的进度区间,共30%
let currentProgress = 55;
if (status.includes('创建导入任务')) {
currentProgress = 60;
} else if (status.includes('等待处理') || status.includes('正在处理')) {
currentProgress = 65;
} else if (status.includes('处理中') || status.includes('转换')) {
currentProgress = 75;
} else if (status.includes('完成')) {
currentProgress = 85;
}
progressModal.updateProgress(currentProgress, status);
}
);
}
return result;
}
/**
* 自动处理文档中的 YAML frontmatter(无用户交互)
* @param docToken 文档Token
* @param yamlInfo YAML信息
*/
private async autoProcessYaml(docToken: string, yamlInfo: YamlInfo): Promise<void> {
try {
if (!this.feishuClient) {
console.warn('[飞书插件] 飞书客户端未初始化,跳过 YAML 处理');
return;
}
const yamlProcessor = new YamlProcessor(this.feishuClient);
// 等待一下确保文档完全同步
await new Promise(resolve => setTimeout(resolve, 2000));
// 在文档开头插入YAML信息块
await yamlProcessor.insertYamlBlockInDocument(docToken, yamlInfo, 0);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`[飞书插件] YAML 处理失败: ${errorMessage}`);
if (this.settings.debugLoggingEnabled) {
console.debug('[飞书插件] YAML 处理失败详情:', error);
}
}
}
/**
* 自动转换文档中的 Callout(无用户交互)
* 在图片处理完成后调用,此时文档已完全同步
* @param docToken 文档Token
* @param cachedCallouts 预先缓存的Callout数组
*/
private async autoConvertCallouts(docToken: string, cachedCallouts: CalloutInfo[]): Promise<void> {
try {
if (!this.feishuClient) {
console.warn('[飞书插件] 飞书客户端未初始化,跳过 Callout 转换');
return;
}
if (cachedCallouts.length > 0) {
const calloutConverter = new CalloutConverter(this.feishuClient);
// 等待一下确保文档完全同步
await new Promise(resolve => setTimeout(resolve, 1000));
// 获取文档的所有块
const documentBlocks = await this.feishuClient.getDocumentBlocksDetailed(docToken);
if (!documentBlocks || documentBlocks.length === 0) {
console.warn('[飞书插件] 无法获取文档块信息,跳过 Callout 转换');
return;
}
// 为文档块添加索引信息
const blocksWithIndex = calloutConverter.addIndexToBlocks(documentBlocks);
// 查找匹配的引用块
const matches = calloutConverter.findMatchingQuoteBlocks(blocksWithIndex, cachedCallouts);
if (matches.length === 0) {
return;
}
// 逐个处理 Callout 转换(先插入后删除)
for (const { callout, block } of matches) {
await calloutConverter.processSingleCalloutConversion(
docToken,
callout,
block
);
}
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`[飞书插件] Callout 自动转换出错: ${errorMessage}`);
if (this.settings.debugLoggingEnabled) {
console.debug('[飞书插件] Callout 自动转换出错详情:', error);
}
// 转换失败不影响主流程,继续执行
}
}
/**
* 显示重试对话框
*/
private showRetryDialog(file: TFile): void {
const modal = new RetryModal(this.app, () => {
// 重试上传
void this.uploadFile(file);
});
modal.open();
}
/**
* 添加上传历史记录
*/
async addUploadHistory(title: string, url: string, docToken: string, permissions?: { isPublic: boolean; allowCopy: boolean; allowCreateCopy: boolean }, referencedDocuments?: Array<{title: string; docToken: string; url: string}>, isReferencedDocument?: boolean): Promise<void> {
const now = new Date();
const uploadTime = now.getFullYear() + '-' +
String(now.getMonth() + 1).padStart(2, '0') + '-' +
String(now.getDate()).padStart(2, '0') + ' ' +
String(now.getHours()).padStart(2, '0') + ':' +
String(now.getMinutes()).padStart(2, '0');
const historyItem: UploadHistoryItem = {
title,
url,
uploadTime,
docToken,
...(permissions && { permissions }),
...(referencedDocuments && { referencedDocuments }),
...(isReferencedDocument && { isReferencedDocument })
};
// 添加到历史记录开头
this.settings.uploadHistory.unshift(historyItem);
// 增加上传次数
this.settings.uploadCount++;
// 文档记录永久保存,不进行清理
// 只保存数据,不重新初始化客户端(加密敏感数据)
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
}
/**
* 更新历史记录中的权限设置
*/
async updateHistoryPermissions(docToken: string, permissions: { isPublic: boolean; allowCopy: boolean; allowCreateCopy: boolean }): Promise<void> {
const historyItem = this.settings.uploadHistory.find(item => item.docToken === docToken);
if (historyItem) {
historyItem.permissions = permissions;
// 只保存数据,不重新初始化客户端(加密敏感数据)
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
}
}
/**
* 更新现有历史记录的时间戳
*/
async updateHistoryTimestamp(docToken: string): Promise<void> {
const historyItem = this.settings.uploadHistory.find(item => item.docToken === docToken);
if (historyItem) {
const now = new Date();
const uploadTime = now.getFullYear() + '-' +
String(now.getMonth() + 1).padStart(2, '0') + '-' +
String(now.getDate()).padStart(2, '0') + ' ' +
String(now.getHours()).padStart(2, '0') + ':' +
String(now.getMinutes()).padStart(2, '0');
historyItem.uploadTime = uploadTime;
// 将更新的记录移到历史记录开头
const index = this.settings.uploadHistory.indexOf(historyItem);
if (index > 0) {
this.settings.uploadHistory.splice(index, 1);
this.settings.uploadHistory.unshift(historyItem);
}
// 只保存数据,不重新初始化客户端(加密敏感数据)
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
}
}
/**
* 删除单个历史记录项
* @param docToken 文档token
*/
async deleteHistoryItem(docToken: string): Promise<void> {
const index = this.settings.uploadHistory.findIndex(item => item.docToken === docToken);
if (index !== -1) {
this.settings.uploadHistory.splice(index, 1);
// 只保存数据,不重新初始化客户端(加密敏感数据)
const encryptedSettings = await CryptoUtils.encryptSensitiveSettings(this.settings);
await this.saveData(encryptedSettings);
}
}
/**
* 删除文件并清除历史记录
* @param docToken 文档token
* @param title 文档标题
*/
async deleteFileAndHistory(docToken: string, title: string): Promise<void> {
if (!this.feishuClient) {
throw new Error('飞书客户端未初始化');
}
try {
// 调用删除文件API
await this.feishuClient.deleteFile(docToken);
// 增加API调用计数
await this.incrementApiCallCount();
// 删除历史记录
await this.deleteHistoryItem(docToken);
this.notificationManager.showNotice(`文件 "${title}" 已删除`, 3000);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.error(`[飞书插件] 删除文件失败: ${errorMessage}`);