-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutil.js
1106 lines (979 loc) · 35.7 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 添加 XML 转义函数
function escapeXml(unsafe) {
if (!unsafe) return '';
return unsafe
.replace(/[<>&'"]/g, c => {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
default: return c;
}
});
}
async function validateToken() {
const token = await LocalStorageMgr.get('token');
logger.debug('检查登录token是否过期', { token: token });
if (!token) {
return { valid: false, user: null };
}
try {
// 解析 JWT token
const tokenData = JSON.parse(atob(token.split('.')[1]));
// 检查 token 是否过期
if (tokenData.exp && tokenData.exp < Date.now() / 1000) {
// token 已过期,清除登录状态
await LocalStorageMgr.remove(['token']);
return { valid: false, user: null };
}
return { valid: true, user: tokenData };
} catch (error) {
logger.error('Token 解析失败:', error);
return { valid: false, user: null };
}
}
// 安全地发送消息的辅助函数
function sendMessageSafely(message, callback = null) {
message.env = EnvIdentifier;
chrome.runtime.sendMessage(message, (response) => {
// 检查是否有错误,但不做任何处理
// 这样可以防止未捕获的错误
const lastError = chrome.runtime.lastError;
if (lastError) {
logger.debug('消息处理失败:', {
error: lastError.message,
message: message
});
}
if (callback) {
callback(response);
}
});
}
function handleRuntimeError() {
const error = chrome.runtime.lastError;
if (error) {
throw new Error(error);
}
}
// 获取网站图标的辅函数
async function getFaviconUrl(bookmarkUrl) {
try {
const url = new URL(chrome.runtime.getURL("/_favicon/"));
url.searchParams.set("pageUrl", bookmarkUrl);
url.searchParams.set("size", "32");
return url.toString();
} catch (error) {
logger.error('获取网站图标失败:', error);
return 'icons/default_favicon.png'; // 返回默认图标
}
}
async function recordBookmarkChange(bookmarks, isDeleted = false, beginSync = true, onError = null) {
sendMessageSafely({
type: MessageType.SYNC_BOOKMARK_CHANGE,
data: { bookmarks, isDeleted, beginSync }
}, (response) => {
logger.debug("recordBookmarkChange response", response);
if (!response.success && onError) {
onError(response.error);
}
});
}
// 检查页面是否已收藏
async function checkIfPageSaved(url) {
const result = await LocalStorageMgr.getBookmark(url, true);
return !!result;
}
// 更新扩展图标状态
async function updateExtensionIcon(tabId, isSaved) {
try {
await chrome.action.setIcon({
tabId: tabId,
path: {
"16": `icons/${isSaved ? 'saved' : 'unsaved'}_16.png`,
"32": `icons/${isSaved ? 'saved' : 'unsaved'}_32.png`,
"48": `icons/${isSaved ? 'saved' : 'unsaved'}_48.png`,
"128": `icons/${isSaved ? 'saved' : 'unsaved'}_128.png`
}
});
} catch (error) {
logger.error('更新图标失败:', {
error: error.message,
tabId: tabId,
isSaved: isSaved,
stack: error.stack
});
}
}
async function openOptionsPage(section = 'overview') {
// 查找所有标签页
const tabs = await chrome.tabs.query({
url: chrome.runtime.getURL('settings.html*') // 使用通配符匹配任何hash
});
if (tabs.length > 0) {
chrome.runtime.openOptionsPage(() => {
sendMessageSafely({
type: MessageType.SWITCH_TO_TAB,
tab: section
});
});
} else {
// 如果没有找到settings页面,创建新页面
await chrome.tabs.create({
url: chrome.runtime.getURL('settings.html#' + section)
});
}
}
// 修改更新书签使用频率的函数
async function updateBookmarkUsage(url) {
try {
const data = await LocalStorageMgr.getBookmark(url, true);
if (data) {
const bookmark = data;
// 更新使用次数和最后使用时间
bookmark.useCount = calculateWeightedScore(
bookmark.useCount,
bookmark.lastUsed
) + 1;
bookmark.lastUsed = new Date().toISOString();
await LocalStorageMgr.setBookmark(url, bookmark);
return bookmark;
}
} catch (error) {
logger.error('更新书签使用频率失败:', error);
}
return null;
}
// 添加计算加权使用分数的函数
function calculateWeightedScore(useCount, lastUsed) {
if (!useCount || !lastUsed) return 0;
const now = new Date();
const lastUsedDate = new Date(lastUsed);
const daysDiff = Math.floor((now - lastUsedDate) / (1000 * 60 * 60 * 24)); // 转换为天数并向下取整
// 使用指数衰减函数
// 半衰期设为30天,即30天前的使用次数权重减半
const decayFactor = Math.exp(-Math.log(2) * daysDiff / 30);
// 基础分数 = 使用次数 * 时间衰减因子
const weightedScore = useCount * decayFactor;
// 返回四舍五入后的整数
return Math.round(weightedScore);
}
async function getAllBookmarks(includeChromeBookmarks = false) {
try {
// 获取扩展书签
const extensionBookmarks = await LocalStorageMgr.getBookmarks();
const extensionBookmarksMap = Object.entries(extensionBookmarks)
.reduce((map, [_, data]) => {
const bookmark = new UnifiedBookmark(data, BookmarkSource.EXTENSION);
map[bookmark.url] = bookmark;
return map;
}, {});
let chromeBookmarksMap = {};
// 获取Chrome书签
if (includeChromeBookmarks) {
const chromeBookmarks = await getChromeBookmarks();
chromeBookmarksMap = chromeBookmarks
.reduce((map, bookmark) => {
// 如果URL已经存在于扩展书签中,则跳过
if (extensionBookmarksMap[bookmark.url]) {
return map;
}
const unifiedBookmark = new UnifiedBookmark(bookmark, BookmarkSource.CHROME);
map[bookmark.url] = unifiedBookmark;
return map;
}, {});
}
// 合并并过滤扩展程序页面
const allBookmarks = { ...extensionBookmarksMap, ...chromeBookmarksMap };
return Object.entries(allBookmarks).reduce((map, [url, bookmark]) => {
if (!isNonMarkableUrl(bookmark.url)) {
map[url] = bookmark;
}
return map;
}, {});
} catch (error) {
logger.error('获取书签失败:', error);
return {};
}
}
async function getDisplayedBookmarks() {
const showChromeBookmarks = await SettingsManager.get('display.showChromeBookmarks');
return await getAllBookmarks(showChromeBookmarks);
}
// 获取Chrome书签的辅助函数
async function getChromeBookmarks() {
try {
const bookmarkTree = await chrome.bookmarks.getTree();
return flattenBookmarkTree(bookmarkTree);
} catch (error) {
logger.error('获取Chrome书签失败:', error);
return [];
}
}
// 展平书签树的辅助函数
function flattenBookmarkTree(nodes, parentFolders = []) {
const bookmarks = [];
function traverse(node, folders, level = 0) {
// 如果是文件夹,添加到路径中
if (!node.url) {
const currentFolders = [...folders];
if (node.title && level > 1) { // 排除根文件夹
currentFolders.push(node.title);
}
if (node.children) {
node.children.forEach(child => traverse(child, currentFolders, level + 1));
}
} else {
// 如果是书签,添加文件夹路径作为标签
bookmarks.push({
...node,
folderTags: folders.filter(folder => folder.trim() !== '')
});
}
}
nodes.forEach(node => traverse(node, parentFolders));
return bookmarks;
}
// 检查URL是否不可标记
function isNonMarkableUrl(url) {
try {
// 1. 基本URL格式检查
if (!url || typeof url !== 'string') {
logger.debug('无效URL格式');
return true;
}
// 2. 解析URL
const urlObj = new URL(url);
// 3. 定义不可标记的URL模式
const nonMarkablePatterns = {
// Chrome特殊页面
chromeInternal: {
pattern: /^chrome(?:-extension|-search|-devtools|-component)?:\/\//i,
description: 'Chrome内部页面',
example: 'chrome://, chrome-extension://'
},
// 浏览器设置和内部页面
browserInternal: {
pattern: /^(?:about|edge|browser|file|view-source):/i,
description: '浏览器内部页面',
example: 'about:blank, file:///'
},
// 扩展和应用页面
extensionPages: {
pattern: /^(?:chrome-extension|moz-extension|extension):\/\//i,
description: '浏览器扩展页面',
example: 'chrome-extension://'
},
// 本地开发服务器
localDevelopment: {
pattern: /^https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|::1)(?::[0-9]+)?(?:\/|$)/i,
description: '本地开发服务器',
example: 'http://localhost:3000/'
},
// Web Socket连接
webSocket: {
pattern: /^wss?:/i,
description: 'WebSocket连接',
example: 'ws://, wss://'
},
// 数据URL
dataUrl: {
pattern: /^data:/i,
description: '数据URL',
example: 'data:text/plain'
},
// 空白页和无效页面
emptyPages: {
pattern: /^(?:about:blank|about:newtab|about:home)$/i,
description: '空白页面',
example: 'about:blank'
}
};
// 4. 检查是否匹配任何不可标记模式
for (const [key, rule] of Object.entries(nonMarkablePatterns)) {
if (rule.pattern.test(url)) {
logger.debug('URL不可标记:', {
url: url,
reason: rule.description,
pattern: rule.pattern.toString(),
example: rule.example,
protocol: urlObj.protocol
});
// 5. 检查是否有例外情况
if (shouldAllowNonMarkableException(url, key)) {
logger.debug('URL虽然匹配不可标记规则,但属于例外情况');
continue;
}
return true;
}
}
// 6. 检查URL长度限制
const MAX_URL_LENGTH = 2048; // 常见浏览器的URL长度限制
if (url.length > MAX_URL_LENGTH) {
logger.debug('URL长度超出限制:', {
url: url.substring(0, 100) + '...',
length: url.length,
maxLength: MAX_URL_LENGTH
});
return true;
}
// 7. 检查协议安全性
if (!urlObj.protocol.match(/^https?:$/i)) {
logger.debug('不支持的URL协议:', {
url: url,
protocol: urlObj.protocol
});
return true;
}
return false;
} catch (error) {
logger.error('URL检查失败:', error);
return true; // 出错时默认为不可标记
}
}
// 处理特殊例外情况
function shouldAllowNonMarkableException(url, ruleKey) {
try {
const urlObj = new URL(url);
// 1. 允许特定的本地开发环境
if (ruleKey === 'localDevelopment') {
const allowedLocalPaths = [
/^\/docs\//i,
/^\/api\//i,
/^\/swagger\//i
];
if (allowedLocalPaths.some(pattern => pattern.test(urlObj.pathname))) {
return true;
}
}
// 2. 允许特定的Chrome扩展页面
if (ruleKey === 'extensionPages') {
const allowedExtensionPages = [
/\/documentation\.html$/i,
/\/help\.html$/i
];
if (allowedExtensionPages.some(pattern => pattern.test(urlObj.pathname))) {
return true;
}
}
return false;
} catch (error) {
logger.error('处理URL例外情况时出错:', error);
return false;
}
}
// 处理标签格式的辅助函数
function cleanTags(tags) {
return tags.map(tag => {
// 移除序号、星号和多余空格
return tag.replace(/^\d+\.\s*\*+|\*+/g, '').trim();
});
}
// 获取隐私模式设置
async function determinePrivacyMode(tab) {
const autoPrivacyMode = await SettingsManager.get('privacy.autoDetect');
const manualPrivacyMode = await SettingsManager.get('privacy.enabled');
// 打印隐私模式设置的调试信息
logger.debug('隐私模式设置:', {
autoPrivacyMode,
manualPrivacyMode
});
// 判断是否启用隐私模式
let isPrivate = false;
if (autoPrivacyMode) {
// 自动检测模式
isPrivate = await containsPrivateContent(tab.url);
} else {
// 手动控制模式
isPrivate = manualPrivacyMode;
}
return isPrivate;
}
async function isPrivacyModeManuallyDisabled() {
const autoPrivacyMode = await SettingsManager.get('privacy.autoDetect');
const manualPrivacyMode = await SettingsManager.get('privacy.enabled');
if (autoPrivacyMode) {
return false;
}
return !manualPrivacyMode;
}
// 检查URL是否包含隐私内容
async function containsPrivateContent(url) {
try {
const urlObj = new URL(url);
// 1. 定义隐私相关路径模式
const patterns = {
// 认证相关页面
auth: {
pattern: /^.*\/(?:login|signin|signup|register|password|auth|oauth|sso)(?:\/|$)/i,
scope: 'pathname',
description: '认证页面'
},
// 验证和确认页面
verification: {
pattern: /^.*\/(?:verify|confirmation|activate|reset)(?:\/|$)/i,
scope: 'pathname',
description: '验证确认页面'
},
// 邮箱和消息页面
mail: {
pattern: /^.*\/(?:mail|inbox|compose|message|chat|conversation)(?:\/|$)/i,
scope: 'pathname',
description: '邮件消息页面'
},
// 个人账户和设置页面
account: {
pattern: /^.*\/(?:profile|account|settings|preferences|dashboard|admin)(?:\/|$)/i,
scope: 'pathname',
description: '账户设置页面'
},
// 支付和财务页面
payment: {
pattern: /^.*\/(?:payment|billing|invoice|subscription|wallet)(?:\/|$)/i,
scope: 'pathname',
description: '支付财务页面'
},
// 敏感查询参数
sensitiveParams: {
pattern: /[?&](?:token|auth|key|password|secret|access_token|refresh_token|session|code)=/i,
scope: 'search',
description: '包含敏感参数'
}
};
// 2. 定义敏感域名列表
const privateDomains = {
// 邮箱服务
mail: [
'mail.google.com',
'outlook.office.com',
'mail.qq.com',
'mail.163.com',
'mail.126.com',
'mail.sina.com',
'mail.yahoo.com'
],
// 网盘服务
storage: [
'drive.google.com',
'onedrive.live.com',
'dropbox.com',
'pan.baidu.com'
],
// 社交和通讯平台的私密页面
social: [
'messages.google.com',
'web.whatsapp.com',
'web.telegram.org',
'discord.com/channels'
],
// 在线办公和协作平台的私密页面
workspace: [
'docs.google.com',
'sheets.googleapis.com',
'notion.so'
]
};
// 3. 检查域名
for (const [category, domains] of Object.entries(privateDomains)) {
if (domains.some(domain => urlObj.hostname === domain || urlObj.hostname.endsWith('.' + domain))) {
logger.debug('URL包含隐私内容:', {
url: url,
reason: `属于隐私域名类别: ${category}`,
domain: urlObj.hostname
});
// 检查是否有例外情况
if (shouldAllowPrivateException(url, 'domain', category)) {
continue;
}
return true;
}
}
// 4. 检查路径和查询参数
for (const [key, rule] of Object.entries(patterns)) {
let testString;
switch (rule.scope) {
case 'pathname':
testString = urlObj.pathname;
break;
case 'search':
testString = urlObj.search;
break;
case 'full':
testString = url;
break;
default:
continue;
}
if (rule.pattern.test(testString)) {
const match = testString.match(rule.pattern);
logger.debug('URL包含隐私内容:', {
url: url,
reason: rule.description,
pattern: rule.pattern.toString(),
matchedPart: match[0],
matchLocation: rule.scope
});
// 检查是否有例外情况
if (shouldAllowPrivateException(url, key, match)) {
continue;
}
return true;
}
}
// 5. 检查自定义隐私域名
const settings = await SettingsManager.getAll();
const customDomains = settings.privacy.customDomains || [];
for (const pattern of customDomains) {
let isMatch = false;
// 处理正则表达式模式
if (pattern.startsWith('/') && pattern.endsWith('/')) {
const regex = new RegExp(pattern.slice(1, -1));
isMatch = regex.test(urlObj.hostname);
}
// 处理通配符模式
else if (pattern.startsWith('*.')) {
const domain = pattern.slice(2);
isMatch = urlObj.hostname.endsWith(domain);
}
// 处理普通域名
else {
isMatch = urlObj.hostname === pattern;
}
if (isMatch) {
logger.debug('URL匹配自定义隐私域名:', {
url: url,
pattern: pattern
});
return true;
}
}
return false;
} catch (error) {
logger.error('隐私内容检查失败:', error);
return true; // 出错时从安全角度返回true
}
}
// 处理隐私检测的例外情况
function shouldAllowPrivateException(url, ruleKey, context) {
try {
const urlObj = new URL(url);
// 1. 允许公开的文档页面
if (context === 'workspace') {
const publicDocPatterns = [
/\/public\//i,
/[?&]sharing=public/i,
/[?&]view=public/i
];
if (publicDocPatterns.some(pattern => pattern.test(url))) {
return true;
}
}
// 2. 允许公开的个人主页
if (ruleKey === 'account') {
const publicProfilePatterns = [
/\/public\/profile\//i,
/\/users\/[^\/]+$/i,
/\/@[^\/]+$/i
];
if (publicProfilePatterns.some(pattern => pattern.test(urlObj.pathname))) {
return true;
}
}
// 3. 允许特定域名的登录页面(如开发文档)
if (ruleKey === 'auth') {
const allowedAuthDomains = [
'developer.mozilla.org',
'docs.github.com',
'learn.microsoft.com'
];
if (allowedAuthDomains.some(domain => urlObj.hostname.endsWith(domain))) {
return true;
}
}
// 4. 允许公开的支付文档或API文档
if (ruleKey === 'payment') {
const publicPaymentDocs = [
/\/docs\/payment/i,
/\/api\/payment/i,
/\/guides\/billing/i
];
if (publicPaymentDocs.some(pattern => pattern.test(urlObj.pathname))) {
return true;
}
}
return false;
} catch (error) {
logger.error('处理隐私例外情况时出错:', error);
return false;
}
}
function isContentFulUrl(url) {
try {
const urlObj = new URL(url);
// 1. 定义更精确的匹配规则
const patterns = {
// 错误页面 - 仅匹配路径部分
errors: {
pattern: /^.*\/(404|403|500|error|not[-\s]?found)(?:\.html?)?$/i,
scope: 'pathname',
description: '错误页面'
},
// 维护页面 - 仅匹配路径部分
maintenance: {
pattern: /^.*\/(maintenance|unavailable|blocked)(?:\.html?)?$/i,
scope: 'pathname',
description: '维护页面'
},
// 预览页面 - 需要考虑查询参数
preview: {
pattern: /^.*\/preview\/|[?&](?:preview|mode)=(?:preview|temp)/i,
scope: 'full',
description: '预览页面'
},
// 下载/上传页面 - 仅匹配路径结尾
fileTransfer: {
pattern: /\/(download|upload)(?:\/|$)/i,
scope: 'pathname',
description: '下载上传页面'
},
// 支付和订单页面 - 需要更精确的匹配
payment: {
pattern: /\/(?:cart|checkout|payment|order)(?:\/|$)|[?&](?:order_id|transaction_id)=/i,
scope: 'full',
description: '支付订单页面'
},
// 登出页面 - 仅匹配路径部分
logout: {
pattern: /\/(?:logout|signout)(?:\/|$)/i,
scope: 'pathname',
description: '登出页面'
},
// 打印页面 - 需要考虑查询参数
print: {
pattern: /\/print\/|[?&](?:print|format)=pdf/i,
scope: 'full',
description: '打印页面'
},
// 搜索结果页面 - 需要更精确的匹配
search: {
pattern: /\/search\/|\/(results|findings)(?:\/|$)|[?&](?:q|query|search|keyword)=/i,
scope: 'full',
description: '搜索结果页面'
},
// 回调和重定向页面 - 需要更精确的匹配
redirect: {
pattern: /\/(?:callback|redirect)(?:\/|$)|[?&](?:callback|redirect_uri|return_url)=/i,
scope: 'full',
description: '回调重定向页面'
}
};
// 2. 检查每个规则
for (const [key, rule] of Object.entries(patterns)) {
let testString;
switch (rule.scope) {
case 'pathname':
// 仅检查路径部分
testString = urlObj.pathname;
break;
case 'full':
// 检查完整URL(包括查询参数)
testString = url;
break;
default:
continue;
}
if (rule.pattern.test(testString)) {
// 记录详细的匹配信息
const match = testString.match(rule.pattern);
logger.debug('URL被过滤:', {
url: url,
reason: rule.description,
pattern: rule.pattern.toString(),
matchedPart: match[0],
matchLocation: rule.scope,
fullPath: urlObj.pathname,
hasQuery: urlObj.search.length > 0
});
// 3. 特殊情况处理
if (shouldAllowException(url, key, match)) {
logger.debug('URL虽然匹配过滤规则,但属于例外情况,允许保存');
continue;
}
return false;
}
}
return true;
} catch (error) {
logger.error('URL验证失败:', error);
return false;
}
}
// 处理特殊例外情况
function shouldAllowException(url, ruleKey, match) {
try {
const urlObj = new URL(url);
// 1. 允许特定域名的搜索结果页面
if (ruleKey === 'search') {
const allowedSearchDomains = [
'github.com',
'stackoverflow.com',
'developer.mozilla.org'
];
if (allowedSearchDomains.some(domain => urlObj.hostname.endsWith(domain))) {
return true;
}
}
// 2. 允许包含有价值内容的错误页面
if (ruleKey === 'errors') {
const valuableErrorPages = [
/\/guides\/errors\//i,
/\/docs\/errors\//i,
/\/error-reference\//i
];
if (valuableErrorPages.some(pattern => pattern.test(urlObj.pathname))) {
return true;
}
}
// 3. 允许特定的下载页面(如软件发布页)
if (ruleKey === 'fileTransfer') {
const allowedDownloadPatterns = [
/\/releases\/download\//i,
/\/downloads\/release\//i,
/\/software\/[^\/]+\/download\/?$/i
];
if (allowedDownloadPatterns.some(pattern => pattern.test(urlObj.pathname))) {
return true;
}
}
return false;
} catch (error) {
logger.error('处理URL例外情况时出错:', error);
return false;
}
}
async function checkUrlAccessibility(url) {
if (isNonMarkableUrl(url)) {
return {accessible: false, reason: '不支持的URL'};
}
return {accessible: true, reason: '可访问'};
}
function smartTruncate(text, maxLength = 500) {
if (!text) return text;
if (text.length <= maxLength) return text;
// 检测文本类型的辅助函数
const detectTextType = (text) => {
// 统计前100个字符的语言特征
const sample = text.slice(0, 100);
// 统计不同类型字符的数量
const stats = {
latin: 0, // 拉丁字母 (英文等)
cjk: 0, // 中日韩文字
cyrillic: 0, // 西里尔字母 (俄文等)
arabic: 0, // 阿拉伯文
other: 0 // 其他字符
};
// 遍历样本文本的每个字符
for (const char of sample) {
const code = char.codePointAt(0);
if (/[\p{Script=Latin}]/u.test(char)) {
stats.latin++;
} else if (/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(char)) {
stats.cjk++;
} else if (/[\p{Script=Cyrillic}]/u.test(char)) {
stats.cyrillic++;
} else if (/[\p{Script=Arabic}]/u.test(char)) {
stats.arabic++;
} else if (!/[\s\p{P}]/u.test(char)) { // 排除空格和标点
stats.other++;
}
}
// 计算主要字符类型的占比
const total = Object.values(stats).reduce((a, b) => a + b, 0);
const threshold = 0.6; // 60%的阈值
// 返回主要语言类型
if (stats.latin / total > threshold) return 'latin';
if (stats.cjk / total > threshold) return 'cjk';
if (stats.cyrillic / total > threshold) return 'cyrillic';
if (stats.arabic / total > threshold) return 'arabic';
// 如果没有明显主导的语言类型,返回混合类型
return 'mixed';
};
const textType = detectTextType(text);
logger.debug('文本类型:', textType);
// 根据不同语言类型选择截取策略
switch (textType) {
case 'latin':
case 'cyrillic':
case 'arabic':
// 按单词数量截取
const maxWords = Math.round(maxLength * 0.5);
const words = text.split(/\s+/).filter(word => word.length > 0);
if (words.length <= maxWords) return text;
return words
.slice(0, maxWords)
.join(' ');
case 'cjk':
// 中日韩文本按字符截取,在标点处断句
const punctuation = /[,。!?;,!?;]/;
let truncated = text.slice(0, maxLength);
// 尝试在标点符号处截断
for (let i = truncated.length - 1; i >= maxLength - 50; i--) {
if (punctuation.test(truncated[i])) {
truncated = truncated.slice(0, i + 1);
break;
}
}
return truncated;
case 'mixed':
default:
// 混合文本采用通用策略
// 先尝试在空格处截断
let mixedTruncated = text.slice(0, maxLength);
for (let i = mixedTruncated.length - 1; i >= maxLength - 30; i--) {
if (/\s/.test(mixedTruncated[i])) {
mixedTruncated = mixedTruncated.slice(0, i);
break;
}
}
return mixedTruncated;
}
}
// 添加辅助函数计算字符串的视觉长度
function getStringVisualLength(str) {
let length = 0;
for (let i = 0; i < str.length; i++) {
// 中日韩文字计为2个单位长度
if (/[\u4e00-\u9fa5\u3040-\u30ff\u3400-\u4dbf]/.test(str[i])) {
length += 2;
}
// 其他字符计为1个单位长度
else {
length += 1;
}
}
return length;
}
// 获取备选标签的辅助函数
function getFallbackTags(title, metadata) {
const maxTags = 5;
const tags = new Set();
// 1. 首先尝试使用 metadata 中的关键词
if (metadata?.keywords) {
const metaKeywords = metadata.keywords
.split(/[,,;;]/) // 分割关键词
.map(tag => tag.trim())
.filter(tag => {
return tag.length >= 1 &&
tag.length <= 20;
});
metaKeywords.forEach(tag => tags.add(tag));
}
const stopWords = new Set([
// 中文停用词
'的', '了', '和', '与', '或', '在', '是', '到', '等', '把',
// 英文停用词
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for',
'from', 'has', 'he', 'in', 'is', 'it', 'its', 'of', 'on',
'that', 'the', 'to', 'was', 'were', 'will', 'with', 'the',
// 常见连接词和介词
'about', 'after', 'before', 'but', 'how', 'into', 'over',
'under', 'what', 'when', 'where', 'which', 'who', 'why',
// 常见动词
'can', 'could', 'did', 'do', 'does', 'had', 'have', 'may',
'might', 'must', 'should', 'would',
// 其他常见词