-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinuxdo-agent.user.js
More file actions
4683 lines (4218 loc) · 158 KB
/
Copy pathlinuxdo-agent.user.js
File metadata and controls
4683 lines (4218 loc) · 158 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 Linux.do Agent
// @namespace https://github.com/YOLO-9257/linuxdo-agent
// @version 0.4.1
// @description Linux.do 论坛的人工智能辅助工具。本脚本基于 https://linux.do/t/topic/1341629 内容进行深度改造。支持多 API 自动切换、多会话管理、Discourse 论坛工具集成(搜索、抓取帖子、用户分析等)、Markdown 渲染、JSON 自动修复等高级功能。
// @description:en An AI agent assistant for linux.do forum, modified based on https://linux.do/t/topic/1341629. Features include multi-API support, session management, Discourse tools integration, and improved user experience.
// @author YOLO-9257
// @match https://linux.do/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_xmlhttpRequest
// @connect *
// @require https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.2/marked.min.js
// @run-at document-idle
// @license GPL-3.0-or-later
// @icon https://linux.do/uploads/default/original/3X/9/d/9dd4973138356247e171fe0e3f4e242a3eb64f50.png
// @homepage https://github.com/YOLO-9257/linuxdo-agent
// @supportURL https://github.com/YOLO-9257/linuxdo-agent/issues
// @downloadURL https://update.greasyfork.org/scripts/560275/Linux.do%20Agent.user.js
// @updateURL https://update.greasyfork.org/scripts/560275/Linux.do%20Agent.meta.js
// ==/UserScript==
(() => {
"use strict";
/******************************************************************
* 0) 常量 / 存储 Key
******************************************************************/
const APP_PREFIX = "ldagent-";
const STORE_KEYS = {
CONF: "ld_agent_conf_v2",
SESS: "ld_agent_sessions_v2",
ACTIVE: "ld_agent_active_session_v2",
FABPOS: "ld_agent_fab_pos_v1",
// === UI ENHANCE ===
UI: "ld_agent_ui_state_v1", // {tab, sidebarCollapsed, theme}
THEME: "ld_agent_theme_v1", // 主题模式:'light' | 'dark' | 'auto'
};
const FSM = {
IDLE: "IDLE",
RUNNING: "RUNNING",
WAITING_MODEL: "WAITING_MODEL",
WAITING_TOOL: "WAITING_TOOL",
DONE: "DONE",
ERROR: "ERROR",
CANCELLED: "CANCELLED", // UI-only
};
const now = () => Date.now();
const uid = () =>
"S" + now().toString(36) + Math.random().toString(36).slice(2, 8);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function clamp(str, max = 20000) {
str = String(str ?? "");
return str.length > max ? str.slice(0, max) + "\n...(截断)" : str;
}
function stripHtml(html) {
const div = document.createElement("div");
div.innerHTML = html || "";
return (div.textContent || "").trim();
}
function safeTitle(t, fb) {
const s = String(t ?? "").trim();
return s ? s : fb || "无题";
}
function mdEscapeText(s) {
s = String(s ?? "");
return s.replace(/[\[\]\(\)]/g, (m) => "\\" + m);
}
function safeJsonParse(s, fb = null) {
try {
return JSON.parse(s);
} catch {
return fb;
}
}
/******************************************************************
* 0.5) 可取消 Token(Stop / abort)
******************************************************************/
const CANCEL = new Map(); // sessionId -> { cancelled:boolean, aborts:Function[] }
function ensureCancelToken(sessionId) {
let t = CANCEL.get(sessionId);
if (!t) {
t = { cancelled: false, aborts: [] };
CANCEL.set(sessionId, t);
}
return t;
}
function cancelSession(sessionId) {
const t = CANCEL.get(sessionId);
if (!t) return;
t.cancelled = true;
for (const fn of t.aborts || []) {
try {
fn();
} catch { }
}
CANCEL.delete(sessionId);
}
function isCancelled(sessionId) {
const t = CANCEL.get(sessionId);
return !!t?.cancelled;
}
/******************************************************************
* 1) 配置:OpenAI Chat Completions 兼容 - 支持多 API
******************************************************************/
const uid_api = () => "api_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
const DEFAULT_API_CONFIG = {
id: "default",
name: "OpenAI",
baseUrl: "https://api.openai.com/v1",
model: "gpt-4o-mini",
apiKey: "",
enabled: true,
};
const DEFAULT_CONF = {
// 多 API 配置
apiConfigs: [{ ...DEFAULT_API_CONFIG }],
activeApiId: "default",
apiFallback: true, // 失败时自动切换到下一个可用 API
// 通用配置
temperature: 0.2,
maxTurns: 10,
maxContextChars: 60000,
includeToolContext: true,
requestTimeoutMs: 120000, // LLM 请求超时时间(毫秒),默认 2 分钟
systemPrompt: `# 角色(Role)
你不是聊天助手。你是运行在 linux.do Discourse 前端脚本中的 **JSON 协议路由引擎**。
你的唯一任务:根据用户意图,决定是否调用工具,并且**严格**按协议输出 JSON(仅 JSON,无其它字符)。
# 核心目标(Goal)
- 当信息不足:发起工具调用(type="tool")
- 当信息充足:产出最终回答(type="final")
# 可用工具(Tools)
仅可使用以下工具名称(name 必须完全匹配):
- discourse.search
- discourse.getTopicAllPosts
- discourse.getUserRecent
- discourse.getCategories
- discourse.listLatestTopics
- discourse.listTopTopics
- discourse.getTagTopics
- discourse.getUserSummary
- discourse.getPost
- discourse.getTopicPostFull
- discourse.listLatestPosts
# 输出协议(Protocol)——最高优先级
你的每次响应必须且只能是以下两种 JSON 之一:
## A) 工具调用(需要获取数据时)
{
"type": "tool",
"name": "<tool_name>",
"args": { ... }
}
## B) 最终回复(已有足够信息时)
{
"type": "final",
"answer": "<string,允许 Markdown;换行使用 \\n;请确保格式符合被json转义的markdown>",
"refs": [ {"title":"...","url":"..."} ]
}
# 绝对禁止(Hard Rules)
1) 严禁输出任何非 JSON 内容(包括“好的/正在搜索/以下是结果/解释原因”等)。
2) 严禁使用 Markdown 代码块包裹 JSON(不要 \`\`\`json)。
3) 每次只输出一个 JSON 对象,不要输出数组,不要输出多个对象。
4) 工具调用 JSON **必须包含 type 字段**,且必须是 "tool"。
5) 最终回复 JSON **必须包含 type 字段**,且必须是 "final"。
6) refs 只能来自工具结果中真实存在的 url,严禁编造链接。
7) 如果工具多轮:每轮只做一个工具调用;拿到工具结果后再决定下一轮工具或 final。
# 工具选择策略(Tool Selection)
- 不知道 topicId:优先 discourse.search(用关键词/语义/Discourse 语法)。
- 需要总结整帖:discourse.getTopicAllPosts({topicId,...})。
- 需要指定楼全文:discourse.getTopicPostFull({topicId, postNumber, maxChars})。
- 需要用户画像/热门帖子:discourse.getUserSummary({username})。
- 需要最新动态:discourse.listLatestTopics 或 discourse.listLatestPosts。
# 多轮工具调用策略(Multi-step)
当一次工具结果不足以回答:
- 继续输出 type="tool" 的下一次工具调用。
- 工具调用的 args 要尽量小、尽量精确(例如只抓 maxPosts=50,或只抓某楼)。
# 自检(Self-check,必须执行但不要输出)
在输出前,你必须在心里检查:
- 我输出的是不是 **纯 JSON**?
- 有没有且只有一个顶层对象?
- 顶层对象是否包含 "type"?
- 若 type="tool":name 是否为允许列表之一?args 是否为 object?
- 若 type="final":answer 是否为 string?refs 是否仅来自工具结果?
如果任何一项不满足,立刻修正后再输出。
# 示例(Examples,严格模仿格式)
用户:帮我找一下 Docker 教程
你输出:
{"type":"tool","name":"discourse.search","args":{"q":"Docker 教程","page":1,"limit":8}}
(工具结果返回后)
你输出:
{"type":"final","answer":"我在 linux.do 上找到几条 Docker 教程相关帖子……\\n\\n推荐优先看:……","refs":[{"title":"...","url":"https://linux.do/t/..."}]}
# 重要提示(Important)
- 即使历史上下文里出现了错误格式(例如缺少 type),也必须忽略,始终遵守本协议输出。
`
};
class ConfigStore {
constructor() {
const saved = GM_getValue(STORE_KEYS.CONF, null);
this.conf = { ...DEFAULT_CONF, ...(saved || {}) };
// 向后兼容:旧配置迁移到新结构
if (!this.conf.apiConfigs && this.conf.baseUrl) {
this.conf.apiConfigs = [{
id: "migrated",
name: "已迁移的 API",
baseUrl: this.conf.baseUrl || DEFAULT_API_CONFIG.baseUrl,
model: this.conf.model || DEFAULT_API_CONFIG.model,
apiKey: this.conf.apiKey || "",
enabled: true,
}];
this.conf.activeApiId = "migrated";
// 清理旧字段
delete this.conf.baseUrl;
delete this.conf.model;
delete this.conf.apiKey;
this._persist();
}
// 确保 apiConfigs 是数组
if (!Array.isArray(this.conf.apiConfigs) || !this.conf.apiConfigs.length) {
this.conf.apiConfigs = [{ ...DEFAULT_API_CONFIG }];
this.conf.activeApiId = "default";
}
}
get() {
return this.conf;
}
save(c) {
this.conf = { ...this.conf, ...(c || {}) };
this._persist();
}
_persist() {
GM_setValue(STORE_KEYS.CONF, this.conf);
}
// ========== 多 API 管理方法 ==========
getActiveApi() {
const active = this.conf.apiConfigs.find(a => a.id === this.conf.activeApiId && a.enabled);
if (active) return active;
// fallback: 返回第一个启用的
return this.conf.apiConfigs.find(a => a.enabled) || this.conf.apiConfigs[0] || DEFAULT_API_CONFIG;
}
getEnabledApis() {
return this.conf.apiConfigs.filter(a => a.enabled);
}
getApiById(id) {
return this.conf.apiConfigs.find(a => a.id === id);
}
setActiveApi(id) {
if (this.conf.apiConfigs.some(a => a.id === id)) {
this.conf.activeApiId = id;
this._persist();
}
}
addApi(api) {
const newApi = {
id: uid_api(),
name: api.name || "新 API",
baseUrl: api.baseUrl || DEFAULT_API_CONFIG.baseUrl,
model: api.model || DEFAULT_API_CONFIG.model,
apiKey: api.apiKey || "",
enabled: api.enabled !== false,
};
this.conf.apiConfigs.push(newApi);
this._persist();
return newApi;
}
updateApi(id, patch) {
const idx = this.conf.apiConfigs.findIndex(a => a.id === id);
if (idx >= 0) {
this.conf.apiConfigs[idx] = { ...this.conf.apiConfigs[idx], ...patch };
this._persist();
}
}
removeApi(id) {
const idx = this.conf.apiConfigs.findIndex(a => a.id === id);
if (idx >= 0 && this.conf.apiConfigs.length > 1) {
this.conf.apiConfigs.splice(idx, 1);
// 如果删除的是当前激活的,切换到第一个
if (this.conf.activeApiId === id) {
this.conf.activeApiId = this.conf.apiConfigs[0].id;
}
this._persist();
}
}
toggleApiEnabled(id) {
const api = this.getApiById(id);
if (api) {
api.enabled = !api.enabled;
this._persist();
}
}
}
/******************************************************************
* 2) 多会话存储(跨刷新)- 含会话数量限制和防抖优化
******************************************************************/
const MAX_SESSIONS = 50; // 最大会话数量限制
const PERSIST_DEBOUNCE_MS = 500; // 存储防抖延迟
class SessionStore {
constructor() {
this.sessions = GM_getValue(STORE_KEYS.SESS, []);
this.activeId = GM_getValue(STORE_KEYS.ACTIVE, null);
this._persistTimer = null;
if (!Array.isArray(this.sessions) || !this.sessions.length) {
const id = uid();
this.sessions = [this._newSessionObj(id, "新会话")];
this.activeId = id;
this._persistNow();
}
if (!this.sessions.some((s) => s.id === this.activeId)) {
this.activeId = this.sessions[0].id;
this._persistNow();
}
// 启动时清理超出限制的旧会话
this._cleanupOldSessions();
}
_newSessionObj(id, title) {
return {
id,
title: title || "新会话",
createdAt: now(),
updatedAt: now(),
fsm: { state: FSM.IDLE, step: 0, lastError: null, isRunning: false },
chat: [], // {role:'user'|'assistant', content, ts}
agent: [], // {role:'agent'|'tool', kind, content, ts}
draft: "", // === UI ENHANCE === 输入草稿持久化
};
}
all() {
return this.sessions;
}
active() {
return (
this.sessions.find((s) => s.id === this.activeId) || this.sessions[0]
);
}
setActive(id) {
this.activeId = id;
GM_setValue(STORE_KEYS.ACTIVE, id);
}
create(title = "新会话") {
const s = this._newSessionObj(uid(), title);
this.sessions.unshift(s);
this.activeId = s.id;
// 创建时清理超出限制的会话
this._cleanupOldSessions();
this._persistNow(); // 关键操作,立即保存
return s;
}
rename(id, title) {
const s = this.sessions.find((x) => x.id === id);
if (!s) return;
s.title =
String(title || "")
.trim()
.slice(0, 24) || "新会话";
s.updatedAt = now();
this._persistNow(); // 关键操作,立即保存
}
remove(id) {
const idx = this.sessions.findIndex((x) => x.id === id);
if (idx < 0) return;
this.sessions.splice(idx, 1);
if (!this.sessions.length) {
const s = this._newSessionObj(uid(), "新会话");
this.sessions = [s];
this.activeId = s.id;
} else if (this.activeId === id) {
this.activeId = this.sessions[0].id;
}
this._persistNow(); // 关键操作,立即保存
}
pushChat(id, msg) {
const s = this.sessions.find((x) => x.id === id);
if (!s) return;
s.chat.push(msg);
s.updatedAt = now();
this._persist();
}
pushAgent(id, msg) {
const s = this.sessions.find((x) => x.id === id);
if (!s) return;
s.agent.push(msg);
s.updatedAt = now();
this._persist();
}
setFSM(id, patch) {
const s = this.sessions.find((x) => x.id === id);
if (!s) return;
s.fsm = { ...(s.fsm || {}), ...(patch || {}) };
s.updatedAt = now();
this._persist();
}
updateLastAgent(id, predicateFn, updaterFn) {
const s = this.sessions.find((x) => x.id === id);
if (!s || !Array.isArray(s.agent)) return;
for (let i = s.agent.length - 1; i >= 0; i--) {
if (predicateFn(s.agent[i])) {
s.agent[i] = updaterFn(s.agent[i]) || s.agent[i];
s.updatedAt = now();
this._persist();
return;
}
}
}
clearSession(id) {
const s = this.sessions.find((x) => x.id === id);
if (!s) return;
s.chat = [];
s.agent = [];
s.draft = "";
s.fsm = { state: FSM.IDLE, step: 0, lastError: null, isRunning: false };
s.updatedAt = now();
this._persistNow(); // 关键操作,立即保存
}
setDraft(id, text) {
const s = this.sessions.find((x) => x.id === id);
if (!s) return;
s.draft = String(text ?? "");
s.updatedAt = now();
this._persist();
}
// 清理超出限制的旧会话
_cleanupOldSessions() {
if (this.sessions.length > MAX_SESSIONS) {
// 按更新时间排序,保留最新的
this.sessions.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
const removed = this.sessions.splice(MAX_SESSIONS);
// 如果当前激活的会话被删除,重置
if (removed.some(s => s.id === this.activeId)) {
this.activeId = this.sessions[0]?.id;
}
console.log(`[Linux.do Agent] 清理了 ${removed.length} 个旧会话`);
}
}
// 防抖存储(减少频繁写入)
_persist() {
if (this._persistTimer) clearTimeout(this._persistTimer);
this._persistTimer = setTimeout(() => this._persistNow(), PERSIST_DEBOUNCE_MS);
}
// 立即存储(用于关键操作)
_persistNow() {
if (this._persistTimer) clearTimeout(this._persistTimer);
this._persistTimer = null;
GM_setValue(STORE_KEYS.SESS, this.sessions);
GM_setValue(STORE_KEYS.ACTIVE, this.activeId);
}
}
/******************************************************************
* 3) Discourse 工具(linux.do 标准 JSON 接口)
******************************************************************/
class DiscourseAPI {
static headers() {
return {
"X-Requested-With": "XMLHttpRequest",
Accept: "application/json",
};
}
static csrfToken() {
return (
document
.querySelector('meta[name="csrf-token"]')
?.getAttribute("content") || ""
);
}
static async fetchJson(path, opt = {}) {
const { method = "GET", body = null, headers = {}, signal } = opt;
const init = {
method,
credentials: "same-origin",
headers: { ...this.headers(), ...(headers || {}) },
signal,
};
if (body != null) {
init.headers["Content-Type"] = "application/json";
init.headers["X-CSRF-Token"] = this.csrfToken();
init.body = JSON.stringify(body);
}
const res = await fetch(path, init);
if (!res.ok) throw new Error(`HTTP ${res.status}: ${path}`);
return res.json();
}
static topicUrl(topicId, postNo = 1) {
return `${location.origin}/t/${encodeURIComponent(topicId)}/${postNo}`;
}
static userUrl(username) {
return `${location.origin}/u/${encodeURIComponent(username)}`;
}
static async search({ q, page = 1, limit = 8 }, signal) {
const params = new URLSearchParams();
params.set("q", q);
params.set("page", String(page));
params.set("include_blurbs", "true");
params.set("skip_context", "true");
const data = await this.fetchJson(`/search.json?${params.toString()}`, {
signal,
});
const topicsMap = new Map(
(data.topics || []).map((t) => [
t.id,
safeTitle(t.fancy_title || t.title, `话题 ${t.id}`),
])
);
const posts = (data.posts || []).slice(0, limit).map((p) => ({
topic_id: p.topic_id,
post_number: p.post_number,
title: topicsMap.get(p.topic_id) || `话题 ${p.topic_id}`,
username: p.username,
created_at: p.created_at,
blurb: p.blurb || "",
url: this.topicUrl(p.topic_id, p.post_number),
}));
return { q, page, posts };
}
static async getTopicAllPosts(
{ topicId, batchSize = 18, maxPosts = 240 },
signal,
cancelToken
) {
const first = await this.fetchJson(
`/t/${encodeURIComponent(topicId)}.json`,
{ signal }
);
const title = safeTitle(first.title, `话题 ${topicId}`);
const stream = (first.post_stream?.stream || []).slice(0, maxPosts);
const got = new Map();
for (const p of first.post_stream?.posts || []) got.set(p.id, p);
for (let i = 0; i < stream.length; i += batchSize) {
if (cancelToken?.cancelled) throw new Error("Cancelled");
const chunk = stream.slice(i, i + batchSize);
const params = new URLSearchParams();
chunk.forEach((id) => params.append("post_ids[]", String(id)));
const data = await this.fetchJson(
`/t/${encodeURIComponent(topicId)}/posts.json?${params.toString()}`,
{ signal }
);
for (const p of data.post_stream?.posts || []) got.set(p.id, p);
await sleep(160);
}
const posts = stream
.map((id) => got.get(id))
.filter(Boolean)
.map((p) => ({
id: p.id,
post_number: p.post_number,
username: p.username,
created_at: p.created_at,
cooked: p.cooked || "",
url: this.topicUrl(topicId, p.post_number),
like_count: p.like_count,
reply_count: p.reply_count,
}));
return { topicId, title, count: posts.length, posts };
}
static async getUserRecent({ username, limit = 10 }, signal) {
const params = new URLSearchParams();
params.set("offset", "0");
params.set("limit", String(limit));
params.set("username", username);
params.set("filter", "4,5");
const data = await this.fetchJson(
`/user_actions.json?${params.toString()}`,
{ signal }
);
const items = (data.user_actions || []).map((a) => ({
action_type: a.action_type,
title: safeTitle(a.title, `话题 ${a.topic_id}`),
topic_id: a.topic_id,
post_number: a.post_number,
created_at: a.created_at,
excerpt: a.excerpt || "",
url: this.topicUrl(a.topic_id, a.post_number),
}));
return { username, items };
}
static async getCategories(signal) {
return this.fetchJson("/categories.json", { signal });
}
static async listLatestTopics({ page = 0 } = {}, signal) {
const params = new URLSearchParams();
params.set("page", String(page));
params.set("no_definitions", "true");
return this.fetchJson(`/latest.json?${params.toString()}`, { signal });
}
static async listTopTopics({ period = "weekly", page = 0 } = {}, signal) {
const params = new URLSearchParams();
params.set("period", String(period));
params.set("page", String(page));
params.set("no_definitions", "true");
return this.fetchJson(`/top.json?${params.toString()}`, { signal });
}
static async getTagTopics({ tag, page = 0 } = {}, signal) {
if (!tag) throw new Error("tag 不能为空");
const params = new URLSearchParams();
params.set("page", String(page));
params.set("no_definitions", "true");
return this.fetchJson(
`/tag/${encodeURIComponent(tag)}.json?${params.toString()}`,
{ signal }
);
}
static async listLatestPosts({ before = null, limit = 20 } = {}, signal) {
const params = new URLSearchParams();
if (before !== null && before !== undefined && before !== "")
params.set("before", String(before));
params.set(
"limit",
String(Math.max(1, Math.min(50, parseInt(limit, 10) || 20)))
);
params.set("no_definitions", "true");
let data;
try {
data = await this.fetchJson(`/posts.json?${params.toString()}`, {
signal,
});
} catch (e1) {
throw new Error(
`获取失败:/posts.json 不可用或被限制。${String(e1?.message || e1)}`
);
}
const arr = Array.isArray(data?.latest_posts)
? data.latest_posts
: Array.isArray(data)
? data
: [];
const posts = arr
.slice(0, Math.max(1, Math.min(50, parseInt(limit, 10) || 20)))
.map((p) => {
const topic_id = p.topic_id;
const post_number = p.post_number || p.post_number;
return {
id: p.id,
topic_id,
post_number,
username: p.username,
created_at: p.created_at,
cooked: p.cooked || "",
raw: p.raw || "",
like_count: p.like_count,
url:
topic_id && post_number
? this.topicUrl(topic_id, post_number)
: "",
};
});
return { before: before ?? null, returned: posts.length, posts };
}
static async getUserSummary({ username } = {}, signal) {
if (!username) throw new Error("username 不能为空");
const out = {
username,
urls: {
profile: this.userUrl(username),
summary: `${this.userUrl(username)}/summary`,
},
profile: null,
summary: null,
badges: null,
hot_topics: [],
hot_posts: [],
recent_topics: [],
recent_posts: [],
_raw: {
summary_json: null,
profile_json: null,
activity_topics_json: null,
activity_posts_json: null,
},
};
let summaryJson = null;
try {
summaryJson = await this.fetchJson(
`/u/${encodeURIComponent(username)}/summary.json`,
{ signal }
);
out._raw.summary_json = summaryJson;
} catch (e) {
throw new Error(`获取 summary.json 失败:${String(e?.message || e)}`);
}
try {
const profileJson = await this.fetchJson(
`/u/${encodeURIComponent(username)}.json`,
{ signal }
);
out._raw.profile_json = profileJson;
} catch { }
try {
const params = new URLSearchParams();
params.set("page", "0");
params.set("no_definitions", "true");
const topicsJson = await this.fetchJson(
`/u/${encodeURIComponent(
username
)}/activity/topics.json?${params.toString()}`,
{ signal }
);
out._raw.activity_topics_json = topicsJson;
} catch { }
try {
const params = new URLSearchParams();
params.set("page", "0");
params.set("no_definitions", "true");
const postsJson = await this.fetchJson(
`/u/${encodeURIComponent(
username
)}/activity/posts.json?${params.toString()}`,
{ signal }
);
out._raw.activity_posts_json = postsJson;
} catch { }
const profileUser =
out._raw.profile_json?.user || summaryJson?.user || null;
if (profileUser) {
out.profile = {
id: profileUser.id,
username: profileUser.username,
name: profileUser.name ?? "",
title: profileUser.title ?? "",
trust_level: profileUser.trust_level,
avatar_template: profileUser.avatar_template,
created_at: profileUser.created_at,
last_seen_at: profileUser.last_seen_at,
last_posted_at: profileUser.last_posted_at,
badge_count: profileUser.badge_count,
website: profileUser.website,
website_name: profileUser.website_name,
profile_view_count: profileUser.profile_view_count,
time_read: profileUser.time_read,
recent_time_read: profileUser.recent_time_read,
user_fields: profileUser.user_fields || {},
};
}
const us = summaryJson?.user_summary || summaryJson?.userSummary || null;
if (us) {
out.summary = {
topic_count: us.topic_count,
reply_count: us.reply_count,
likes_given: us.likes_given,
likes_received: us.likes_received,
days_visited: us.days_visited,
posts_read_count: us.posts_read_count,
time_read: us.time_read,
};
}
out.badges = {
user_badges:
summaryJson?.user_badges || summaryJson?.userBadges || null,
badges: summaryJson?.badges || null,
badge_types: summaryJson?.badge_types || null,
users: summaryJson?.users || null,
};
const topTopics = Array.isArray(summaryJson?.top_topics)
? summaryJson.top_topics
: Array.isArray(summaryJson?.topTopics)
? summaryJson.topTopics
: [];
const topReplies = Array.isArray(summaryJson?.top_replies)
? summaryJson.top_replies
: Array.isArray(summaryJson?.topReplies)
? summaryJson.topReplies
: [];
out.hot_topics = topTopics
.map((t) => ({
topic_id: t.id || t.topic_id || t.topicId,
title: safeTitle(
t.fancy_title || t.title,
`话题 ${t.id || t.topic_id || ""}`
),
like_count: t.like_count,
views: t.views,
reply_count: t.reply_count ?? t.posts_count,
last_posted_at: t.last_posted_at ?? t.bumped_at,
category_id: t.category_id,
tags: t.tags || [],
url: this.topicUrl(t.id || t.topic_id || t.topicId, 1),
}))
.filter((x) => x.topic_id);
out.hot_posts = topReplies
.map((p) => ({
topic_id: p.topic_id,
post_number: p.post_number,
post_id: p.id,
title: safeTitle(p.topic_title || p.title, `话题 ${p.topic_id}`),
like_count: p.like_count,
created_at: p.created_at,
excerpt: p.excerpt || "",
username: p.username,
url: this.topicUrl(p.topic_id, p.post_number || 1),
}))
.filter((x) => x.topic_id);
const actTopics =
out._raw.activity_topics_json?.topic_list?.topics ||
out._raw.activity_topics_json?.topics ||
[];
if (Array.isArray(actTopics) && actTopics.length) {
const extra = actTopics.map((t) => ({
topic_id: t.id,
title: safeTitle(t.fancy_title || t.title, `话题 ${t.id}`),
like_count: t.like_count,
views: t.views,
reply_count:
t.reply_count ??
(t.posts_count ? Math.max(0, t.posts_count - 1) : undefined),
last_posted_at: t.last_posted_at ?? t.bumped_at,
category_id: t.category_id,
tags: t.tags || [],
url: this.topicUrl(t.id, 1),
_score:
(t.like_count || 0) * 4 +
(t.views || 0) * 0.01 +
(t.reply_count || 0) * 2,
}));
out.recent_topics = extra
.slice(0, 12)
.map(({ _score, ...rest }) => rest);
const exist = new Set(out.hot_topics.map((x) => x.topic_id));
extra.sort((a, b) => b._score - a._score);
for (const t of extra) {
if (out.hot_topics.length >= 10) break;
if (!exist.has(t.topic_id)) {
exist.add(t.topic_id);
const { _score, ...rest } = t;
out.hot_topics.push(rest);
}
}
}
const actPosts =
out._raw.activity_posts_json?.user_actions ||
out._raw.activity_posts_json?.posts ||
out._raw.activity_posts_json?.activity_stream ||
[];
if (Array.isArray(actPosts) && actPosts.length) {
const normPosts = actPosts
.map((a) => {
const topic_id = a.topic_id || a?.post?.topic_id;
const post_number = a.post_number || a?.post?.post_number;
const like_count = a.like_count ?? a?.post?.like_count;
const excerpt = a.excerpt || a?.post?.excerpt || "";
const created_at = a.created_at || a?.post?.created_at;
const username2 = a.username || a?.post?.username || username;
const title = safeTitle(
a.title || a.topic_title || a?.post?.topic_title,
topic_id ? `话题 ${topic_id}` : "帖子"
);
return {
topic_id,
post_number,
post_id: a.post_id || a.id || a?.post?.id,
title,
like_count,
created_at,
excerpt,
username: username2,
url:
topic_id && post_number
? this.topicUrl(topic_id, post_number)
: "",
};
})
.filter((x) => x.topic_id && x.post_number);
out.recent_posts = normPosts.slice(0, 12);
const existPostKey = new Set(
out.hot_posts.map((x) => `${x.topic_id}#${x.post_number}`)
);
const scored = normPosts.map((p) => ({
...p,
_score:
(p.like_count || 0) * 5 +
(p.excerpt ? Math.min(1, p.excerpt.length / 120) : 0),
}));
scored.sort((a, b) => b._score - a._score);
for (const p of scored) {
if (out.hot_posts.length >= 10) break;
const k = `${p.topic_id}#${p.post_number}`;
if (!existPostKey.has(k)) {
existPostKey.add(k);
const { _score, ...rest } = p;
out.hot_posts.push(rest);
}
}
}
out.hot_topics = out.hot_topics.slice(0, 10);
out.hot_posts = out.hot_posts.slice(0, 10);
out.recent_topics = out.recent_topics.slice(0, 12);
out.recent_posts = out.recent_posts.slice(0, 12);
return out;
}
static async getPost({ postId } = {}, signal) {
if (!postId) throw new Error("postId 不能为空");
return this.fetchJson(`/posts/${encodeURIComponent(postId)}.json`, {
signal,
});
}
static async getTopicPostFull(
{ topicId, postNumber = 1, maxChars = 10000 } = {},
signal
) {
if (topicId === undefined || topicId === null || topicId === "")