-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathai-comment-summarizer.user.js
More file actions
1700 lines (1568 loc) · 76.6 KB
/
Copy pathai-comment-summarizer.user.js
File metadata and controls
1700 lines (1568 loc) · 76.6 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
// ==UserScript==
// @name AI 评论总结助手
// @namespace http://tampermonkey.net/
// @version 1.8.1
// @description 自动抓取当前页面的评论并使用 AI 进行总结(Markdown + 主题摘要 + AI 独立洞察)
// @author Kerinlin
// @match *://*.youtube.com/*
// @match *://*.reddit.com/*
// @match *://*.bilibili.com/*
// @match *://*.zhihu.com/*
// @match *://*.xiaohongshu.com/*
// @match *://*.twitter.com/*
// @match *://*.x.com/*
// @match *://news.ycombinator.com/*
// @match https://linux.do/*
// @match https://*.linux.do/*
// @match https://tieba.baidu.com/*
// @match https://*.douyin.com/*
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @require https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js
// @connect *
// @connect localhost
// @connect 127.0.0.1
// @run-at document-idle
// ==/UserScript==
(function () {
'use strict';
// === 基础工具:trustedTypes 策略 + 安全 HTML 注入 ===
// CSP 严格站点(如 GitHub、Hacker News)要求 trustedTypes 才能写 innerHTML;
// 创建一次性 policy 后所有 innerHTML 写入都走 safeHTML,无 policy 则直接赋值。
const _ttPolicy = (typeof trustedTypes !== 'undefined' && trustedTypes.createPolicy)
? trustedTypes.createPolicy('ai-comment-summarizer', { createHTML: s => s })
: null;
function safeHTML(el, html) {
if (_ttPolicy) el.innerHTML = _ttPolicy.createHTML(html);
else el.innerHTML = html;
}
// === 配置与 Prompt 常量 ===
const CONFIG_KEY = 'ai_comment_summarizer_config';
const DEFAULT_PROMPT = `你是一位资深的社区舆情分析师。请阅读我提供的「帖子标题 + 评论列表」,输出一份结构化的中文分析报告。
【输出格式(严格使用 Markdown,不要输出任何多余的解释或开场白)】
## 讨论主题
用 1-2 句话概括本次讨论的核心议题,需结合标题与评论整体判断,避免复述标题。
## 核心观点
列出评论中反复出现、最具代表性的观点(3-6 条),格式:
- 一句话观点:补充说明该观点的依据或背景(可标注大致占比 / 热度,如「多数人认为」「少数声音」)。
## 共识
- 评论者普遍认同的 2-4 个点,尽量具体,不要空泛。
## 分歧与争议
列出 2-4 个存在对立的话题,每个话题单独成段,严格按以下格式输出(正方、反方各占一行,不要合并):
- 话题标题:简述争议点。
- 正方:正方核心立场,1 句话。
- 反方:反方核心立场,1 句话。
## 情绪与风向
用 2-4 个关键词概括整体情绪(如:期待、吐槽、质疑、玩梗……),再用 1-2 句话说明原因;若情绪有明显变化或分裂,也请点明。
## 高赞金句
挑选 1-3 条最有代表性、信息量或话题度的原文,用引用块展示(保留原文语言),并在括号内标注点赞数:
> 原文内容(👍 点赞数)
【硬性要求】
1. 全程使用简体中文输出(金句保留原文)。
2. 严格使用 Markdown 语法(##、-、**、>)。
3. 只输出中立归纳,不要给出个人立场或判断(独立判断由系统另行生成)。
4. 不要客气、不要奉承、不要"以上只是个人浅见"之类的自我消解。
5. 证据不足的部分可如实说明「样本有限」。`;
const INSIGHT_PROMPT = `你是对抗性测试员,不是反方辩手。系统已完成对某帖子评论的中立归纳,现在请对它执行对抗性测试:尝试挑翻高赞、挖出群体盲区,再基于测试结果和全部证据下判断。判断方向不预设——证据支持主流就认同,不支持就反对,但不许为了对抗而对抗。
【输出格式(严格 Markdown,不要任何开场白,不要输出顶层 # 或 ## 标题,直接从 ### 开始)】
### 质疑高赞
挑出归纳中最被高赞但不成立(或有重大遗漏)的一条,1-2 句话直接驳它。如果高赞都站得住,如实说"未找到明显漏洞"。
### 指出盲点
评论中集体遗漏的一个变量(事实、视角、风险),1-2 句话说清。
### AI 评论
基于以上测试和全部证据,1-2 句话给出你的真实判断。可以是认同主流、反对主流、或综合判断,但必须押注一方,不许骑墙、不许"从多个角度看"、不许"仁者见仁"。
### 信心程度
用「高 / 中 / 低」三档之一标注你对上述判断的自信度,格式:信心程度:高
【硬性要求】
1. 全程使用简体中文。
2. 仅基于归纳内容推理,不引入归纳之外的未知事实。
3. 不要客气、不要自我消解、不要"以上仅供参考"。
4. 判断方向不预设——证据支持主流就认同,证据不支持就反对,不允许为了对抗而对抗。`;
// 默认配置:首次安装时的回退值,apiKey/apiEndpoint 为本地代理默认值。
const DEFAULT_CONFIG = {
apiKey: 'sk-sOisCHwyDG3GIhUvL',
apiEndpoint: 'http://localhost:8317',
model: 'MiniMax-M3',
maxComments: 500,
minLikes: 0,
customPrompt: DEFAULT_PROMPT
};
// HTML 转义:md 渲染前先转义文本,避免 XSS / 显示乱码
function escapeHtml(s) {
return s.replace(/[&<>"']/g, c => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": '''
}[c]));
}
// 极简 Markdown → HTML 渲染器(无依赖)
// 流程:抽取 code block/inline 占位 → escape → 块级元素(标题/引用/列表/分隔线)→ 行内(粗斜体/链接)→ 段落 → 还原 code 占位
// 用 \x00.. 占位符避免内联代码被 markdown 语法误伤
function md(input) {
if (!input) return '';
const codeBlocks = [];
input = input.replace(/```([\s\S]*?)```/g, (_, code) => {
codeBlocks.push(code);
return '\x00CB' + (codeBlocks.length - 1) + '\x00';
});
const inlineCodes = [];
input = input.replace(/`([^\n]+)`/g, (_, code) => {
inlineCodes.push(code);
return '\x00IC' + (inlineCodes.length - 1) + '\x00';
});
let html = escapeHtml(input);
// 标题:从 h6 → h1 依次匹配,避免 # 前缀被更高层级规则吞掉
html = html.replace(/^######\s?(.*)$/gm, '<h6>$1</h6>')
.replace(/^#####\s?(.*)$/gm, '<h5>$1</h5>')
.replace(/^####\s?(.*)$/gm, '<h4>$1</h4>')
.replace(/^###\s?(.*)$/gm, '<h3>$1</h3>')
.replace(/^##\s?(.*)$/gm, '<h2>$1</h2>')
.replace(/^#\s?(.*)$/gm, '<h1>$1</h1>');
html = html.replace(/^\s*---\s*$/gm, '<hr>');
// 引用块:连续 > 开头行合并为 blockquote,内部用 <br> 换行
html = html.replace(/(^|\n)((?:> .*(?:\n|$))+)/g, (m, pre, block) => {
const inner = block.trim().split('\n').map(l => l.replace(/^>\s?/, '')).join('<br>');
return pre + '<blockquote>' + inner + '</blockquote>';
});
// 无序列表:连续 - 或 * 开头行合并为 ul/li
html = html.replace(/(^|\n)((?:[-*]\s+.*(?:\n|$))+)/g, (m, pre, block) => {
const items = block.trim().split('\n').map(l => '<li>' + l.replace(/^[-*]\s+/, '') + '</li>').join('');
return pre + '<ul>' + items + '</ul>';
});
// 行内:粗体 → 斜体(避免吞粗体的 **)→ 删除线
html = html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>')
.replace(/~~([^~\n]+)~~/g, '<del>$1</del>');
// 链接:仅 http(s),强制 target=_blank + rel=noopener 防止反向 tabnabbing
html = html.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,
'<a href="$2" target="_blank" rel="noopener">$1</a>');
// 段落:以空行分隔的文本块包 <p>,已识别的块级标签直接保留
html = html.split(/\n{2,}/).map(p => {
p = p.trim();
if (!p) return '';
if (/^<(h\d|ul|ol|blockquote|hr|pre)/.test(p)) return p;
return '<p>' + p.replace(/\n/g, '<br>') + '</p>';
}).join('\n');
// 最后还原 code 占位为 <pre><code> / <code>,对代码内容再做一次 escape
html = html.replace(/\x00CB(\d+)\x00/g, (_, i) =>
'<pre><code>' + escapeHtml(codeBlocks[+i]) + '</code></pre>');
html = html.replace(/\x00IC(\d+)\x00/g, (_, i) =>
'<code>' + escapeHtml(inlineCodes[+i]) + '</code>');
return html;
}
// 配置持久化:合并默认值 + 用户存储,避免老版本缺字段崩溃
function loadConfig() {
try { return Object.assign({}, DEFAULT_CONFIG, JSON.parse(GM_getValue(CONFIG_KEY, '{}'))); }
catch { return Object.assign({}, DEFAULT_CONFIG); }
}
function saveConfig(cfg) { GM_setValue(CONFIG_KEY, JSON.stringify(cfg)); }
let config = loadConfig();
// === 全局样式注入 ===
// 配色系统:parchment 纸感(#faf5ea 底 / #f5efe0 区块 / #e0d5c0 描边)
// + ink-blue 主色(#1B365D)+ 红砖强调(#8b3a1f 用于 insight/警告)
// 分区:FAB 按钮 / panel 容器 / 头部+话题+正文 / 骨架屏+加载态 /
// 操作行按钮 / 对抗性审视 insight 块 / 正文 markdown 排版 /
// 设置面板 / 模型下拉 / 复制方式弹窗
GM_addStyle(`
#ai-fab{position:fixed;bottom:24px;right:24px;z-index:999999;width:52px;height:52px;border-radius:50%;background:#1B365D;color:#faf5ea;border:1px solid #14263f;cursor:pointer;box-shadow:0 2px 8px rgba(27,54,93,.22);font-size:22px;display:flex;align-items:center;justify-content:center;transition:transform .2s,box-shadow .2s;font-family:Georgia,"Songti SC","STSong",serif}
#ai-fab:hover{transform:scale(1.06);box-shadow:0 4px 14px rgba(27,54,93,.32)}
#ai-fab:disabled{opacity:.5;cursor:wait}
#ai-panel{position:fixed;bottom:86px;right:24px;z-index:999999;width:460px;max-width:calc(100vw - 40px);max-height:76vh;background:#faf5ea;color:#2a2520;border-radius:4px;box-shadow:0 10px 32px rgba(42,37,32,.18);display:none;flex-direction:column;overflow:hidden;font-family:Georgia,"Songti SC","STSong","Source Han Serif SC",serif;border:1px solid #e0d5c0;animation:ai-pop .18s ease-out}
@keyframes ai-pop{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}
#ai-panel.open{display:flex}
#ai-panel .ai-hd{padding:12px 16px;background:#f5efe0;border-bottom:1px solid #e0d5c0;display:flex;justify-content:space-between;align-items:center;font-weight:600;font-size:14px;min-height:44px;letter-spacing:.01em}
#ai-panel .ai-hd .ai-title{display:flex;align-items:center;gap:7px;line-height:1;color:#1B365D}
#ai-panel .ai-hd .ai-title em{font-style:normal;font-size:11px;background:#1B365D;color:#faf5ea;padding:2px 7px;border-radius:2px;line-height:1.4;display:inline-flex;align-items:center;font-family:Georgia,serif}
#ai-panel .ai-hd .ai-actions{display:flex;align-items:center;gap:5px}
#ai-panel .ai-hd button{background:transparent;border:1px solid transparent;color:#5a5248;cursor:pointer;font-size:13px;width:27px;height:27px;border-radius:3px;display:inline-flex;align-items:center;justify-content:center;transition:background .15s,border-color .15s;font-family:inherit}
#ai-panel .ai-hd button:hover{background:#faf5ea;border-color:#e0d5c0;color:#1B365D}
#ai-panel .ai-meta{padding:10px 16px;background:#faf5ea;border-bottom:1px solid #ecd9b8;font-size:12px;color:#8a7f70;display:flex;align-items:center;gap:8px;font-style:italic}
#ai-panel .ai-meta .ai-topic{flex:1;min-width:0;color:#3a342c;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-style:normal}
#ai-panel .ai-meta .ai-topic::before{content:"§ "}
#ai-panel .ai-body{padding:18px 22px;overflow-y:auto;line-height:1.75;font-size:14px;flex:1;min-height:150px;color:#3a342c;scrollbar-width:thin;scrollbar-color:#c9bea8 transparent}
#ai-panel .ai-body::-webkit-scrollbar{width:8px}
#ai-panel .ai-body::-webkit-scrollbar-thumb{background:#c9bea8;border-radius:4px}
#ai-panel .ai-body.status{display:flex;align-items:center;justify-content:center;color:#8a7f70;font-style:italic;text-align:center;padding:40px 24px}
#ai-panel .ai-skeleton{display:flex;flex-direction:column;gap:11px}
#ai-panel .ai-skeleton .ai-bar{height:11px;background:linear-gradient(90deg,#ece3d0 25%,#dfd4bc 50%,#ece3d0 75%);background-size:200% 100%;border-radius:2px;animation:sk-shine 1.4s infinite}
#ai-panel .ai-skeleton .ai-bar.w70{width:70%}
#ai-panel .ai-skeleton .ai-bar.w90{width:90%}
#ai-panel .ai-skeleton .ai-bar.w50{width:50%}
@keyframes sk-shine{0%{background-position:200% 0}100%{background-position:-200% 0}}
#ai-panel .ai-actions-row{padding:12px 16px;border-top:1px solid #e0d5c0;display:flex;gap:10px;background:#f5efe0}
#ai-panel .ai-actions-row button{flex:1;display:flex;align-items:center;justify-content:center;gap:5px;padding:9px 10px;border:1px solid #e0d5c0;border-radius:3px;cursor:pointer;font-size:13.5px;font-weight:500;line-height:1;transition:background .15s,transform .1s;font-family:inherit}
#ai-panel .ai-actions-row button:active{transform:scale(.97)}
#ai-panel .ai-actions-row button.ai-primary{background:#1B365D;color:#faf5ea;border-color:#14263f}
#ai-panel .ai-actions-row button.ai-primary:hover{background:#14263f}
#ai-panel .ai-actions-row button.ai-ghost{background:#faf5ea;color:#3a342c}
#ai-panel .ai-actions-row button.ai-ghost:hover{background:#f0e9d8}
#ai-panel .ai-actions-row button.ai-stopping{background:#8b3a1f;color:#faf5ea;border-color:#6b2c17;animation:ai-pulse 1.2s ease-in-out infinite}
#ai-panel .ai-actions-row button.ai-stopping:hover{background:#6b2c17}
@keyframes ai-pulse{0%,100%{opacity:1}50%{opacity:.72}}
.ai-insight{margin:18px -22px 0;padding:14px 22px 16px;background:#fbf2e8;border-top:1px dashed #d4a574;border-bottom:1px dashed #d4a574;position:relative}
.ai-insight::before{content:"";position:absolute;left:0;top:0;bottom:0;width:3px;background:#8b3a1f}
.ai-insight .ai-insight-tag{display:inline-flex;align-items:center;gap:5px;background:#8b3a1f;color:#faf5ea;padding:3px 9px;border-radius:2px;font-size:11px;font-weight:600;letter-spacing:.05em;margin-bottom:10px;font-family:Georgia,serif}
.ai-insight .ai-insight-notice{font-size:11.5px;color:#8b3a1f;font-style:italic;margin-bottom:12px;padding-bottom:10px;border-bottom:1px solid rgba(139,58,31,.18)}
.ai-insight h2{color:#8b3a1f !important;margin-top:14px}
.ai-insight h2:first-child{margin-top:0}
.ai-insight h2::before{background:#8b3a1f !important}
.ai-insight li::before{color:#8b3a1f !important}
.ai-insight blockquote{border-left-color:#8b3a1f !important;background:#f5e8d8 !important}
#ai-panel .ai-body h1,#ai-panel .ai-body h2,#ai-panel .ai-body h3{margin:16px 0 8px;font-weight:700;line-height:1.3;letter-spacing:.005em}
#ai-panel .ai-body h1{font-size:18px;color:#1B365D;border-bottom:1px solid #e0d5c0;padding-bottom:5px}
#ai-panel .ai-body h2{font-size:15.5px;color:#1B365D;display:flex;align-items:center;gap:7px;margin-top:18px}
#ai-panel .ai-body h2::before{content:"";display:inline-block;width:3px;height:14px;background:#1B365D;flex-shrink:0}
#ai-panel .ai-body h2:first-child{margin-top:0}
#ai-panel .ai-body h3{font-size:14px;color:#2c5278}
#ai-panel .ai-body p{margin:7px 0}
#ai-panel .ai-body ul{margin:8px 0;padding-left:22px}
#ai-panel .ai-body li{margin:6px 0;list-style:none;position:relative;padding-left:4px}
#ai-panel .ai-body li::before{content:"▸";color:#1B365D;position:absolute;left:-15px;top:0}
#ai-panel .ai-body strong{color:#8b3a1f;font-weight:700}
#ai-panel .ai-body em{color:#2c5278;font-style:italic}
#ai-panel .ai-body blockquote{margin:10px 0;padding:10px 14px;background:#f5efe0;border-left:3px solid #1B365D;border-radius:0 2px 2px 0;color:#5a5248;font-style:italic}
#ai-panel .ai-body hr{border:none;border-top:1px dashed #c9bea8;margin:16px 0}
#ai-panel .ai-body code{background:#f0e9d8;padding:2px 6px;border-radius:2px;font-family:ui-monospace,Menlo,monospace;font-size:12.5px;color:#8b3a1f;border:1px solid #e0d5c0}
#ai-panel .ai-body pre{background:#f5efe0;padding:12px;border-radius:3px;overflow-x:auto;border:1px solid #e0d5c0}
#ai-panel .ai-body pre code{background:none;border:none;color:#3a342c}
#ai-panel .ai-body a{color:#1B365D;text-decoration:none;border-bottom:1px solid rgba(27,54,93,.4)}
#ai-panel .ai-body a:hover{border-bottom-color:#1B365D}
#ai-panel .ai-body del{color:#a89e8a}
#ai-settings{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:1000000;width:520px;max-width:calc(100vw - 40px);max-height:82vh;overflow:auto;background:#faf5ea;color:#2a2520;border-radius:4px;box-shadow:0 14px 44px rgba(42,37,32,.24);padding:24px;display:none;font-family:Georgia,"Songti SC","STSong","Source Han Serif SC",serif;border:1px solid #e0d5c0}
#ai-settings.open{display:block}
#ai-settings h3{margin-top:0;color:#1B365D;border-bottom:1px solid #e0d5c0;padding-bottom:8px;font-size:16px}
#ai-settings label{display:block;margin:12px 0 5px;font-size:13px;color:#5a5248;font-style:italic}
#ai-settings input,#ai-settings textarea{width:100%;padding:9px 11px;background:#fffdf7;color:#2a2520;border:1px solid #e0d5c0;border-radius:3px;font-size:13px;box-sizing:border-box;font-family:inherit;transition:border-color .15s,box-shadow .15s}
#ai-settings input:focus,#ai-settings textarea:focus{outline:none;border-color:#1B365D;box-shadow:0 0 0 2px rgba(27,54,93,.12)}
#ai-settings textarea{min-height:200px;resize:vertical;font-family:ui-monospace,Menlo,monospace;line-height:1.6}
#ai-settings .ai-row{display:flex;gap:12px}
#ai-settings .ai-row>div{flex:1}
#ai-settings .ai-footer{margin-top:20px;display:flex;gap:8px;justify-content:flex-end}
#ai-settings button{padding:9px 18px;border:1px solid #e0d5c0;border-radius:3px;cursor:pointer;font-size:13px;font-family:inherit;transition:background .15s;display:inline-flex;align-items:center;justify-content:center;line-height:1;vertical-align:middle;box-sizing:border-box}
#ai-settings .ai-save{background:#1B365D;color:#faf5ea;border-color:#14263f}
#ai-settings .ai-save:hover{background:#14263f}
#ai-settings .ai-cancel{background:#faf5ea;color:#3a342c}
#ai-settings .ai-cancel:hover{background:#f0e9d8}
#ai-settings .ai-reset{background:#faf5ea;color:#8b3a1f;border-color:#d4b8a8;margin-right:auto}
#ai-settings .ai-reset:hover{background:#f5efe0}
.ai-model-dropdown{position:absolute;left:0;right:0;top:100%;max-height:200px;overflow-y:auto;background:#fffdf7;border:1px solid #e0d5c0;border-top:none;border-radius:0 0 3px 3px;box-shadow:0 4px 12px rgba(42,37,32,.12);z-index:10;display:none}
.ai-model-item{padding:7px 11px;cursor:pointer;font-size:13px;color:#2a2520}
.ai-model-item:hover{background:#f0e9d8}
.ai-model-loading,.ai-model-error{font-style:italic;color:#8a7f70;cursor:default}
.ai-model-loading:hover,.ai-model-error:hover{background:transparent}
#ai-copy-modal{position:fixed;inset:0;z-index:1000001;display:none;align-items:center;justify-content:center;background:rgba(42,37,32,.42);backdrop-filter:blur(2px);animation:ai-pop .16s ease-out}
#ai-copy-modal.open{display:flex}
#ai-copy-modal .ai-cm-card{position:relative;width:280px;max-width:calc(100vw - 40px);background:#faf5ea;color:#2a2520;border-radius:5px;box-shadow:0 14px 44px rgba(42,37,32,.28);padding:22px 20px 18px;border:1px solid #e0d5c0;font-family:Georgia,"Songti SC","STSong","Source Han Serif SC",serif}
#ai-copy-modal .ai-cm-title{font-size:14px;font-weight:600;color:#1B365D;text-align:center;margin-bottom:16px;letter-spacing:.02em}
#ai-copy-modal .ai-cm-btn{width:100%;display:flex;align-items:center;justify-content:center;gap:8px;padding:11px 12px;border:1px solid #e0d5c0;border-radius:3px;cursor:pointer;font-size:13.5px;font-weight:500;line-height:1;font-family:inherit;transition:background .15s,transform .1s;margin-bottom:10px}
#ai-copy-modal .ai-cm-btn:last-of-type{margin-bottom:0}
#ai-copy-modal .ai-cm-btn:active{transform:scale(.97)}
#ai-copy-modal .ai-cm-text{background:#1B365D;color:#faf5ea;border-color:#14263f}
#ai-copy-modal .ai-cm-text:hover{background:#14263f}
#ai-copy-modal .ai-cm-image{background:#faf5ea;color:#3a342c}
#ai-copy-modal .ai-cm-image:hover{background:#f0e9d8}
#ai-copy-modal .ai-cm-x{position:absolute;top:8px;right:10px;width:24px;height:24px;border:none;background:transparent;color:#8a7f70;font-size:16px;cursor:pointer;line-height:1;display:flex;align-items:center;justify-content:center;border-radius:3px}
#ai-copy-modal .ai-cm-x:hover{background:#f0e9d8;color:#1B365D}
`);
// === 平台爬虫集合 ===
// 每个方法同步抓取当前 DOM 上的评论,返回统一结构 { author, text, likes }。
// 特殊字段:zhihu.accepted(被采纳答案)、hackernews.depth(嵌套层级)、linuxdo.isOP(楼主标记)。
// 复杂平台(Twitter、Linux.do)支持外部 __ai_*_comments 缓存,由 autoLoad* 异步填充。
const Scrapers = {
youtube() {
return Array.from(document.querySelectorAll('ytd-comment-thread-renderer')).map(el => ({
author: (el.querySelector('#author-text')?.textContent || '').trim(),
text: (el.querySelector('#content-text')?.innerText || '').trim(),
likes: parseInt(el.querySelector('#vote-count-middle')?.textContent || '0', 10) || 0
})).filter(c => c.text);
},
reddit() {
return Array.from(document.querySelectorAll('shreddit-comment')).map(el => ({
author: el.getAttribute('author') || '',
text: (el.querySelector('[slot="comment"]')?.innerText || el.querySelector('div[md]')?.innerText || '').trim(),
likes: parseInt(el.getAttribute('score') || '0', 10) || 0
})).filter(c => c.text);
},
bilibili() {
const root = document.querySelector('bili-comments')?.shadowRoot;
if (!root) return [];
return Array.from(root.querySelectorAll('bili-comment-thread-renderer')).map(t => {
const comment = t?.shadowRoot?.querySelector('bili-comment-renderer');
const cr = comment?.shadowRoot;
if (!cr) return { author: '', text: '', likes: 0 };
const userInfo = cr.querySelector('#header bili-comment-user-info');
const author = userInfo?.shadowRoot?.querySelector('#user-name')?.textContent?.trim()
|| userInfo?.textContent?.trim() || '';
const rich = cr.querySelector('#content bili-rich-text');
const text = rich?.shadowRoot?.querySelector('#contents')?.textContent?.trim()
|| rich?.textContent?.trim() || '';
const actions = cr.querySelector('#footer bili-comment-action-buttons-renderer');
const likes = parseInt(actions?.shadowRoot?.querySelector('#like')?.textContent?.trim() || '0', 10) || 0;
return { author, text, likes };
}).filter(c => c.text);
},
zhihu() {
return Array.from(document.querySelectorAll('.ContentItem.AnswerItem')).map(el => {
const authorEl = el.querySelector('.AuthorInfo-name, .UserLink-link, a[href*="/people/"]');
const contentEl = el.querySelector('.RichText, .AnswerContent .RichText, .ContentItem.RichText');
const voteBtn = el.querySelector('button[aria-label^="赞同"]');
let likes = 0;
if (voteBtn) {
const m = (voteBtn.getAttribute('aria-label') || voteBtn.innerText || '').match(/\d+/);
if (m) likes = parseInt(m[0], 10) || 0;
}
return {
author: (authorEl?.textContent || '').trim() || '匿名',
text: (contentEl?.innerText || '').trim(),
likes,
accepted: el.getAttribute('itemprop') === 'acceptedAnswer'
};
}).filter(c => c.text);
},
xiaohongshu() {
const items = Array.from(document.querySelectorAll('.comment-item, .comment-inner, .comment-item-sub'));
const seen = new Set();
return items.map(el => {
const author = (el.querySelector('.user-name, .author, .author-wrapper [class*="name"]')?.textContent || '').trim();
const text = (el.querySelector('.content, .note-text, .text, [class*="content"]')?.innerText || '').trim();
if (!text || seen.has(text)) return { author: '', text: '', likes: 0 };
seen.add(text);
const likeEl = el.querySelector('.like-count, .like, [class*="like"]');
const likes = parseInt(likeEl?.textContent || '0', 10) || 0;
return { author, text, likes };
}).filter(c => c.text);
},
twitter() {
if (window.__ai_twitter_comments) return window.__ai_twitter_comments;
return Array.from(document.querySelectorAll('article[data-testid="tweet"]')).map(el => {
const userNameEl = el.querySelector('[data-testid="User-Name"]');
let author = '';
if (userNameEl) {
const firstLink = userNameEl.querySelector('a span') || userNameEl.querySelector('a');
if (firstLink) author = firstLink.textContent.trim();
if (!author || author.startsWith('@')) {
author = userNameEl.textContent
.replace(/@[A-Za-z0-9_]+/, '')
.replace(/·\s*[\dhms]+(\s*(AM|PM|hours?|hrs?|mins?|minutes?|days?))?\s*$/i, '')
.replace(/·\s*\d+[hm]\s*$/i, '')
.trim();
}
}
const textEl = el.querySelector('[data-testid="tweetText"]');
let text = '';
if (textEl) {
text = textEl.innerText.trim();
} else {
const langEls = el.querySelectorAll('[lang]');
text = [...langEls].map(l => l.textContent.trim()).join(' ').trim();
}
const likeAria = el.querySelector('[data-testid="like"]')?.getAttribute('aria-label') || '';
let likes = 0;
const lm = likeAria.match(/([\d,.]+)\s*Likes?/i);
if (lm) {
const raw = lm[1].replace(/,/g, '');
if (/k$/i.test(raw)) likes = Math.round(parseFloat(raw) * 1000);
else if (/m$/i.test(raw)) likes = Math.round(parseFloat(raw) * 1000000);
else likes = parseInt(raw, 10) || 0;
}
return { author, text, likes };
}).filter(c => c.text);
},
hackernews() {
return Array.from(document.querySelectorAll('tr.athing.comtr')).map(el => {
const author = el.querySelector('.hnuser')?.textContent?.trim() || '';
const text = el.querySelector('.commtext')?.innerText?.trim() || '';
const scoreText = el.querySelector('.score')?.textContent || '';
const likes = parseInt(scoreText.replace(/[^\d]/g, ''), 10) || 0;
const indent = el.querySelector('.ind')?.getAttribute('indent') || '0';
const depth = parseInt(indent, 10) || 0;
return { author, text, likes, depth };
}).filter(c => c.text);
},
linuxdo() {
if (window.__ai_linuxdo_comments) return window.__ai_linuxdo_comments;
return Array.from(document.querySelectorAll('.topic-post')).map(p => {
const cooked = p.querySelector('.cooked');
const user = p.querySelector('a[data-user-card]');
const counter = p.querySelector('.discourse-reactions-counter .reactions-counter');
return {
author: (user?.textContent || '').trim() || '匿名',
text: (cooked?.innerText || '').trim(),
likes: parseInt((counter?.textContent || '0').trim(), 10) || 0,
isOP: p.classList.contains('post--topic-owner')
};
}).filter(c => c.text);
},
tieba() {
const vueEl = document.querySelector('.thread-container');
if (vueEl && vueEl.__vue__) {
const list = vueEl.__vue__.$props?.list;
// 【动态楼中楼采样上限】
// 硬约束:主楼层 + 楼中楼 总评论数 ≤ 500(用户配置 maxComments)
// 计算公式:每楼中楼 = floor(maxComments / 主楼层数)
// 边界:主楼层数 > maxComments 时,每楼取 1 条(保证热门长贴仍可解析)
// 兜底:主楼层数 ≤ 0 或缺失时,每楼取 3 条
const MAX_TOTAL = config.maxComments || 500;
const mainCount = list?.length || 0;
const lzlLimit = mainCount > 0
? Math.max(1, Math.floor(MAX_TOTAL / mainCount))
: 3;
if (Array.isArray(list) && list.length) {
// Vue 数据中只有 author_id(数字),用其作为 author
function extractText(contentArr) {
if (!Array.isArray(contentArr)) return '';
return contentArr.map(c => {
if (c.type === 0) return c.text || '';
if (c.type === 2) return c.c ? `[${c.c}]` : (c.text || '');
if (c.type === 3) return '[图片]';
return '';
}).join('');
}
const comments = [];
for (const item of list) {
const text = extractText(item.content);
if (!text) continue;
const agree = item.agree?.agree_num || 0;
comments.push({
author: '用户' + item.author_id,
text,
likes: agree
});
// 楼中楼(按主楼层数动态采样上限 lzlLimit)
const subObj = item.sub_post_list;
if (subObj && typeof subObj === 'object' && Array.isArray(subObj.sub_post_list)) {
for (const lzl of subObj.sub_post_list.slice(0, lzlLimit)) {
const lzlText = extractText(lzl.content);
if (lzlText) {
comments.push({
author: '',
text: lzlText,
likes: lzl.agree?.agree_num || 0
});
}
}
}
}
if (comments.length) return comments;
}
}
// fallback:DOM 抓取
return Array.from(document.querySelectorAll('.pb-comment-item')).map(el => {
const author = (el.querySelector('.head-name')?.textContent || '').trim() || '匿名';
const text = (el.querySelector('.pb-rich-text')?.innerText
|| el.querySelector('.comment-content')?.innerText || '').trim();
const likes = parseInt(el.querySelector('.zan-container span')?.textContent?.replace(/[^\d]/g, ''), 10) || 0;
return { author, text, likes };
}).filter(c => c.text);
},
douyin() {
if (window.__ai_douyin_comments) return window.__ai_douyin_comments;
return Array.from(document.querySelectorAll('[data-e2e="comment-item"]')).map(el => {
const author = (el.querySelector('.comment-item-info-wrap a')?.innerText || '').trim();
// 正文:info-wrap 之后、stats-container 之前的第一个非空文本块
const infoWrap = el.querySelector('.comment-item-info-wrap');
const stats = el.querySelector('.comment-item-stats-container');
let text = '';
if (infoWrap && stats) {
let node = infoWrap.nextElementSibling;
while (node && node !== stats) {
const t = (node.innerText || '').trim();
if (t) { text = t; break; }
node = node.nextElementSibling;
}
}
const likeText = (el.querySelector('.comment-item-stats-container p')?.textContent || '0').trim();
let likes = 0;
if (/万$/.test(likeText)) {
likes = Math.round(parseFloat(likeText) * 10000);
} else {
likes = parseInt(likeText, 10) || 0;
}
return { author, text, likes };
}).filter(c => c.text);
}
};
// 根据当前 hostname 选定爬虫;未匹配站点返回 null
function detectScraper() {
const h = location.hostname;
if (h.includes('youtube.com')) return 'youtube';
if (h.includes('reddit.com')) return 'reddit';
if (h.includes('bilibili.com')) return 'bilibili';
if (h.includes('zhihu.com')) return 'zhihu';
if (h.includes('xiaohongshu.com')) return 'xiaohongshu';
if (h.includes('twitter.com') || h.includes('x.com')) return 'twitter';
if (h.includes('news.ycombinator.com')) return 'hackernews';
if (h.includes('linux.do')) return 'linuxdo';
if (h.includes('tieba.baidu.com')) return 'tieba';
if (h.includes('douyin.com')) return 'douyin';
return null;
}
function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
// === 通用自动加载(YouTube / Reddit 共用)===
// 通过反复滚动 + 点击"更多"按钮直到评论数稳定或达到 max。
// 两阶段:先快速滚动 40 次(连续 4 次无新增视为稳定),再 8 次慢速兜底。
async function autoLoadComments(scraper, max, cb, token) {
let last = 0, stable = 0;
for (let i = 0; i < 40; i++) {
if (token?.aborted) return;
clickMoreButtons();
const ytCont = document.querySelector(
'ytd-comments #contents > ytd-continuation-item-renderer, ' +
'ytd-item-section-renderer#sections #contents > ytd-continuation-item-renderer'
);
if (ytCont) {
ytCont.scrollIntoView({ behavior: 'instant', block: 'center' });
} else {
const c = document.querySelector('shreddit-app')
|| document.scrollingElement;
if (c) c.scrollTop = c.scrollHeight;
window.scrollTo(0, document.documentElement.scrollHeight);
}
await sleep(1200);
if (token?.aborted) return;
const items = scraper();
if (items.length >= max) break;
if (items.length === last) { stable++; if (stable >= 4) break; }
else stable = 0;
last = items.length;
cb && cb(items.length);
}
for (let k = 0; k < 8; k++) {
if (token?.aborted) return;
const before = scraper().length;
clickMoreButtons();
await sleep(1500);
if (token?.aborted) return;
const after = scraper().length;
cb && cb(after);
if (after >= max || after === before) break;
}
}
// === Twitter/X 自动加载 ===
// 用 Map 按 text 去重(同一条推文会反复出现)。
// 两阶段:先滚到底 40 次(含偶尔回滚触发懒加载),再从底部 6 等分往上扫一遍捞漏。
async function autoLoadTwitterComments(scraper, max, cb, token) {
const collected = new Map();
let batch = scraper();
for (const c of batch) {
if (c.text) collected.set(c.text, c);
}
cb && cb(collected.size);
let prevSize = collected.size;
let stable = 0;
for (let i = 0; i < 40; i++) {
if (token?.aborted) return;
if (i % 2 === 0) {
window.scrollTo(0, document.documentElement.scrollHeight);
} else {
window.scrollTo(0, Math.max(0, document.documentElement.scrollHeight - window.innerHeight * 1.5));
await sleep(300);
window.scrollTo(0, document.documentElement.scrollHeight);
}
await sleep(1500);
if (token?.aborted) return;
batch = scraper();
for (const c of batch) {
if (c.text) collected.set(c.text, c);
}
if (collected.size >= max) break;
if (collected.size === prevSize) {
stable++;
if (stable >= 4) break;
} else {
stable = 0;
}
prevSize = collected.size;
cb && cb(collected.size);
}
stable = 0;
let lastSize = collected.size;
for (let i = 0; i < 10; i++) {
if (token?.aborted) return;
const scrollStep = Math.floor(document.documentElement.scrollHeight / 6);
const target = document.documentElement.scrollHeight - (i + 1) * scrollStep;
window.scrollTo(0, Math.max(0, target));
await sleep(1200);
if (token?.aborted) return;
batch = scraper();
for (const c of batch) {
if (c.text) collected.set(c.text, c);
}
if (collected.size === lastSize) {
stable++;
if (stable >= 3) break;
} else {
stable = 0;
}
lastSize = collected.size;
cb && cb(collected.size);
}
window.__ai_twitter_comments = [...collected.values()];
cb && cb(collected.size);
}
// 小红书评论在独立滚动容器内,向上找第一个 overflow:auto/scroll 且有滚动空间的祖先
function findXHSCommentScroller() {
const item = document.querySelector('.comment-item, .comment-item-sub');
let node = item?.parentElement;
while (node && node !== document.body) {
const style = getComputedStyle(node);
if ((style.overflowY === 'auto' || style.overflowY === 'scroll') && node.scrollHeight > node.clientHeight + 20) {
return node;
}
node = node.parentElement;
}
return document.scrollingElement;
}
// === 小红书 / B 站自动加载 ===
// SAFE 上限 500 避免无限滚动把内存撑爆;二者结构类似:滚动到底 → 等加载 → 数稳定即停。
async function autoLoadXHSComments(scraper, max, cb, token) {
const SAFE = 500;
let last = 0, stable = 0;
for (let i = 0; i < 30; i++) {
if (token?.aborted) return;
const scroller = findXHSCommentScroller();
if (scroller && scroller !== document.scrollingElement) {
scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' });
}
window.scrollTo(0, document.body.scrollHeight);
await sleep(1800 + Math.random() * 700);
if (token?.aborted) return;
const items = scraper();
if (items.length >= max || items.length >= SAFE) break;
if (items.length === last) { stable++; if (stable >= 4) break; }
else stable = 0;
last = items.length;
cb && cb(items.length);
}
}
async function autoLoadBiliComments(scraper, max, cb, token) {
const SAFE = 500;
let last = 0, stable = 0;
for (let i = 0; i < 30; i++) {
if (token?.aborted) return;
const c = document.scrollingElement;
if (c) c.scrollTop = c.scrollHeight;
window.scrollTo(0, document.body.scrollHeight);
await sleep(1500 + Math.random() * 600);
if (token?.aborted) return;
const items = scraper();
if (items.length >= max || items.length >= SAFE) break;
if (items.length === last) { stable++; if (stable >= 4) break; }
else stable = 0;
last = items.length;
cb && cb(items.length);
}
}
// === Shadow DOM 全局扫描 + 通用"更多"按钮点击 ===
// YouTube/B 站评论藏在 closed shadow root,必须递归收集 host 才能命中按钮。
// _clickedBtns 用 WeakSet 避免按钮被回收后内存泄漏;_scanTick 每 8 轮重新扫描一次 shadow 树(成本高)。
const _shadowHosts = new Set();
const _clickedBtns = new WeakSet();
let _scanTick = 0;
// 递归收集所有 shadowRoot 的 host(含嵌套 shadow)
function collectShadowHosts() {
_shadowHosts.clear();
function walk(root) {
for (const el of root.querySelectorAll('*')) {
if (el.shadowRoot) {
_shadowHosts.add(el);
walk(el.shadowRoot);
}
}
}
walk(document);
}
// 在 document + 所有已知 shadow root 内找匹配"更多/展开/View more"的按钮并点击
// 关键过滤:排除侧边栏(避免误点关注/Trends)、限制文字长度(避免点到段落)、显式黑名单
function clickMoreButtons() {
if ((_scanTick++ & 7) === 0) collectShadowHosts();
const RE = /查看更多|更多评论|更多回复|加载更多|展开更多|更多结果|展开.*条回复|View more|more replies|load more|see more|show more/i;
const EXCLUDE_RE = /^Follow$|^关注$|^Unfollow$|^取消关注$/i;
const SIDEBAR = '[data-testid="sidebarColumn"], [aria-label="Trends for you"], [aria-label="Who to follow"]';
const roots = [document];
for (const host of _shadowHosts) {
if (host.isConnected && host.shadowRoot) roots.push(host.shadowRoot);
}
let clicked = 0;
for (const root of roots) {
let btns;
try { btns = root.querySelectorAll('button, a, [role="button"]'); }
catch { continue; }
for (const b of btns) {
if (_clickedBtns.has(b)) continue;
if (b.closest(SIDEBAR)) continue;
const txt = (b.innerText || b.textContent || '').trim();
if (!txt || txt.length >= 40) continue;
if (EXCLUDE_RE.test(txt)) continue;
if (RE.test(txt)) {
try { b.click(); _clickedBtns.add(b); clicked++; } catch {}
}
}
}
return clicked;
}
// HN 翻页用 GM_xmlhttpRequest 绕过跨域,anonymous 不带 cookie 减少服务器压力
function fetchHNPage(url) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url,
anonymous: true,
onload: (res) => {
if (res.status >= 200 && res.status < 300) resolve(res.responseText);
else reject(new Error('HN page HTTP ' + res.status));
},
onerror: (e) => reject(new Error('HN page fetch failed: ' + (e.error || 'network')))
});
});
}
// === Hacker News 自动加载 ===
// HN 是服务端分页(?p=2,3...),通过 a.morelink 拿下一页 HTML,DOMParser 解析后把评论 table 追加到当前页
async function autoLoadHNComments(scraper, max, cb, token) {
let collected = scraper().length;
cb && cb(collected);
if (collected >= max) return;
const isItemPage = /\/item\?id=\d+/.test(location.pathname + location.search);
if (!isItemPage) return;
for (let page = 2; page <= 30; page++) {
if (token?.aborted) return;
if (collected >= max) break;
const moreHref = document.querySelector('a.morelink')?.getAttribute('href');
if (!moreHref) break;
let html;
try { html = await fetchHNPage('https://news.ycombinator.com/' + moreHref); }
catch (e) { console.warn('[AI总结] HN 翻页失败:', e); break; }
if (token?.aborted) return;
const doc = new DOMParser().parseFromString(html, 'text/html');
const tables = doc.querySelectorAll('table');
for (const t of tables) {
const clone = document.importNode(t, true);
const target = document.querySelector('table.comment-tree') || document.body;
target.appendChild(clone);
}
const newMore = doc.querySelector('a.morelink')?.getAttribute('href');
const curMore = document.querySelector('a.morelink');
if (curMore && newMore) curMore.setAttribute('href', newMore);
else if (curMore && !newMore) curMore.remove();
collected = scraper().length;
cb && cb(collected);
if (collected >= max) break;
await sleep(150);
}
}
// === 知乎回答自动加载 ===
// 先点开所有"展开全文",再循环点"更多回答"/滚动到底,stable=3 即停
async function autoLoadZHAnswers(scraper, max, cb, token) {
let last = 0, stable = 0;
for (let i = 0; i < 30; i++) {
if (token?.aborted) return;
document.querySelectorAll('button').forEach(b => {
if (/展开全文|显示全部|展开/.test(b.innerText)) b.click();
});
const items = scraper();
if (items.length >= max) break;
if (items.length === last) { stable++; if (stable >= 3) break; }
else stable = 0;
last = items.length;
cb && cb(items.length);
const moreBtn = [...document.querySelectorAll('button')]
.find(b => /更多回答|查看更多/.test(b.innerText));
if (moreBtn) {
moreBtn.click();
} else {
window.scrollTo(0, document.body.scrollHeight);
}
await sleep(1500);
if (token?.aborted) return;
}
}
// === Linux.do 自动加载(走 Discourse JSON API)===
// 走 /t/{id}.json?page=N 翻页比 DOM 滚动可靠,按 post_number 建索引后递归算 depth 还原嵌套层级。
// 失败回退到 DOM 抓取(scraper 直接读 .topic-post)。结果写入 window.__ai_linuxdo_comments 供 scraper 取。
async function autoLoadLinuxdoComments(scraper, max, cb, token) {
const m = location.pathname.match(/\/t\/(?:[^\/]+\/)?(\d+)/);
if (!m) return;
const topicId = m[1];
try {
const d1 = await fetch(`/t/${topicId}.json?page=1`, { credentials: 'include' }).then(r => r.json());
if (token?.aborted) return;
const totalPosts = d1.posts_count || d1.post_stream?.stream?.length || 0;
const allPosts = [...(d1.post_stream?.posts || [])];
cb && cb(allPosts.length);
const totalPages = Math.ceil(totalPosts / 20);
for (let page = 2; page <= totalPages; page++) {
if (token?.aborted) return;
if (allPosts.length >= max) break;
try {
const d = await fetch(`/t/${topicId}.json?page=${page}`, { credentials: 'include' }).then(r => r.json());
if (token?.aborted) return;
const posts = d.post_stream?.posts || [];
if (!posts.length) break;
allPosts.push(...posts);
cb && cb(allPosts.length);
} catch (e) { break; }
await sleep(300);
}
// 通过 reply_to_post_number 链式追溯祖先算嵌套深度,visited 防环,d>20 兜底
const map = new Map(allPosts.map(p => [p.post_number, p]));
function getDepth(p) {
let d = 0, cur = p, visited = new Set();
while (cur && cur.reply_to_post_number != null && !visited.has(cur.post_number)) {
visited.add(cur.post_number);
d++;
cur = map.get(cur.reply_to_post_number);
if (d > 20) break;
}
return d;
}
const comments = allPosts
.filter(p => p.post_number !== 1)
.map(p => {
const tmp = document.createElement('div');
safeHTML(tmp, p.cooked || '');
return {
author: p.username || '匿名',
text: (tmp.innerText || '').trim(),
likes: p.actions_summary?.find(a => a.id === 2)?.count || 0,
postNumber: p.post_number,
depth: getDepth(p),
isOP: false
};
})
.filter(c => c.text);
window.__ai_linuxdo_comments = comments;
cb && cb(comments.length);
} catch (e) {
console.warn('[AI总结] linux.do JSON API 失败,回退 DOM', e);
}
}
// === 百度贴吧自动加载 ===
// 两阶段:
// 1. 循环 emit('load-more') 加载全部主楼层(虚拟列表初始只预加载 ~15 条)
// 2. 逐步滚动 + 点击 .show-more-lzl 展开楼中楼(初始只有 4-5 条,需点击展开)
async function autoLoadTiebaComments(scraper, max, cb, token) {
const scrollDom = document.querySelector('.pc-pb-box.styled-scrollbar.deep')
|| document.scrollingElement;
// 阶段 1:等待 Vue 组件就绪
for (let i = 0; i < 10; i++) {
if (token?.aborted) return;
const vueEl = document.querySelector('.thread-container');
if (vueEl && vueEl.__vue__ && vueEl.__vue__.$props?.list) break;
await sleep(500);
}
// 阶段 2:循环触发 load-more 加载全部主楼层
const vueEl = document.querySelector('.thread-container');
if (vueEl && vueEl.__vue__) {
const vm = vueEl.__vue__;
for (let i = 0; i < 100; i++) {
if (token?.aborted) return;
if (!vm.$props?.hasMore) break;
if (scraper().length >= max) break;
vm.$emit('load-more');
await sleep(800);
cb && cb(scraper().length);
}
}
// 阶段 3:逐步滚动展开楼中楼
// 虚拟列表只渲染可视区域附近的楼层,必须步进式滚动让每层 DOM 渲染出来
if (scrollDom) {
for (let pos = 0; pos <= scrollDom.scrollHeight; pos += 400) {
if (token?.aborted) return;
if (scraper().length >= max) break;
scrollDom.scrollTop = pos;
await sleep(300);
// 点击当前可视区域内的 show-more-lzl 按钮
const btns = document.querySelectorAll('.show-more-lzl');
for (const btn of btns) {
if (token?.aborted) return;
btn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
await sleep(800);
cb && cb(scraper().length);
}
}
}
const items = scraper();
cb && cb(items.length);
}
// === 抖音自动加载 ===
// 评论列表虚拟化,真正的滚动祖先通过 getComputedStyle 向上遍历定位。
// 滚动到底触发懒加载,配合 Map 去重避免虚拟列表回收节点导致丢失。
async function autoLoadDouyinComments(scraper, max, cb, token) {
const SAFE = 500;
function findScroller() {
let node = document.querySelector('[data-e2e="comment-list"]');
while (node && node !== document.body) {
const style = getComputedStyle(node);
if ((style.overflowY === 'auto' || style.overflowY === 'scroll')
&& node.scrollHeight > node.clientHeight + 10) {
return node;
}
node = node.parentElement;
}
return document.scrollingElement;
}
const scroller = findScroller();
if (!scroller) return;
const collected = new Map();
let batch = scraper();
for (const c of batch) { if (c.text) collected.set(c.text, c); }
cb && cb(collected.size);
let prevSize = collected.size;
let stable = 0;
for (let i = 0; i < 40; i++) {
if (token?.aborted) return;
if (collected.size >= max || collected.size >= SAFE) break;
scroller.scrollTo({ top: scroller.scrollHeight, behavior: 'smooth' });
await sleep(2000 + Math.random() * 800);
if (token?.aborted) return;
batch = scraper();
for (const c of batch) { if (c.text) collected.set(c.text, c); }
if (collected.size >= max || collected.size >= SAFE) break;