-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
3228 lines (2810 loc) · 105 KB
/
background.js
File metadata and controls
3228 lines (2810 loc) · 105 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
// Background service worker for QuickFinder extension
// Global AI service instances
let aiServiceOptimized = null;
let aiServiceManager = null;
let aiServiceInstance = null;
// Global preload manager instance
let preloadManager = null;
// 性能优化 - 智能缓存系统
class PerformanceCache {
constructor() {
this.bookmarksCache = null;
this.historyCache = null;
this.searchResultsCache = new Map(); // 搜索结果缓存
this.pinyinIndexCache = new Map(); // 拼音索引缓存
// 缓存时间戳
this.bookmarksCacheTime = 0;
this.historyCacheTime = 0;
this.pinyinCacheTime = 0;
// 缓存配置 - 优化为更实时的数据同步
this.config = {
bookmarksCacheDuration: 5 * 60 * 1000, // 缩短到5分钟
historyCacheDuration: 2 * 60 * 1000, // 缩短到2分钟,更实时
searchResultsCacheDuration: 1 * 60 * 1000, // 缩短到1分钟
pinyinCacheDuration: 5 * 60 * 1000, // 缩短到5分钟
maxSearchResults: 1000, // 最大缓存搜索结果数
maxMemoryMB: 50, // 最大内存使用50MB
cleanupInterval: 30 * 60 * 1000, // 30分钟清理一次
realtimeUpdateDelay: 500 // 实时更新延迟500ms
};
// 性能监控
this.stats = {
cacheHits: 0,
cacheMisses: 0,
totalSearches: 0,
avgResponseTime: 0,
memoryUsage: 0
};
// 启动定期清理
this.startPeriodicCleanup();
console.log('🚀 Performance Cache System initialized');
}
// 启动定期清理
startPeriodicCleanup() {
setInterval(() => {
this.cleanupExpiredCache();
this.monitorMemoryUsage();
}, this.config.cleanupInterval);
}
// 清理过期缓存
cleanupExpiredCache() {
const now = Date.now();
let cleanedCount = 0;
// 清理搜索结果缓存
for (const [key, value] of this.searchResultsCache.entries()) {
if (now - value.timestamp > this.config.searchResultsCacheDuration) {
this.searchResultsCache.delete(key);
cleanedCount++;
}
}
// 清理过期的主缓存
if (now - this.bookmarksCacheTime > this.config.bookmarksCacheDuration) {
this.bookmarksCache = null;
this.bookmarksCacheTime = 0;
}
if (now - this.historyCacheTime > this.config.historyCacheDuration) {
this.historyCache = null;
this.historyCacheTime = 0;
}
if (now - this.pinyinCacheTime > this.config.pinyinCacheDuration) {
this.pinyinIndexCache.clear();
this.pinyinCacheTime = 0;
}
console.log(`🧹 Cache cleanup: removed ${cleanedCount} expired entries`);
}
// 监控内存使用
monitorMemoryUsage() {
const memoryInfo = this.estimateMemoryUsage();
this.stats.memoryUsage = memoryInfo.totalMB;
if (memoryInfo.totalMB > this.config.maxMemoryMB) {
console.warn(`⚠️ Memory usage high: ${memoryInfo.totalMB}MB, forcing cleanup`);
this.forceCleanup();
}
console.log(`📊 Memory usage: ${memoryInfo.totalMB}MB (${memoryInfo.breakdown})`);
}
// 估算内存使用
estimateMemoryUsage() {
const bookmarksSize = this.bookmarksCache ? JSON.stringify(this.bookmarksCache).length : 0;
const historySize = this.historyCache ? JSON.stringify(this.historyCache).length : 0;
const searchResultsSize = JSON.stringify([...this.searchResultsCache.values()]).length;
const pinyinSize = JSON.stringify([...this.pinyinIndexCache.entries()]).length;
const totalBytes = bookmarksSize + historySize + searchResultsSize + pinyinSize;
const totalMB = (totalBytes / (1024 * 1024)).toFixed(2);
return {
totalMB: parseFloat(totalMB),
breakdown: `Bookmarks: ${(bookmarksSize/1024).toFixed(1)}KB, History: ${(historySize/1024).toFixed(1)}KB, Search: ${(searchResultsSize/1024).toFixed(1)}KB, Pinyin: ${(pinyinSize/1024).toFixed(1)}KB`
};
}
// 强制清理
forceCleanup() {
// 清理一半的搜索结果缓存
const entries = [...this.searchResultsCache.entries()];
const toDelete = entries.slice(0, Math.floor(entries.length / 2));
toDelete.forEach(([key]) => this.searchResultsCache.delete(key));
// 清理拼音缓存
this.pinyinIndexCache.clear();
this.pinyinCacheTime = 0;
console.log('🔥 Forced cache cleanup completed');
}
// 获取性能统计
getStats() {
return {
...this.stats,
cacheHitRate: this.stats.totalSearches > 0 ?
(this.stats.cacheHits / this.stats.totalSearches * 100).toFixed(2) + '%' : '0%',
memoryUsage: this.stats.memoryUsage + 'MB'
};
}
// 清理所有搜索结果缓存 - 当底层数据变化时调用
clearSearchResultsCache() {
const cacheSize = this.searchResultsCache.size;
this.searchResultsCache.clear();
console.log(`🧹 Cleared ${cacheSize} search result cache entries`);
}
// 强制刷新历史记录缓存
forceRefreshHistoryCache() {
this.historyCache = null;
this.historyCacheTime = 0;
this.clearSearchResultsCache(); // 同时清理搜索缓存
console.log('🔄 Forced history cache refresh');
}
// 强制刷新书签缓存
forceRefreshBookmarksCache() {
this.bookmarksCache = null;
this.bookmarksCacheTime = 0;
this.clearSearchResultsCache(); // 同时清理搜索缓存
console.log('🔄 Forced bookmarks cache refresh');
}
// 检查数据是否需要刷新(用于实时同步)
needsDataRefresh() {
const now = Date.now();
const historyStale = !this.historyCache || (now - this.historyCacheTime) > this.config.historyCacheDuration;
const bookmarksStale = !this.bookmarksCache || (now - this.bookmarksCacheTime) > this.config.bookmarksCacheDuration;
return {
history: historyStale,
bookmarks: bookmarksStale,
any: historyStale || bookmarksStale
};
}
}
// 全局缓存实例
const performanceCache = new PerformanceCache();
// 扩展启动时的预加载
async function initializeExtension() {
console.log('🚀 Initializing QuickFinder extension...');
try {
// 预加载核心数据
const startTime = performance.now();
await Promise.all([
preloadBookmarks(),
preloadHistory()
]);
const endTime = performance.now();
console.log(`✅ Extension initialized in ${(endTime - startTime).toFixed(2)}ms`);
// 输出性能统计
console.log('📊 Performance stats:', performanceCache.getStats());
} catch (error) {
console.error('❌ Extension initialization failed:', error);
}
}
// 监听扩展启动事件
chrome.runtime.onStartup.addListener(async () => {
await initializeExtension();
await reinjectContentScriptsToAllTabs();
});
chrome.runtime.onInstalled.addListener(async (details) => {
await initializeExtension();
// 如果是扩展更新或重新加载,重新注入所有页面
if (details.reason === 'install' || details.reason === 'update') {
console.log('🔄 Extension installed/updated, reinjecting content scripts to all tabs...');
await reinjectContentScriptsToAllTabs();
}
});
// 监听书签变化,清除相关缓存并立即重新加载 - 改进版本
chrome.bookmarks.onCreated.addListener(async (id, bookmark) => {
console.log('📚 Bookmark created:', bookmark.title);
// 使用新的强制刷新方法,同时清理搜索缓存
performanceCache.forceRefreshBookmarksCache();
// 延迟重新加载书签缓存,确保新书签能被搜索到
setTimeout(async () => {
try {
await getAllBookmarks();
console.log('✅ Bookmark cache refreshed after creation');
} catch (error) {
console.error('❌ Failed to refresh bookmark cache:', error);
}
}, performanceCache.config.realtimeUpdateDelay);
});
chrome.bookmarks.onRemoved.addListener(async (id, removeInfo) => {
console.log('📚 Bookmark removed:', id);
performanceCache.forceRefreshBookmarksCache();
// 延迟重新加载
setTimeout(async () => {
try {
await getAllBookmarks();
console.log('✅ Bookmark cache refreshed after removal');
} catch (error) {
console.error('❌ Failed to refresh bookmark cache:', error);
}
}, performanceCache.config.realtimeUpdateDelay);
});
chrome.bookmarks.onChanged.addListener(async (id, changeInfo) => {
console.log('📚 Bookmark changed:', changeInfo);
performanceCache.forceRefreshBookmarksCache();
// 延迟重新加载
setTimeout(async () => {
try {
await getAllBookmarks();
console.log('✅ Bookmark cache refreshed after change');
} catch (error) {
console.error('❌ Failed to refresh bookmark cache:', error);
}
}, performanceCache.config.realtimeUpdateDelay);
});
chrome.bookmarks.onMoved.addListener(async (id, moveInfo) => {
console.log('📚 Bookmark moved:', id);
performanceCache.forceRefreshBookmarksCache();
// 延迟重新加载
setTimeout(async () => {
try {
await getAllBookmarks();
console.log('✅ Bookmark cache refreshed after move');
} catch (error) {
console.error('❌ Failed to refresh bookmark cache:', error);
}
}, performanceCache.config.realtimeUpdateDelay);
});
// 简化版拼音转换(与lib中的保持一致)
const PINYIN_MAP = {
'中': 'zhong', '国': 'guo', '人': 'ren', '大': 'da', '小': 'xiao',
'好': 'hao', '的': 'de', '是': 'shi', '在': 'zai', '有': 'you',
'我': 'wo', '他': 'ta', '她': 'ta', '它': 'ta', '们': 'men',
'这': 'zhe', '那': 'na', '个': 'ge', '了': 'le', '不': 'bu',
'一': 'yi', '二': 'er', '三': 'san', '四': 'si', '五': 'wu',
'六': 'liu', '七': 'qi', '八': 'ba', '九': 'jiu', '十': 'shi',
'百': 'bai', '千': 'qian', '万': 'wan', '年': 'nian', '月': 'yue',
'日': 'ri', '时': 'shi', '分': 'fen', '秒': 'miao', '上': 'shang',
'下': 'xia', '左': 'zuo', '右': 'you', '前': 'qian', '后': 'hou',
'东': 'dong', '南': 'nan', '西': 'xi', '北': 'bei', '内': 'nei',
'外': 'wai', '里': 'li', '面': 'mian', '边': 'bian', '来': 'lai',
'去': 'qu', '到': 'dao', '从': 'cong', '向': 'xiang', '对': 'dui',
'和': 'he', '与': 'yu', '及': 'ji', '以': 'yi', '为': 'wei',
'被': 'bei', '把': 'ba', '让': 'rang', '使': 'shi', '得': 'de',
'着': 'zhe', '过': 'guo', '起': 'qi', '开': 'kai', '关': 'guan',
'打': 'da', '做': 'zuo', '说': 'shuo', '看': 'kan', '听': 'ting',
'想': 'xiang', '知': 'zhi', '道': 'dao', '会': 'hui', '能': 'neng',
'可': 'ke', '要': 'yao', '应': 'ying', '该': 'gai', '必': 'bi',
'须': 'xu', '需': 'xu', '用': 'yong', '给': 'gei', '拿': 'na',
'放': 'fang', '买': 'mai', '卖': 'mai', '吃': 'chi', '喝': 'he',
'穿': 'chuan', '住': 'zhu', '行': 'xing', '走': 'zou', '跑': 'pao',
'飞': 'fei', '游': 'you', '泳': 'yong', '学': 'xue', '习': 'xi',
'工': 'gong', '作': 'zuo', '生': 'sheng', '活': 'huo', '家': 'jia',
'庭': 'ting', '父': 'fu', '母': 'mu', '子': 'zi', '女': 'nv',
'男': 'nan', '老': 'lao', '少': 'shao', '新': 'xin', '旧': 'jiu',
'高': 'gao', '低': 'di', '长': 'chang', '短': 'duan', '宽': 'kuan',
'窄': 'zhai', '厚': 'hou', '薄': 'bao', '重': 'zhong', '轻': 'qing',
'快': 'kuai', '慢': 'man', '早': 'zao', '晚': 'wan', '多': 'duo',
'少': 'shao', '全': 'quan', '半': 'ban', '空': 'kong', '满': 'man',
'红': 'hong', '黄': 'huang', '蓝': 'lan', '绿': 'lv', '白': 'bai',
'黑': 'hei', '灰': 'hui', '粉': 'fen', '紫': 'zi', '书': 'shu',
'本': 'ben', '页': 'ye', '字': 'zi', '词': 'ci', '句': 'ju',
'段': 'duan', '章': 'zhang', '文': 'wen', '网': 'wang', '站': 'zhan',
'链': 'lian', '接': 'jie', '地': 'di', '址': 'zhi', '搜': 'sou',
'索': 'suo', '查': 'cha', '找': 'zhao', '发': 'fa', '现': 'xian',
'结': 'jie', '果': 'guo', '信': 'xin', '息': 'xi', '数': 'shu',
'据': 'ju', '件': 'jian', '图': 'tu', '片': 'pian', '视': 'shi',
'频': 'pin', '音': 'yin', '乐': 'le', '电': 'dian', '影': 'ying',
'戏': 'xi', '软': 'ruan', '应': 'ying', '程': 'cheng', '序': 'xu',
'系': 'xi', '统': 'tong', '设': 'she', '置': 'zhi', '配': 'pei',
'管': 'guan', '理': 'li', '员': 'yuan', '户': 'hu', '密': 'mi',
'码': 'ma', '登': 'deng', '录': 'lu', '注': 'zhu', '册': 'ce',
'退': 'tui', '出': 'chu', '保': 'bao', '存': 'cun', '删': 'shan',
'除': 'chu', '修': 'xiu', '改': 'gai', '更': 'geng', '添': 'tian',
'加': 'jia', '创': 'chuang', '建': 'jian', '编': 'bian', '辑': 'ji',
'复': 'fu', '制': 'zhi', '粘': 'zhan', '贴': 'tie', '剪': 'jian',
'切': 'qie', '撤': 'che', '销': 'xiao', '重': 'chong', '确': 'que',
'定': 'ding', '取': 'qu', '消': 'xiao', '帮': 'bang', '助': 'zhu',
'于': 'yu', '版': 'ban', '权': 'quan', '联': 'lian', '反': 'fan',
'馈': 'kui', '意': 'yi', '见': 'jian', '建': 'jian', '议': 'yi',
// 技术相关词汇 - 支持"advance"等词汇的拼音搜索
'高': 'gao', '级': 'ji', '进': 'jin', '阶': 'jie', '先': 'xian',
'进': 'jin', '技': 'ji', '术': 'shu', '科': 'ke', '学': 'xue',
'研': 'yan', '究': 'jiu', '开': 'kai', '发': 'fa', '编': 'bian',
'程': 'cheng', '代': 'dai', '码': 'ma', '算': 'suan', '法': 'fa',
'数': 'shu', '据': 'ju', '库': 'ku', '服': 'fu', '务': 'wu',
'器': 'qi', '客': 'ke', '户': 'hu', '端': 'duan', '界': 'jie',
'面': 'mian', '设': 'she', '计': 'ji', '架': 'jia', '构': 'gou',
'框': 'kuang', '架': 'jia', '模': 'mo', '块': 'kuai', '组': 'zu',
'件': 'jian', '功': 'gong', '能': 'neng', '特': 'te', '性': 'xing',
'优': 'you', '化': 'hua', '性': 'xing', '能': 'neng', '效': 'xiao',
'率': 'lv', '速': 'su', '度': 'du', '质': 'zhi', '量': 'liang',
'稳': 'wen', '定': 'ding', '安': 'an', '全': 'quan', '可': 'ke',
'靠': 'kao', '扩': 'kuo', '展': 'zhan', '维': 'wei', '护': 'hu',
'测': 'ce', '试': 'shi', '调': 'tiao', '试': 'shi', '部': 'bu',
'署': 'shu', '发': 'fa', '布': 'bu', '版': 'ban', '本': 'ben',
'更': 'geng', '新': 'xin', '升': 'sheng', '级': 'ji', '修': 'xiu',
'复': 'fu', '备': 'bei', '份': 'fen', '恢': 'hui', '复': 'fu',
'监': 'jian', '控': 'kong', '日': 'ri', '志': 'zhi', '记': 'ji',
'录': 'lu', '分': 'fen', '析': 'xi', '统': 'tong', '计': 'ji',
'报': 'bao', '告': 'gao', '文': 'wen', '档': 'dang', '说': 'shuo',
'明': 'ming', '教': 'jiao', '程': 'cheng', '指': 'zhi', '南': 'nan',
'手': 'shou', '册': 'ce', '参': 'can', '考': 'kao', '示': 'shi',
'例': 'li', '演': 'yan', '示': 'shi', '培': 'pei', '训': 'xun',
'学': 'xue', '习': 'xi', '实': 'shi', '践': 'jian', '项': 'xiang',
'目': 'mu', '任': 'ren', '务': 'wu', '计': 'ji', '划': 'hua',
'方': 'fang', '案': 'an', '策': 'ce', '略': 'lve', '流': 'liu',
'程': 'cheng', '步': 'bu', '骤': 'zhou', '操': 'cao', '作': 'zuo'
};
// 拼音处理函数
function hasChinese(text) {
return /[\u4e00-\u9fff]/.test(text);
}
function convertToPinyin(text) {
if (!text || !hasChinese(text)) {
return [text.toLowerCase()];
}
const result = [];
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (PINYIN_MAP[char]) {
result.push(PINYIN_MAP[char]);
} else if (/[a-zA-Z0-9]/.test(char)) {
result.push(char.toLowerCase());
}
}
return result;
}
function generatePinyinIndex(text) {
if (!text) return [];
const indexes = new Set();
// 原文
indexes.add(text.toLowerCase());
if (hasChinese(text)) {
// 完整拼音
const fullPinyin = convertToPinyin(text).join('');
if (fullPinyin) indexes.add(fullPinyin);
// 首字母拼音
const firstLetters = convertToPinyin(text).map(py => py[0] || '').join('');
if (firstLetters) indexes.add(firstLetters);
// 分词拼音(简单实现)
const words = text.split(/[\s\-_]+/);
words.forEach(word => {
if (word && hasChinese(word)) {
const wordPinyin = convertToPinyin(word).join('');
if (wordPinyin) indexes.add(wordPinyin);
const wordFirstLetters = convertToPinyin(word).map(py => py[0] || '').join('');
if (wordFirstLetters) indexes.add(wordFirstLetters);
}
});
}
return Array.from(indexes);
}
// 增强的拼音匹配检测函数 - 支持部分字符匹配
function searchPinyinMatch(query, indexes) {
if (!query || !indexes || indexes.length === 0) return false;
const lowerQuery = query.toLowerCase().trim();
return indexes.some(index => {
const lowerIndex = index.toLowerCase();
// 1. 完整匹配
if (lowerIndex.includes(lowerQuery) || lowerQuery.includes(lowerIndex)) {
return true;
}
// 2. 部分字符匹配 - 支持跨词搜索
if (partialMatch(lowerQuery, lowerIndex)) {
return true;
}
// 3. 分词后的部分匹配
const words = lowerIndex.split(/[\s\-_]+/);
return words.some(word => {
return word.includes(lowerQuery) || partialMatch(lowerQuery, word);
});
});
}
// 部分字符匹配算法
function partialMatch(query, target) {
if (!query || !target) return false;
// 如果查询长度小于3,只进行前缀匹配避免过多误匹配
if (query.length < 3) {
return target.startsWith(query);
}
// 对于较长的查询,支持更灵活的部分匹配
let queryIndex = 0;
let targetIndex = 0;
while (queryIndex < query.length && targetIndex < target.length) {
if (query[queryIndex] === target[targetIndex]) {
queryIndex++;
}
targetIndex++;
}
// 如果查询的所有字符都在目标字符串中按顺序找到
return queryIndex === query.length;
}
// 增强的标题匹配函数 - 优化部分匹配
function enhancedTitleMatch(query, title) {
if (!query || !title) return false;
const queryLower = query.toLowerCase().trim();
const titleLower = title.toLowerCase();
// 1. 直接包含匹配 - 最高优先级
if (titleLower.includes(queryLower)) {
return true;
}
// 2. 分词匹配 - 检查每个单词
const titleWords = titleLower.split(/[\s\-_\.]+/);
const hasWordMatch = titleWords.some(word => {
// 直接包含或部分匹配
return word.includes(queryLower) ||
word.startsWith(queryLower) ||
partialMatch(queryLower, word);
});
if (hasWordMatch) {
return true;
}
// 3. 跨词部分匹配
const titleWithoutSpaces = titleLower.replace(/[\s\-_\.]+/g, '');
if (partialMatch(queryLower, titleWithoutSpaces)) {
return true;
}
// 4. 特殊情况:查询是单词的开头部分
const queryStartsWord = titleWords.some(word => word.startsWith(queryLower));
if (queryStartsWord) {
return true;
}
return false;
}
// Enhanced AI Service for Service Worker with performance optimizations
class BackgroundAIService {
constructor() {
this.providers = {
siliconflow: {
name: '硅基流动 (SiliconFlow)',
apiUrl: 'https://api.siliconflow.cn/v1/chat/completions',
models: [
{ id: 'deepseek-ai/DeepSeek-V3', name: 'DeepSeek-V3', description: '深度求索V3模型' },
{ id: 'Qwen/Qwen2.5-72B-Instruct', name: 'Qwen2.5-72B', description: '通义千问2.5-72B' }
]
},
openai: {
name: 'OpenAI',
apiUrl: 'https://api.openai.com/v1/chat/completions',
models: [
{ id: 'gpt-4o', name: 'GPT-4o', description: 'OpenAI最新模型' },
{ id: 'gpt-4', name: 'GPT-4', description: 'GPT-4模型' }
]
},
google: {
name: 'Google Gemini',
apiUrl: 'https://generativelanguage.googleapis.com/v1beta/models',
models: [
{ id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro', description: '最新的高性能Gemini模型' },
{ id: 'gemini-2.5-flash', name: 'Gemini 2.5 Flash', description: '快速响应的Gemini 2.5模型' },
{ id: 'gemini-2.5-flash-lite', name: 'Gemini 2.5 Flash Lite', description: '轻量级Gemini 2.5模型' },
{ id: 'gemini-2.5-flash-lite preview-06-17', name: 'Gemini 2.5 Flash Lite Preview', description: 'Gemini 2.5 Flash Lite预览版' },
{ id: 'gemini-1.5-pro', name: 'Gemini 1.5 Pro', description: 'Gemini 1.5 Pro模型' },
{ id: 'gemini-1.5-flash', name: 'Gemini 1.5 Flash', description: 'Gemini 1.5 Flash模型' }
]
}
};
this.settings = null;
this.retryConfig = {
maxRetries: 3,
baseDelay: 1000,
maxDelay: 10000,
backoffFactor: 2
};
this.cache = new Map();
this.cacheTimeout = 5 * 60 * 1000; // 5分钟缓存
console.log('🔧 Enhanced Background AI Service initialized');
}
async loadSettings() {
try {
let result = {};
try {
result = await chrome.storage.local.get(['aiSettings']);
} catch (localError) {
console.warn('⚠️ Local storage failed:', localError);
result = await chrome.storage.sync.get(['aiSettings']);
}
this.settings = result.aiSettings || {
provider: 'siliconflow',
model: 'deepseek-ai/DeepSeek-V3',
apiKey: '',
enabledFeatures: ['smart-search', 'auto-categorize', 'summarize', 'recommendations']
};
console.log('📋 AI settings loaded:', {
provider: this.settings.provider,
model: this.settings.model,
hasApiKey: !!this.settings.apiKey
});
} catch (error) {
console.error('❌ Error loading AI settings:', error);
this.settings = {
provider: 'siliconflow',
model: 'deepseek-ai/DeepSeek-V3',
apiKey: '',
enabledFeatures: ['smart-search', 'auto-categorize', 'summarize', 'recommendations']
};
}
}
isFeatureEnabled(feature) {
return this.settings?.enabledFeatures?.includes(feature) || false;
}
isAvailable() {
return !!(this.settings?.apiKey && this.settings?.provider && this.providers[this.settings.provider]);
}
// 指数退避重试逻辑
async retryWithBackoff(operation, context = '') {
let lastError;
for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
try {
if (attempt > 0) {
const delay = Math.min(
this.retryConfig.baseDelay * Math.pow(this.retryConfig.backoffFactor, attempt - 1),
this.retryConfig.maxDelay
);
console.log(`🔄 Retry attempt ${attempt} for ${context} after ${delay}ms`);
await this.sleep(delay);
}
return await operation();
} catch (error) {
lastError = error;
// 检查是否为不可重试的错误
if (this.isNonRetryableError(error)) {
console.error(`❌ Non-retryable error in ${context}:`, error.message);
throw error;
}
if (attempt === this.retryConfig.maxRetries) {
console.error(`❌ Max retries exceeded for ${context}:`, error.message);
throw error;
}
console.warn(`⚠️ Attempt ${attempt + 1} failed for ${context}:`, error.message);
}
}
throw lastError;
}
// 判断是否为不可重试的错误
isNonRetryableError(error) {
if (error.status) {
// 4xx客户端错误通常不可重试
return error.status >= 400 && error.status < 500;
}
// 检查错误消息中的关键词
const nonRetryableKeywords = [
'invalid api key',
'unauthorized',
'forbidden',
'bad request',
'invalid input',
'quota exceeded permanently'
];
const errorMessage = error.message?.toLowerCase() || '';
return nonRetryableKeywords.some(keyword => errorMessage.includes(keyword));
}
// 工具函数:延迟
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// 缓存管理
getCacheKey(operation, data) {
return `${operation}:${JSON.stringify(data)}`;
}
getCachedResult(key) {
const cached = this.cache.get(key);
if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
console.log('📦 Using cached result for:', key.split(':')[0]);
return cached.result;
}
return null;
}
setCachedResult(key, result) {
this.cache.set(key, {
result: result,
timestamp: Date.now()
});
// 清理过期缓存
if (this.cache.size > 100) {
const now = Date.now();
for (const [k, v] of this.cache.entries()) {
if (now - v.timestamp > this.cacheTimeout) {
this.cache.delete(k);
}
}
}
}
async request(messages, options = {}) {
return await this.retryWithBackoff(async () => {
if (!this.isAvailable()) {
throw new Error('AI服务未配置或不可用');
}
// 对于Google Gemini,使用专用方法
if (this.settings.provider === 'google') {
return await this.requestGemini(messages, options);
}
const provider = this.providers[this.settings.provider];
const apiUrl = provider.apiUrl;
const apiKey = this.settings.apiKey;
const model = this.settings.model;
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
};
const requestBody = {
model: model,
messages: messages,
temperature: options.temperature || 0.7,
max_tokens: options.maxTokens || 2000
};
console.log('🚀 AI请求:', { provider: this.settings.provider, model, messageCount: messages.length });
const response = await fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody),
mode: 'cors'
});
if (!response.ok) {
const errorText = await response.text();
console.error('❌ API错误:', response.status, errorText);
const error = new Error(`API请求失败: ${response.status} ${response.statusText}`);
error.status = response.status;
error.response = errorText;
throw error;
}
const data = await response.json();
if (data.choices && data.choices[0] && data.choices[0].message) {
return data.choices[0].message.content;
}
throw new Error('无效的API响应格式');
}, `AI request to ${this.settings.provider}`);
}
// Google Gemini专用请求方法
async requestGemini(messages, options = {}) {
const provider = this.providers[this.settings.provider];
const model = this.settings.model;
const apiKey = this.settings.apiKey;
// 构建Gemini API URL
const apiUrl = `${provider.apiUrl}/${model}:generateContent?key=${apiKey}`;
// 转换消息格式为Gemini格式
const contents = messages.map(msg => ({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.role === 'system' ? `System: ${msg.content}` : msg.content }]
}));
const requestBody = {
contents: contents,
generationConfig: {
temperature: options.temperature || 0.7,
maxOutputTokens: options.maxTokens || 2000
}
};
console.log('🚀 Gemini API请求:', { model, messageCount: messages.length });
const response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestBody),
mode: 'cors'
});
if (!response.ok) {
const errorText = await response.text();
console.error('❌ Gemini API错误:', response.status, errorText);
const error = new Error(`Gemini API请求失败: ${response.status} ${response.statusText}`);
error.status = response.status;
error.response = errorText;
throw error;
}
const data = await response.json();
if (data.candidates && data.candidates[0] && data.candidates[0].content) {
return data.candidates[0].content.parts[0].text;
}
throw new Error('无效的Gemini API响应格式');
}
async smartSearch(query, bookmarks) {
console.log('🔍 Starting enhanced smartSearch for:', query);
// 检查缓存
const cacheKey = this.getCacheKey('smart-search', { query, bookmarkCount: bookmarks.length });
const cached = this.getCachedResult(cacheKey);
if (cached) {
return cached;
}
const messages = [
{
role: 'system',
content: `你是一个智能书签搜索助手。基于用户的自然语言查询,从书签列表中找到最相关的结果。
理解查询意图,匹配相关书签,按相关性排序。支持:
- 主题搜索(如"前端开发"、"机器学习")
- 功能搜索(如"在线工具"、"学习资源")
- 情感搜索(如"有趣的"、"实用的")
返回JSON格式:
{
"results": [
{
"id": "书签ID",
"title": "标题",
"url": "URL",
"relevanceScore": 0.95,
"reason": "匹配原因"
}
],
"totalFound": 数量,
"searchIntent": "查询意图分析"
}`
},
{
role: 'user',
content: `查询: "${query}"
书签数据:
${JSON.stringify(bookmarks.slice(0, 50).map(b => ({
id: b.id,
title: b.title,
url: b.url,
type: b.type || 'bookmark'
})), null, 2)}
请找出最相关的书签并解释匹配原因。`
}
];
try {
console.log('🚀 Sending enhanced smart search request...');
const response = await this.request(messages, { maxTokens: 1500 });
console.log('📥 Raw search response:', response);
// 清理响应
let cleanResponse = response.trim();
if (cleanResponse.includes('```')) {
cleanResponse = cleanResponse.replace(/^```(?:json)?\s*/, '').replace(/\s*```$/, '');
}
const result = JSON.parse(cleanResponse);
console.log('✅ Parsed search result:', result);
// 缓存结果
this.setCachedResult(cacheKey, result);
return result;
} catch (error) {
console.error('❌ 智能搜索失败:', error);
// 回退到简单搜索
console.log('🔄 Falling back to simple keyword search');
return this.fallbackSearch(query, bookmarks);
}
}
// 回退搜索方法
fallbackSearch(query, bookmarks) {
const queryLower = query.toLowerCase();
const results = bookmarks
.filter(bookmark =>
bookmark.title?.toLowerCase().includes(queryLower) ||
bookmark.url?.toLowerCase().includes(queryLower)
)
.slice(0, 10)
.map(bookmark => ({
id: bookmark.id,
title: bookmark.title,
url: bookmark.url,
relevanceScore: 0.5,
reason: '文本匹配'
}));
return {
results: results,
totalFound: results.length,
searchIntent: '简单文本搜索(AI不可用)',
fallback: true
};
}
async categorizeBookmarks(bookmarks) {
const messages = [
{
role: 'system',
content: '你是一个书签分类专家。将提供的书签按照内容主题进行智能分类。返回JSON格式的分类结果。'
},
{
role: 'user',
content: `请对以下书签进行智能分类:\n\n${JSON.stringify(bookmarks.slice(0, 30), null, 2)}\n\n返回格式: {"categories": [{"name": "分类名", "bookmarks": [{"id": "ID", "title": "标题", "reason": "分类原因"}]}]}`
}
];
try {
const response = await this.request(messages);
return JSON.parse(response);
} catch (error) {
console.error('书签分类失败:', error);
return null;
}
}
async summarizeContent(url, title, content) {
const messages = [
{
role: 'system',
content: '你是一个内容总结专家。为提供的网页内容生成简洁的摘要。'
},
{
role: 'user',
content: `请为以下网页生成摘要:\n\n标题: ${title}\n网址: ${url}\n内容: ${content.slice(0, 2000)}\n\n请返回JSON格式: {"summary": "摘要内容", "keyPoints": ["要点1", "要点2"], "tags": ["标签1", "标签2"]}`
}
];
try {
const response = await this.request(messages);
return JSON.parse(response);
} catch (error) {
console.error('内容总结失败:', error);
return null;
}
}
async getRecommendations(bookmarks, context) {
console.log('🎯 Starting getRecommendations with:', {
bookmarkCount: bookmarks.length,
context: context.substring(0, 100) + '...'
});
const messages = [
{
role: 'system',
content: '你是一个智能推荐专家。基于用户的书签和当前上下文,提供个性化推荐。请严格按照JSON格式返回结果。'
},
{
role: 'user',
content: `基于以下信息提供智能推荐:
书签数据: ${JSON.stringify(bookmarks.slice(0, 10), null, 2)}
当前上下文: ${context}
请严格按照以下JSON格式返回结果,不要添加任何其他文字:
{
"relatedBookmarks": [
{
"id": "书签ID",
"title": "书签标题",
"url": "书签链接",
"reason": "推荐原因",
"relevanceScore": 0.95
}
],
"suggestedSearches": ["搜索建议1", "搜索建议2"],
"insights": ["洞察1", "洞察2"]
}`
}
];
try {
console.log('🚀 Sending recommendation request...');
const response = await this.request(messages, { maxTokens: 1000 });
console.log('📥 Raw recommendation response:', response);
// 清理响应中可能的多余文字
let cleanResponse = response.trim();
if (cleanResponse.startsWith('```json')) {
cleanResponse = cleanResponse.replace(/^```json\s*/, '').replace(/\s*```$/, '');
}
if (cleanResponse.startsWith('```')) {
cleanResponse = cleanResponse.replace(/^```\s*/, '').replace(/\s*```$/, '');
}
console.log('🧹 Cleaned response:', cleanResponse);
const result = JSON.parse(cleanResponse);
console.log('✅ Parsed recommendation result:', result);
return result;
} catch (error) {