-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.js
More file actions
1028 lines (904 loc) · 27.1 KB
/
Copy pathutils.js
File metadata and controls
1028 lines (904 loc) · 27.1 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
// 工具函数库 - 包含分类、去重、备份等核心功能
/**
* 从URL提取域名
*/
function extractDomain(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname.replace(/^www\./, '');
} catch (e) {
return '';
}
}
/**
* 规范化URL:去掉查询参数和哈希,只保留 origin + pathname
*/
function normalizeUrl(url) {
try {
const urlObj = new URL(url);
return urlObj.origin + urlObj.pathname;
} catch (e) {
return url;
}
}
/**
* 获取书签的完整路径(文件夹层级)
*/
async function getBookmarkPath(bookmarkId) {
try {
const path = [];
let currentNode = await chrome.bookmarks.get(bookmarkId);
if (!currentNode || !currentNode[0]) {
return typeof _t === 'function' ? _t('unknownPath') : 'Unknown Location';
}
let parentId = currentNode[0].parentId;
// 向上遍历直到根节点
while (parentId && parentId !== '0') {
const parent = await chrome.bookmarks.get(parentId);
if (parent && parent[0]) {
path.unshift(parent[0].title);
parentId = parent[0].parentId;
} else {
break;
}
}
return path.length > 0 ? path.join(' > ') : (typeof _t === 'function' ? _t('bookmarksBar') : 'Bookmarks Bar');
} catch (error) {
console.error('获取书签路径失败:', error);
return typeof _t === 'function' ? _t('unknownPath') : 'Unknown Location';
}
}
/**
* 批量获取书签路径(优化性能)
*/
async function getBookmarksPaths(bookmarkIds) {
const paths = {};
// 先获取所有需要的节点信息,减少API调用次数
const nodes = await Promise.all(
bookmarkIds.map(id => chrome.bookmarks.get(id).catch(() => null))
);
// 收集所有需要查询的父节点ID
const parentIds = new Set();
const nodeMap = {};
for (let i = 0; i < nodes.length; i++) {
if (nodes[i] && nodes[i][0]) {
const node = nodes[i][0];
nodeMap[node.id] = node;
if (node.parentId && node.parentId !== '0') {
parentIds.add(node.parentId);
}
}
}
// 批量获取父节点信息
const parentIdArray = Array.from(parentIds);
if (parentIdArray.length > 0) {
try {
const parents = await chrome.bookmarks.get(parentIdArray);
parents.forEach(p => {
nodeMap[p.id] = p;
if (p.parentId && p.parentId !== '0') {
parentIds.add(p.parentId);
}
});
// 继续向上查找更高层级的父节点
let currentParentIds = Array.from(parentIds).filter(id => !nodeMap[id]);
let depth = 0;
const maxDepth = 10; // 防止无限循环
while (currentParentIds.length > 0 && depth < maxDepth) {
const grandparents = await chrome.bookmarks.get(currentParentIds);
grandparents.forEach(gp => {
nodeMap[gp.id] = gp;
if (gp.parentId && gp.parentId !== '0' && !nodeMap[gp.parentId]) {
parentIds.add(gp.parentId);
}
});
currentParentIds = Array.from(parentIds).filter(id => !nodeMap[id]);
depth++;
}
} catch (e) {
console.error('批量获取父节点失败:', e);
}
}
// 为每个书签构建路径
for (const id of bookmarkIds) {
const path = [];
let currentNode = nodeMap[id];
if (!currentNode) {
paths[id] = { path: (typeof _t === 'function' ? _t('unknownPath') : 'Unknown Location'), inBookmarksBar: false };
continue;
}
let parentId = currentNode.parentId;
let inBookmarksBar = false;
while (parentId && parentId !== '0' && nodeMap[parentId]) {
if (parentId === '1') {
inBookmarksBar = true;
}
path.unshift(nodeMap[parentId].title);
parentId = nodeMap[parentId].parentId;
}
paths[id] = {
path: path.length > 0 ? path.join(' > ') : (typeof _t === 'function' ? _t('bookmarksBar') : 'Bookmarks Bar'),
inBookmarksBar
};
}
return paths;
}
/**
* 计算字符串相似度 (使用简单的字符匹配算法)
*/
function calculateSimilarity(str1, str2) {
if (!str1 || !str2) return 0;
const s1 = str1.toLowerCase();
const s2 = str2.toLowerCase();
if (s1 === s2) return 1;
// 使用最长公共子序列算法简化版
const longer = s1.length > s2.length ? s1 : s2;
const shorter = s1.length > s2.length ? s2 : s1;
if (longer.length === 0) return 1.0;
const costs = [];
for (let i = 0; i <= shorter.length; i++) {
let lastValue = i;
for (let j = 0; j <= longer.length; j++) {
if (i === 0) {
costs[j] = j;
} else if (j > 0) {
let newValue = costs[j - 1];
if (shorter[i - 1] !== longer[j - 1]) {
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
}
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
if (i > 0) costs[longer.length] = lastValue;
}
return (longer.length - costs[longer.length]) / longer.length;
}
/**
* 分析单个书签,返回推荐的分类
*/
async function analyzeBookmark(bookmark, categories) {
const title = bookmark.title || '';
const url = bookmark.url || '';
const domain = extractDomain(url);
let bestMatch = null;
let highestScore = 0;
for (const category of categories) {
const score = calculateCategoryScore(title, url, domain, category);
if (score > highestScore) {
highestScore = score;
bestMatch = category;
}
}
return {
bookmark: bookmark,
category: bestMatch,
score: highestScore,
confidence: getConfidenceLevel(highestScore)
};
}
/**
* 计算书签与分类的匹配分数
*/
function calculateCategoryScore(title, url, domain, category) {
let score = 0;
const titleLower = title.toLowerCase();
const urlLower = url.toLowerCase();
// 关键词匹配
if (category.keywords) {
for (const keyword of category.keywords) {
const keywordLower = keyword.toLowerCase();
if (titleLower.includes(keywordLower)) {
score += 2; // 标题匹配权重更高
}
if (urlLower.includes(keywordLower)) {
score += 1;
}
}
}
// 域名匹配
if (category.domains && domain) {
for (const catDomain of category.domains) {
if (domain === catDomain || domain.endsWith('.' + catDomain)) {
score += 3; // 域名匹配权重最高
break;
}
}
}
return score;
}
/**
* 获取置信度等级
*/
function getConfidenceLevel(score) {
if (score >= 5) return 'high';
if (score >= 3) return 'medium';
if (score >= 1) return 'low';
return 'none';
}
/**
* 遍历所有书签
*/
async function getAllBookmarks() {
const tree = await chrome.bookmarks.getTree();
const bookmarks = [];
function traverse(nodes) {
for (const node of nodes) {
if (node.url) {
bookmarks.push(node);
}
if (node.children) {
traverse(node.children);
}
}
}
traverse(tree);
return bookmarks;
}
/**
* 检测重复书签
*/
async function detectDuplicates(similarityThreshold = 0.8) {
const bookmarks = await getAllBookmarks();
const duplicates = [];
const processed = new Set();
// 按域名分组
const domainGroups = {};
for (const bookmark of bookmarks) {
const domain = extractDomain(bookmark.url);
if (!domainGroups[domain]) {
domainGroups[domain] = [];
}
domainGroups[domain].push(bookmark);
}
// 阶段1: 检测完全重复(URL字符串完全相同)
const urlMap = {};
for (const bookmark of bookmarks) {
if (!urlMap[bookmark.url]) {
urlMap[bookmark.url] = [];
}
urlMap[bookmark.url].push(bookmark);
}
for (const url in urlMap) {
if (urlMap[url].length > 1) {
duplicates.push({
type: 'exact',
items: urlMap[url]
});
urlMap[url].forEach(b => processed.add(b.id));
}
}
// 阶段2: 检测规范化重复(同路径不同查询参数)
const normalizedMap = {};
for (const bookmark of bookmarks) {
if (processed.has(bookmark.id)) continue;
const norm = normalizeUrl(bookmark.url);
if (!normalizedMap[norm]) {
normalizedMap[norm] = [];
}
normalizedMap[norm].push(bookmark);
}
for (const norm in normalizedMap) {
const group = normalizedMap[norm];
if (group.length > 1) {
// 过滤掉已经在完全重复中处理过的
const unprocessed = group.filter(b => !processed.has(b.id));
if (unprocessed.length > 1) {
duplicates.push({
type: 'normalized',
items: unprocessed,
similarity: 1.0
});
unprocessed.forEach(b => processed.add(b.id));
}
}
}
// 阶段3: 检测相似重复(同域名、标题相似且URL路径也相似)
for (const domain in domainGroups) {
const group = domainGroups[domain];
if (group.length < 2) continue;
for (let i = 0; i < group.length; i++) {
if (processed.has(group[i].id)) continue;
const similarGroup = [group[i]];
for (let j = i + 1; j < group.length; j++) {
if (processed.has(group[j].id)) continue;
// 同时计算标题相似度和URL相似度(使用规范化后的URL)
const titleSim = calculateSimilarity(group[i].title, group[j].title);
const urlSim = calculateSimilarity(
normalizeUrl(group[i].url),
normalizeUrl(group[j].url)
);
// 加权平均:标题占60%,URL路径占40%
const similarity = titleSim * 0.6 + urlSim * 0.4;
if (similarity >= similarityThreshold) {
similarGroup.push(group[j]);
processed.add(group[j].id);
}
}
if (similarGroup.length > 1) {
duplicates.push({
type: 'similar',
items: similarGroup,
similarity: calculateGroupSimilarity(similarGroup)
});
}
}
}
// 为所有重复项添加路径信息
if (duplicates.length > 0) {
// 收集所有需要查询路径的书签ID
const allBookmarkIds = [];
duplicates.forEach(group => {
group.items.forEach(item => {
allBookmarkIds.push(item.id);
});
});
// 批量获取路径
const pathsMap = await getBookmarksPaths(allBookmarkIds);
// 将路径信息添加到每个书签
duplicates.forEach(group => {
group.items.forEach(item => {
const info = pathsMap[item.id] || { path: (typeof _t === 'function' ? _t('unknownPath') : 'Unknown Location'), inBookmarksBar: false };
item.path = info.path;
item.inBookmarksBar = info.inBookmarksBar;
});
});
}
return duplicates;
}
/**
* 备份书签
*/
async function backupBookmarks() {
try {
const tree = await chrome.bookmarks.getTree();
const backup = {
timestamp: Date.now(),
date: new Date().toLocaleString('zh-CN'),
data: tree,
count: countBookmarks(tree)
};
// 获取现有备份列表
const result = await chrome.storage.local.get(['bookmarksBackups']);
const backups = result.bookmarksBackups || [];
// 添加新备份(保留最近10个)
backups.unshift(backup);
if (backups.length > 10) {
backups.pop();
}
await chrome.storage.local.set({ bookmarksBackups: backups });
// 更新最后备份时间
const settingsResult = await chrome.storage.local.get('settings');
const settings = settingsResult.settings || {};
settings.lastBackup = Date.now();
await chrome.storage.local.set({ settings });
return backup;
} catch (error) {
console.error('备份失败:', error);
throw error;
}
}
/**
* 恢复书签
*/
async function restoreBookmarks(backupData) {
try {
// 警告: 这将删除所有现有书签
await clearAllBookmarks();
// 递归恢复书签树
await restoreTree(backupData, '0'); // '0' 是根文件夹ID
return true;
} catch (error) {
console.error('恢复失败:', error);
throw error;
}
}
/**
* 清空所有书签
*/
async function clearAllBookmarks() {
const tree = await chrome.bookmarks.getTree();
async function removeChildren(node) {
if (node.children) {
for (const child of node.children) {
if (child.children && child.children.length > 0) {
await chrome.bookmarks.removeTree(child.id);
} else {
await chrome.bookmarks.remove(child.id);
}
}
}
}
// 删除根节点下的所有内容
for (const root of tree) {
await removeChildren(root);
}
}
/**
* 递归恢复书签树
*/
async function restoreTree(nodes, parentId) {
for (const node of nodes) {
let newNode;
if (node.url) {
// 这是书签
newNode = await chrome.bookmarks.create({
parentId: parentId,
title: node.title,
url: node.url
});
} else {
// 这是文件夹
newNode = await chrome.bookmarks.create({
parentId: parentId,
title: node.title
});
}
// 递归处理子节点
if (node.children && node.children.length > 0) {
await restoreTree(node.children, newNode.id);
}
}
}
/**
* 统计书签数量
*/
function countBookmarks(nodes) {
let count = 0;
for (const node of nodes) {
if (node.url) {
count++;
}
if (node.children) {
count += countBookmarks(node.children);
}
}
return count;
}
/**
* 创建分类文件夹
*/
async function createCategoryFolder(categoryName) {
// 检查是否已存在
const tree = await chrome.bookmarks.getTree();
const existing = await findFolderByName(tree, categoryName);
if (existing) {
return existing;
}
// 创建新文件夹
const folder = await chrome.bookmarks.create({
parentId: '0', // 根目录
title: categoryName
});
return folder;
}
/**
* 查找文件夹
*/
async function findFolderByName(nodes, name) {
for (const node of nodes) {
if (!node.url && node.title === name) {
return node;
}
if (node.children) {
const found = await findFolderByName(node.children, name);
if (found) return found;
}
}
return null;
}
/**
* 移动书签到文件夹
*/
async function moveBookmarkToFolder(bookmarkId, folderId) {
await chrome.bookmarks.move(bookmarkId, {
parentId: folderId
});
}
/**
* 批量移动书签
*/
async function batchMoveBookmarks(bookmarkIds, folderId) {
const results = [];
for (const id of bookmarkIds) {
try {
await moveBookmarkToFolder(id, folderId);
results.push({ id, success: true });
} catch (error) {
results.push({ id, success: false, error: error.message });
}
}
return results;
}
/**
* 计算相似组内所有项的最小相似度
*/
function calculateGroupSimilarity(items) {
if (items.length < 2) return 1;
let minSimilarity = 1;
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
const sim = calculateSimilarity(items[i].title, items[j].title);
if (sim < minSimilarity) {
minSimilarity = sim;
}
}
}
return minSimilarity;
}
/**
* HTML转义,防止XSS攻击
*/
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* 检测单个链接是否失效
*/
async function checkSingleLink(bookmark, timeoutMs = 10000) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
async function tryFetch(method) {
return fetch(bookmark.url, {
method,
signal: controller.signal,
redirect: 'follow',
// 不发送 cookie,避免不必要的身份验证问题
credentials: 'omit'
});
}
try {
let response;
try {
response = await tryFetch('HEAD');
} catch (headErr) {
// HEAD 失败,尝试 GET
response = await tryFetch('GET');
}
clearTimeout(timeoutId);
if (response.status === 404 || response.status === 410) {
return {
bookmark,
status: 'broken',
statusCode: response.status,
error: `HTTP ${response.status}`,
checkedAt: new Date().toLocaleString()
};
}
if (response.status >= 500) {
return {
bookmark,
status: 'error',
statusCode: response.status,
error: `Server Error ${response.status}`,
checkedAt: new Date().toLocaleString()
};
}
// 2xx, 3xx, 401, 403 等都认为是正常的
return null;
} catch (error) {
clearTimeout(timeoutId);
let status = 'error';
let errorMsg = error.message || String(error);
if (error.name === 'AbortError') {
status = 'timeout';
errorMsg = 'Connection timeout';
} else if (errorMsg.includes('Failed to fetch') || errorMsg.includes('NetworkError')) {
status = 'broken';
errorMsg = 'Network error / DNS failed / Connection refused';
}
return {
bookmark,
status,
statusCode: null,
error: errorMsg,
checkedAt: new Date().toLocaleString()
};
}
}
/**
* 批量检测失效链接(带并发控制)
* @param {Array} bookmarks - 书签列表
* @param {Function} onProgress - 进度回调 (current, total)
* @param {number} concurrency - 并发数
*/
async function checkBrokenLinks(bookmarks, onProgress, concurrency = 3) {
// 过滤掉非 http/https 的 URL
const validBookmarks = bookmarks.filter(b => {
try {
const url = new URL(b.url);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
});
const results = [];
const total = validBookmarks.length;
let index = 0;
async function worker() {
while (index < total) {
const currentIndex = index++;
const bookmark = validBookmarks[currentIndex];
const result = await checkSingleLink(bookmark);
if (result) {
results.push(result);
}
if (onProgress) {
onProgress(currentIndex + 1, total);
}
// 小延迟,避免对同一域名发送过多请求
await new Promise(r => setTimeout(r, 150));
}
}
const workers = [];
/**
* 解析 Netscape Bookmark Format HTML
* 支持 Chrome/Firefox/Edge 等浏览器导出的标准书签格式
*/
function parseNetscapeBookmarkFormat(htmlContent) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlContent, 'text/html');
// 验证基本结构
const doctype = doc.doctype;
const titleEl = doc.querySelector('title');
const hasNetscapeDoctype = doctype && doctype.name.toLowerCase().includes('netscape');
const hasBookmarks = doc.querySelector('dl') !== null;
if (!hasNetscapeDoctype && !hasBookmarks) {
throw new Error('Invalid bookmark file format');
}
function parseDL(dlElement, parentPath) {
const items = [];
const children = Array.from(dlElement.children);
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.tagName !== 'DT') continue;
const h3 = child.querySelector(':scope > H3');
const a = child.querySelector(':scope > A');
const nestedDL = child.querySelector(':scope > DL');
if (h3) {
// 文件夹
const folder = {
type: 'folder',
title: h3.textContent.trim(),
addDate: h3.getAttribute('ADD_DATE') || h3.getAttribute('add_date') || '',
lastModified: h3.getAttribute('LAST_MODIFIED') || h3.getAttribute('last_modified') || '',
children: []
};
if (nestedDL) {
folder.children = parseDL(nestedDL, [...parentPath, folder.title]);
}
items.push(folder);
} else if (a) {
// 书签
const bookmark = {
type: 'bookmark',
title: a.textContent.trim(),
url: a.getAttribute('HREF') || a.getAttribute('href') || '',
addDate: a.getAttribute('ADD_DATE') || a.getAttribute('add_date') || '',
icon: a.getAttribute('ICON') || a.getAttribute('icon') || ''
};
items.push(bookmark);
}
}
return items;
}
const rootDL = doc.querySelector('DL');
if (!rootDL) {
throw new Error('No bookmark data found in file');
}
return {
title: titleEl ? titleEl.textContent.trim() : 'Bookmarks',
items: parseDL(rootDL, [])
};
}
/**
* 验证书签数据结构完整性
*/
function validateBookmarkStructure(data) {
if (!data || typeof data !== 'object') {
return { valid: false, error: 'Invalid data format' };
}
// 检查是否为数组(直接的书签列表)
if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
const item = data[i];
if (item.type === 'bookmark') {
if (!item.url || typeof item.url !== 'string') {
return { valid: false, error: `Item ${i}: missing or invalid URL` };
}
try {
new URL(item.url);
} catch {
return { valid: false, error: `Item ${i}: invalid URL format: ${item.url}` };
}
}
}
return { valid: true, count: countBookmarkItems(data) };
}
// 检查标准格式 { title, items }
if (!Array.isArray(data.items)) {
return { valid: false, error: 'Missing items array' };
}
function validateItems(items, depth) {
if (depth > 20) {
return { valid: false, error: 'Nesting too deep (max 20 levels)' };
}
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (!item.type || !['bookmark', 'folder'].includes(item.type)) {
return { valid: false, error: `Item ${i}: unknown type "${item.type}"` };
}
if (item.type === 'bookmark') {
if (!item.url || typeof item.url !== 'string') {
return { valid: false, error: `Item ${i}: missing or invalid URL` };
}
try {
new URL(item.url);
} catch {
return { valid: false, error: `Item ${i}: invalid URL format` };
}
}
if (item.type === 'folder') {
if (!Array.isArray(item.children)) {
return { valid: false, error: `Folder "${item.title}": missing children array` };
}
const result = validateItems(item.children, depth + 1);
if (!result.valid) return result;
}
}
return { valid: true };
}
const result = validateItems(data.items, 0);
if (!result.valid) return result;
return { valid: true, count: countBookmarkItems(data.items) };
}
/**
* 统计书签项目数量
*/
function countBookmarkItems(items) {
let count = 0;
for (const item of items) {
if (item.type === 'bookmark') count++;
if (item.type === 'folder' && item.children) {
count += countBookmarkItems(item.children);
}
}
return count;
}
/**
* 从 HTML 格式导入书签
* @param {string} htmlContent - HTML 文件内容
* @param {string} mode - 'merge' 合并到现有书签, 'replace' 覆盖现有书签
*/
async function importBookmarksFromHTML(htmlContent, mode = 'merge') {
const parsed = parseNetscapeBookmarkFormat(htmlContent);
const validation = validateBookmarkStructure(parsed);
if (!validation.valid) {
throw new Error(validation.error);
}
if (mode === 'replace') {
await clearAllBookmarks();
}
// 获取根节点,导入到书签栏或其他合适位置
const tree = await chrome.bookmarks.getTree();
// 默认导入到"其他书签" (parentId '2')
const targetParentId = '2';
async function createItems(items, parentId) {
for (const item of items) {
if (item.type === 'bookmark') {
try {
await chrome.bookmarks.create({
parentId: parentId,
title: item.title || item.url,
url: item.url
});
} catch (e) {
console.warn('Failed to create bookmark:', item.title, e.message);
}
} else if (item.type === 'folder') {
try {
const folder = await chrome.bookmarks.create({
parentId: parentId,
title: item.title || 'Untitled Folder'
});
if (item.children && item.children.length > 0) {
await createItems(item.children, folder.id);
}
} catch (e) {
console.warn('Failed to create folder:', item.title, e.message);
}
}
}
}
await createItems(parsed.items, targetParentId);
return { success: true, count: validation.count, title: parsed.title };
}
/**
* 导出书签为 Netscape Bookmark Format HTML
*/
async function exportBookmarksToHTML() {
const tree = await chrome.bookmarks.getTree();
function buildHTML(nodes, depth) {
const indent = ' '.repeat(depth);
let html = '';
for (const node of nodes) {
if (node.url) {
// 书签
const addDate = node.dateAdded ? Math.floor(node.dateAdded / 1000) : '';
html += `${indent}<DT><A HREF="${escapeHtml(node.url)}" ADD_DATE="${addDate}">${escapeHtml(node.title || 'Untitled')}</A>\n`;
} else if (node.children) {
// 文件夹(跳过根节点)
if (node.id === '0') {
html += buildHTML(node.children, depth);
} else {
const addDate = node.dateAdded ? Math.floor(node.dateAdded / 1000) : '';
const modDate = node.dateGroupModified ? Math.floor(node.dateGroupModified / 1000) : '';
html += `${indent}<DT><H3 ADD_DATE="${addDate}" LAST_MODIFIED="${modDate}">${escapeHtml(node.title || 'Untitled')}</H3>\n`;
html += `${indent}<DL><p>\n`;
html += buildHTML(node.children, depth + 1);
html += `${indent}</DL><p>\n`;
}
}
}
return html;
}
const bookmarksHtml = buildHTML(tree, 1);
return `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
It will be read and overwritten.
DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
${bookmarksHtml}</DL><p>
`;
}
/**
* 导出书签为 JSON 格式
*/
async function exportBookmarksToJSON() {
const tree = await chrome.bookmarks.getTree();
return JSON.stringify(tree, null, 2);
}
/**
* 生成书签导入预览结构
*/
function generateImportPreview(items, maxDepth = 3, currentDepth = 0) {
if (currentDepth >= maxDepth) {
const remaining = countBookmarkItems(items);
return remaining > 0 ? `<div class="preview-more">... ${remaining} more items</div>` : '';
}
let html = '<ul class="preview-list">';
let shown = 0;
const maxItems = currentDepth === 0 ? 50 : 20;
for (const item of items) {
if (shown >= maxItems) {