@ssamurias/dsh-fish 1.0.7 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/AGENTS.md +32 -3
  2. package/CHANGELOG.md +4366 -4265
  3. package/README.md +243 -627
  4. package/RELEASE-NOTES-1.0.8.md +81 -0
  5. package/RELEASE-NOTES-1.0.9.md +79 -0
  6. package/THIRD-PARTY-NOTICES.md +1 -1
  7. package/docs/troubleshooting.md +79 -1
  8. package/docs//350/256/244/344/272/272/345/210/244/346/215/256.md +112 -0
  9. package/lib/appoint.js +106 -22
  10. package/lib/ask.js +8 -3
  11. package/lib/at.js +16 -1
  12. package/lib/capture.js +51 -1
  13. package/lib/claim.js +103 -0
  14. package/lib/client/00-shell.js +500 -0
  15. package/lib/client/01-state-load.js +860 -0
  16. package/lib/client/02-actions.js +670 -0
  17. package/lib/client/03-widgets-header.js +721 -0
  18. package/lib/client/04-pressure-lab.js +891 -0
  19. package/lib/client/05-pressure-charts.js +431 -0
  20. package/lib/client/06-tab-status-grow.js +468 -0
  21. package/lib/client/07-tab-home-bili.js +542 -0
  22. package/lib/client/08-tab-memory-plugins.js +733 -0
  23. package/lib/client/09-tab-outing.js +710 -0
  24. package/lib/client/10-data-handlers.js +519 -0
  25. package/lib/client/11-tab-data-frame.js +661 -0
  26. package/lib/client/12-pressure-chip-mount.js +565 -0
  27. package/lib/client.js +109 -24
  28. package/lib/comment.js +18 -3
  29. package/lib/cue.js +102 -5
  30. package/lib/deliver.js +3 -1
  31. package/lib/derive.js +308 -41
  32. package/lib/doing.js +31 -15
  33. package/lib/drive.js +3 -5
  34. package/lib/env.d.ts +224 -0
  35. package/lib/health.js +56 -0
  36. package/lib/hear.js +70 -0
  37. package/lib/home.js +48 -20
  38. package/lib/identity.js +25 -2
  39. package/lib/index.js +32 -18
  40. package/lib/look.js +2 -1
  41. package/lib/loops.js +39 -0
  42. package/lib/make.js +60 -12
  43. package/lib/markup.js +77 -1
  44. package/lib/match.js +262 -0
  45. package/lib/observe-bili.js +331 -0
  46. package/lib/observe-config.js +223 -0
  47. package/lib/observe-data.js +522 -0
  48. package/lib/observe-home.js +383 -0
  49. package/lib/observe-http.js +250 -0
  50. package/lib/observe-outing.js +650 -0
  51. package/lib/observe-state.js +419 -0
  52. package/lib/observe-trip.js +286 -0
  53. package/lib/observe.js +99 -3574
  54. package/lib/persona.js +187 -40
  55. package/lib/proactive.js +48 -47
  56. package/lib/pronounask.js +15 -1
  57. package/lib/restrict.js +146 -9
  58. package/lib/say.js +68 -4
  59. package/lib/scheduler.js +63 -25
  60. package/lib/schema.js +57 -4
  61. package/lib/scrub.js +16 -1
  62. package/lib/settings.js +128 -12
  63. package/lib/stance.js +131 -19
  64. package/lib/status.js +14 -5
  65. package/lib/store.js +24 -2
  66. package/lib/sub.js +7 -1
  67. package/lib/talkmem.js +12 -8
  68. package/lib/transcript.js +205 -0
  69. package/lib/turns.js +147 -19
  70. package/lib/types.d.ts +513 -0
  71. package/lib/voices.js +26 -1
  72. package/lib/wiki.js +47 -13
  73. package/lib/works.js +200 -49
  74. package/media/banner.jpg +0 -0
  75. package/package.json +1 -1
  76. package/scripts/build-client.mjs +83 -0
  77. package/scripts/sync-pressure-formulas.mjs +12 -15
package/lib/match.js ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * match.js —— 新材料碰上她手上还悬着的事(1.0.8,C)
3
+ *
4
+ * 1.0.7 把「悬着的事」收成了一张清单(loops.js),但那张清单只在好奇/便条/约定
5
+ * 各自的地方用;新材料进来(她读到的一段话、他新说的一句)不会自动去碰它。
6
+ * 这一层就是那个「便宜的后台」:纯字符串比对,不调模型、不花 token,只在真碰上
7
+ * 的时候留一行给她下一轮看。
8
+ *
9
+ * 设计边界:
10
+ * - 只比对「最近还悬着的」(openLoops,最多 20 条)和「最近 48 小时的新材料」;
11
+ * - 阈值:共享二字组 ≥ 3 且覆盖到那件事的一半以上,宁缺勿滥;
12
+ * - 只在两个当轮入口比对:他开口那一轮(cue.js 的 flashFor)、她读到材料那一刻
13
+ * (materialFlash,附在工具结果末尾);不另开一轮,也不事后补摆(用户 m02704);
14
+ * - 一天最多摆 `config.match.dayMax` 次,同一对冷却 `cooldownDays` 天(D);
15
+ * - 只摆原话,不解释为什么像、不给分数、不催她去看(黑名单:不读自身数值)。
16
+ */
17
+
18
+ import { appendEvent } from './store.js'
19
+ import { logLine } from './log.js'
20
+ import { dateKey, configCache } from './settings.js'
21
+
22
+ /** 只碰最近两天的材料。更老的,她自己有 her_recall。 */
23
+ export const MATCH_WINDOW_MS = 48 * 60 * 60_000
24
+ /**
25
+ * 同一件事 × 同一份材料,隔几天才允许再摆一次(`config.match.cooldownDays`)。
26
+ * 默认 3 天;0 = 不冷却;上限 14 天。没有独立的设置项——这个数只有看得懂
27
+ * 「一件事被一份材料碰到之后隔多久再提」的人才会去改,放进设置页反而误导。
28
+ */
29
+ export const MATCH_COOLDOWN_DAYS = 3
30
+ export const MATCH_COOLDOWN_MAX_DAYS = 14
31
+ export function cooldownDays() {
32
+ const raw = configCache()?.match?.cooldownDays
33
+ if (raw === undefined || raw === null || raw === '') return MATCH_COOLDOWN_DAYS
34
+ const n = Math.round(Number(raw))
35
+ if (!Number.isFinite(n)) return MATCH_COOLDOWN_DAYS
36
+ return Math.max(0, Math.min(MATCH_COOLDOWN_MAX_DAYS, n))
37
+ }
38
+
39
+ /**
40
+ * 一天最多摆几次(`config.match.dayMax`,默认 2,0 不设上限? —— 不,最少 1)。
41
+ * 用户 m02704:E 一开,一天撞上三五件事就可能连着摆,那会变成骚扰,所以给个日上限。
42
+ * 代码级配置,不放进设置页(和冷却天数同一个理由)。
43
+ */
44
+ export const MATCH_DAY_MAX = 2
45
+ export const MATCH_DAY_MAX_MAX = 5
46
+ export function dayMax() {
47
+ const raw = configCache()?.match?.dayMax
48
+ if (raw === undefined || raw === null || raw === '') return MATCH_DAY_MAX
49
+ const n = Math.round(Number(raw))
50
+ if (!Number.isFinite(n)) return MATCH_DAY_MAX
51
+ return Math.max(1, Math.min(MATCH_DAY_MAX_MAX, n))
52
+ }
53
+
54
+ let shown = { dk: '', n: 0 }
55
+ let blockedCache = { root: '', set: new Set(), at: 0 }
56
+
57
+ /** 轮次结账时把「今天摆了几次」和「哪些对还在冷却」一次性读进内存。 */
58
+ export function seedMatch({ root = '', events = [], now = Date.now() } = {}) {
59
+ const dk = dateKey(new Date(now))
60
+ shown = { dk, n: matchesOn(events, dk) }
61
+ blockedCache = { root: String(root ?? ''), set: blockedFrom(events, now), at: now }
62
+ }
63
+
64
+ export function shownToday(now = Date.now()) {
65
+ const dk = dateKey(new Date(now))
66
+ if (shown.dk !== dk) shown = { dk, n: 0 }
67
+ return shown.n
68
+ }
69
+
70
+ export function canShowMore(now = Date.now()) {
71
+ return shownToday(now) < dayMax()
72
+ }
73
+
74
+ /** 同步取一份冷却集合;换了屋子或太旧就当没有。 */
75
+ export function blockedCached(root = '', now = Date.now()) {
76
+ if (String(root ?? '') !== blockedCache.root) return new Set()
77
+ if (now - blockedCache.at > MATCH_WINDOW_MS) return new Set()
78
+ return blockedCache.set
79
+ }
80
+
81
+ /** 一句话 × 还悬着的事:人开口那一轮用这个(同步)。 */
82
+ export function pickForText({ text = '', loops = [], blocked = new Set(), now = Date.now() } = {}) {
83
+ const t = String(text ?? '').trim()
84
+ if (!t) return null
85
+ return pickMatch({
86
+ loops,
87
+ materials: [{ id: `turn:${hashOf(t)}`, text: t, at: now }],
88
+ now,
89
+ blocked,
90
+ })
91
+ }
92
+
93
+ /**
94
+ * 真摆出去之后记账:写 `cmatch:`、加今天那一次、把这一对放进冷却。
95
+ * 用户 m02704:「算她看到过」——冷却和每日计数按「摆过」记,避免同一段材料每轮重复附。
96
+ */
97
+ export async function recordShown({ root, best, now = Date.now() } = {}) {
98
+ if (!root || !best?.key) return false
99
+ try {
100
+ await appendEvent(
101
+ { type: 'meta', text: `cmatch:${new Date(now).toISOString()} ${best.key} ${best.materialId}` },
102
+ { source: 'system' },
103
+ root,
104
+ )
105
+ } catch { /* 记不下也不挡这一行 */ }
106
+ const today = shownToday(now) + 1
107
+ shown = { dk: dateKey(new Date(now)), n: today }
108
+ // 先把这间屋子认下来:materialFlash 第一次记录时 blockedCache.root 还是空的,
109
+ // 不认的话下一次取冷却集合会当成「换了屋子」,同一对会再附一次。
110
+ blockedCache.root = String(root)
111
+ blockedCache.at = now
112
+ blockedCache.set.add(`${best.key}\u0000${best.materialId}`)
113
+ try {
114
+ const dk = dateKey(new Date(now))
115
+ if (today === 1) logLine('info', ['match', 'day', dk, 'hits=1'], root)
116
+ logLine(
117
+ 'info',
118
+ ['match', 'hit', `kind=${best.kind}`, `score=${best.score.toFixed(2)}`, `material=${best.materialId}`, `today=${today}`],
119
+ root,
120
+ )
121
+ } catch { /* 日志挂了不挡 match */ }
122
+ return true
123
+ }
124
+
125
+ /** 测试用:清掉内存里的计数与冷却。 */
126
+ export function resetMatchState() {
127
+ shown = { dk: '', n: 0 }
128
+ blockedCache = { root: '', set: new Set(), at: 0 }
129
+ }
130
+
131
+ /** 摆出去的一行最多这么长(码点)。 */
132
+ export const MATCH_TEXT_MAX = 60
133
+ /** 至少共享三个有信息量的二字组。 */
134
+ export const MATCH_MIN_SHARED = 3
135
+ /** 共享词要覆盖到那件事的一半,光撞一个常见词不算。 */
136
+ export const MATCH_MIN_RATIO = 0.4
137
+
138
+ const STOP_BI = new Set([
139
+ '什么', '不是', '可以', '我们', '你们', '他们', '这个', '那个', '时候',
140
+ '知道', '觉得', '一个', '没有', '就是', '还是', '因为', '所以', '但是',
141
+ '如果', '真的', '自己', '事情', '东西', '现在', '已经', '一点', '有点',
142
+ '怎么', '这样', '那样', '可能', '应该', '需要', '喜欢', '不要', '不会',
143
+ ])
144
+
145
+ function bigrams(s) {
146
+ const chars = [...String(s ?? '').replace(/[^\u4e00-\u9fffA-Za-z0-9]/g, '')]
147
+ const out = new Set()
148
+ for (let i = 0; i + 1 < chars.length; i++) {
149
+ const g = chars[i] + chars[i + 1]
150
+ if (!STOP_BI.has(g)) out.add(g)
151
+ }
152
+ return out
153
+ }
154
+
155
+ function clipText(s, n = MATCH_TEXT_MAX) {
156
+ const t = String(s ?? '').replace(/\s+/g, ' ').trim()
157
+ return [...t].length > n ? `${[...t].slice(0, n).join('')}…` : t
158
+ }
159
+
160
+ function msOf(v, fallback) {
161
+ if (typeof v === 'number' && Number.isFinite(v)) return v
162
+ const t = Date.parse(String(v ?? ''))
163
+ return Number.isFinite(t) ? t : fallback
164
+ }
165
+
166
+ /** 稳定的小哈希,只用来给冷却记录当键。 */
167
+ function hashOf(s) {
168
+ let h = 5381
169
+ for (const ch of String(s ?? '')) h = ((h * 33) ^ ch.codePointAt(0)) >>> 0
170
+ return h.toString(36)
171
+ }
172
+
173
+ /**
174
+ * 纯函数:一件事的文字和一份材料碰得多紧。
175
+ * @returns {{ score: number, shared: number }|null}
176
+ */
177
+ export function matchScore(loopText, materialText) {
178
+ const a = bigrams(loopText)
179
+ if (a.size < MATCH_MIN_SHARED) return null
180
+ const b = bigrams(materialText)
181
+ if (!b.size) return null
182
+ let shared = 0
183
+ for (const g of a) if (b.has(g)) shared++
184
+ if (shared < MATCH_MIN_SHARED) return null
185
+ const ratio = shared / a.size
186
+ if (ratio < MATCH_MIN_RATIO) return null
187
+ return { score: ratio, shared }
188
+ }
189
+
190
+ /**
191
+ * 从清单和材料里挑一条最该摆的。纯函数,便于单测。
192
+ * @returns {{ kind: string, id: string, loop: string, materialId: string, material: string, at: number, score: number }|null}
193
+ */
194
+ export function pickMatch({ loops = [], materials = [], now = Date.now(), blocked = new Set() } = {}) {
195
+ let best = null
196
+ for (const loop of loops) {
197
+ const text = String(loop?.text ?? '').trim()
198
+ if (!text) continue
199
+ const key = `${loop?.kind ?? ''}\u0000${hashOf(text)}`
200
+ for (const m of materials) {
201
+ const mt = String(m?.text ?? '').trim()
202
+ if (!mt) continue
203
+ if (blocked.has(`${key}\u0000${m?.id ?? ''}`)) continue
204
+ const hit = matchScore(text, mt)
205
+ if (!hit) continue
206
+ const cand = {
207
+ kind: String(loop?.kind ?? ''),
208
+ id: String(loop?.id ?? ''),
209
+ loop: clipText(text),
210
+ materialId: String(m?.id ?? ''),
211
+ material: clipText(mt),
212
+ at: msOf(m?.at, now),
213
+ score: hit.score,
214
+ key,
215
+ }
216
+ if (!best) { best = cand; continue }
217
+ if (cand.score > best.score) best = cand
218
+ else if (cand.score === best.score && cand.at > best.at) best = cand
219
+ }
220
+ }
221
+ return best
222
+ }
223
+
224
+ /** 冷却记录:近 14 天的 `cmatch:`,同一对不再摆(冷却天数见 `cooldownDays()`)。 */
225
+ function blockedFrom(events, now) {
226
+ const blocked = new Set()
227
+ const ms = cooldownDays() * 24 * 60 * 60_000
228
+ if (ms <= 0) return blocked
229
+ for (const e of events ?? []) {
230
+ const t = String(e?.text ?? '')
231
+ if (e?.type !== 'meta' || !t.startsWith('cmatch:')) continue
232
+ const parts = t.split(/\s+/)
233
+ if (parts.length < 3) continue
234
+ const at = Date.parse(parts[0].slice('cmatch:'.length))
235
+ if (!(now - at <= 14 * 24 * 60 * 60_000)) continue
236
+ if (now - at < ms) blocked.add(`${parts[1]}\u0000${parts[2]}`)
237
+ }
238
+ return blocked
239
+ }
240
+
241
+ /** 最近的、像「材料」的东西:她读到的和他说的。 */
242
+ export function materialsOf(events = [], { now = Date.now() } = {}) {
243
+ return (events ?? [])
244
+ .filter((e) => (e?.type === 'voice' || e?.type === 'heard') && e?.text)
245
+ .map((e) => ({ id: String(e.id ?? ''), text: String(e.text), at: msOf(e.at, now) }))
246
+ .filter((m) => m.id && [...String(m.text).trim()].length >= 8 && now - m.at <= MATCH_WINDOW_MS)
247
+ .sort((a, b) => b.at - a.at)
248
+ .slice(0, 80)
249
+ }
250
+
251
+ /** 诊断用:今天命中了几次(只读 `cmatch:`,给 H 的每日计数)。 */
252
+ export function matchesOn(events = [], dk = dateKey(new Date())) {
253
+ let n = 0
254
+ for (const e of events ?? []) {
255
+ if (e?.type !== 'meta') continue
256
+ const t = String(e.text ?? '')
257
+ if (!t.startsWith('cmatch:')) continue
258
+ const at = Date.parse(t.split(/\s+/)[0].slice('cmatch:'.length))
259
+ if (dateKey(new Date(at)) === dk) n++
260
+ }
261
+ return n
262
+ }
@@ -0,0 +1,331 @@
1
+ // @ts-check
2
+ /**
3
+ * observe-bili.js —— 观测台 B 站登录、扫码、刷站、历史、封面、风控与评论/@ 路由
4
+ *
5
+ * 路由:
6
+ * /owner · /bili/state · /bili/qr · /browse-review · /browse · /history
7
+ * /away · /cover · /risk · /comment · /at
8
+ */
9
+
10
+ import fs from 'node:fs'
11
+ import { readEvents, readOwner } from './store.js'
12
+ import { loadConfig, updateConfig, dateKey, biliOn } from './settings.js'
13
+ import { deriveSelf } from './derive.js'
14
+ import { quietBrowse, reviewNow } from './scheduler.js'
15
+ import { itemsFromEvents, browseCountToday, parseBrowseLine } from './browse.js'
16
+ import { seenOn } from './whatseen.js'
17
+ import { readAway } from './away.js'
18
+ import { coverPath, fetchCover } from './cover.js'
19
+ import { memoryCooldown, createClient } from './bili.js'
20
+ import { commentCountToday, replyCountToday, herComments, scanReplies } from './comment.js'
21
+ import { repliedToOthers, mentionsToday } from './at.js'
22
+ import { QR_TTL_MS } from './biliqr.js'
23
+ import { publicOwner, saveOwner, saveAccount } from './owner.js'
24
+ import { historyFromEvents } from './history.js'
25
+ import { riskState, clearRisk } from './risk.js'
26
+ import { logLine } from './log.js'
27
+ import { send, sentTooLarge, readBody } from './observe-http.js'
28
+
29
+ /**
30
+ * 引导文案:别人第一次装,本机没有现成 cookie。
31
+ */
32
+ export const COOKIE_HINT = [
33
+ '在你的浏览器里登录 B 站 → 按 F12 → Application(应用)→ Cookies → https://www.bilibili.com',
34
+ '找到 SESSDATA 和 bili_jct 这两行,把它们的值复制下来。',
35
+ '粘成一行:SESSDATA=...; bili_jct=...',
36
+ '(也可以在 Network 里随便点一个请求,直接复制整条 Cookie 请求头贴进来。)',
37
+ ].join('\n')
38
+
39
+ /**
40
+ * 封面图懒下载:设置页的 <img> 引到这条路由,第一次才真去取,之后命中缓存。
41
+ *
42
+ * @param {string} root
43
+ * @param {string} bvid
44
+ * @returns {Promise<string>}
45
+ */
46
+ export async function lazyCover(root, bvid) {
47
+ try {
48
+ const { events } = await readEvents(root)
49
+ let pic = ''
50
+ for (const e of events) {
51
+ const got = parseBrowseLine(e?.text)
52
+ if (!got) continue
53
+ const hit = got.arr.find((it) => it?.bvid === bvid && it?.pic)
54
+ if (hit) pic = String(hit.pic)
55
+ }
56
+ if (!pic) {
57
+ const ow = await readOwner(root)
58
+ const client = createClient({ cookie: ow?.cookie || '' })
59
+ const v = /** @type {any} */ (await client.view(bvid))
60
+ pic = v?.data?.pic || v?.pic || ''
61
+ }
62
+ if (!pic) return ''
63
+ return await fetchCover(/** @type {any} */ ({ root, bvid, pic }))
64
+ } catch {
65
+ return ''
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @param {import('./types.js').ObserveEnv} env
71
+ * @returns {import('./types.js').ObserveRouteEntry[]}
72
+ */
73
+ export function buildBiliRoutes(env) {
74
+ const { ctx, root, qrLogin } = env
75
+
76
+ return [
77
+ ['/owner', async (req, res) => {
78
+ if (req.method === 'GET') {
79
+ const ow = await readOwner(root)
80
+ const { config } = await loadConfig(root)
81
+ return send(res, 200, {
82
+ ...publicOwner(ow),
83
+ atOwner: config?.comment?.atOwner !== false,
84
+ hint: COOKIE_HINT,
85
+ qrTtlMs: QR_TTL_MS,
86
+ })
87
+ }
88
+ if (req.method === 'POST' || req.method === 'PUT') {
89
+ const raw = await readBody(req)
90
+ let body
91
+ try { body = JSON.parse(raw || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
92
+ if (body.test) {
93
+ const ow = await readOwner(root)
94
+ if (!ow?.cookie) return send(res, 200, { ok: false, note: '还没存 cookie。' })
95
+ try {
96
+ const c = createClient({ cookie: ow.cookie })
97
+ const me = await c.me()
98
+ if (!me?.isLogin) return send(res, 200, { ok: false, note: '这个 cookie 登不上,可能过期了。' })
99
+ const owner = await saveAccount(me, root)
100
+ return send(res, 200, { ok: true, note: `登上了:${me.uname}(uid ${me.mid})`, mid: String(me.mid), name: String(me.uname), account: owner.account, canWrite: Boolean(me.canWrite) })
101
+ } catch (err) {
102
+ const msg = String(/** @type {any} */ (err)?.message ?? err)
103
+ logLine('warn', ['登录态:拿这份 cookie 连不上 B 站', msg.slice(0, 160)], root)
104
+ return send(res, 200, { ok: false, note: `连不上:${msg.slice(0, 60)}` })
105
+ }
106
+ }
107
+ if (body.atOwner !== undefined) {
108
+ await updateConfig({ comment: { atOwner: Boolean(body.atOwner) } }, root)
109
+ }
110
+ /** @type {Record<string, unknown>} */
111
+ const patch = {}
112
+ if (body.mid !== undefined) patch.mid = body.mid
113
+ if (body.nickname !== undefined) patch.nickname = body.nickname
114
+ if (body.cookie !== undefined) patch.cookie = body.cookie
115
+ const r = /** @type {any} */ (Object.keys(patch).length ? await saveOwner(patch, root) : { ok: true, note: '存下了。', owner: publicOwner(await readOwner(root)) })
116
+ if (r.ok && patch.cookie) {
117
+ try {
118
+ const probe = createClient({ cookie: (await readOwner(root))?.cookie || '' })
119
+ const me = await probe.me()
120
+ if (me?.isLogin && me.uname) {
121
+ const r2 = await saveAccount(me, root)
122
+ if (r2) return send(res, 200, { ...r, owner: r2, note: `${r.note || '存下了。'} 登录的是:${me.uname}(uid ${me.mid})` })
123
+ }
124
+ } catch { /* 认不出来就算了,cookie 已经存下 */ }
125
+ }
126
+ return send(res, r.ok ? 200 : 400, r)
127
+ }
128
+ send(res, 405, { error: 'method not allowed' })
129
+ }],
130
+
131
+ ['/bili/state', async (req, res) => {
132
+ if (req.method !== 'GET') return send(res, 405, { error: '只支持 GET' })
133
+ const ow = await readOwner(root)
134
+ if (!ow?.cookie) return send(res, 200, { ok: false, state: 'none', note: '还没存 B 站登录。' })
135
+ try {
136
+ const c = createClient({ cookie: ow.cookie, log: () => {} })
137
+ const me = /** @type {any} */ (await c.me())
138
+ if (!me?.isLogin) {
139
+ return send(res, 200, { ok: false, state: 'expired', note: 'B 站登录已过期,需要重新登录。', why: me?.why ?? '' })
140
+ }
141
+ return send(res, 200, { ok: true, state: 'ok', name: String(me.uname ?? ''), mid: String(me.mid ?? ''), canWrite: Boolean(me.canWrite) })
142
+ } catch (err) {
143
+ const msg = String(/** @type {any} */ (err)?.message ?? err)
144
+ logLine('warn', ['登录态:查状态时没连上 B 站', msg.slice(0, 160)], root)
145
+ return send(res, 200, { ok: false, state: 'error', note: `没连上 B 站:${msg.slice(0, 60)}` })
146
+ }
147
+ }],
148
+
149
+ ['/bili/qr', async (req, res) => {
150
+ const u = new URL(String(req.url ?? '/'), 'http://x')
151
+ const sub = u.pathname.replace(/^\/dsh-fish\/bili\/qr/, '').replace(/\/+$/, '')
152
+
153
+ if (!sub) {
154
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
155
+ const r = await qrLogin.start()
156
+ return send(res, r.ok ? 200 : 502, r)
157
+ }
158
+
159
+ if (sub === '/status') {
160
+ if (req.method !== 'GET') return send(res, 405, { error: 'method not allowed' })
161
+ return send(res, 200, await qrLogin.poll(u.searchParams.get('key') ?? ''))
162
+ }
163
+
164
+ if (sub === '/save' || sub === '/drop') {
165
+ if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
166
+ /** @type {Record<string, unknown>} */
167
+ let body = {}
168
+ try {
169
+ body = JSON.parse((await readBody(req, 20_000)) || '{}')
170
+ } catch (err) {
171
+ if (sentTooLarge(res, err)) return
172
+ return send(res, 400, { error: 'body 不是合法 JSON' })
173
+ }
174
+ const key = String(body.key ?? '')
175
+ if (!key) return send(res, 400, { error: '缺 key' })
176
+ if (sub === '/drop') return send(res, 200, qrLogin.drop(key))
177
+ const r = await qrLogin.save(key, root)
178
+ return send(res, r.ok ? 200 : 409, r.ok ? r : { ...r, error: r.why || '这张码没存上。' })
179
+ }
180
+
181
+ send(res, 404, { error: 'no such route' })
182
+ }],
183
+
184
+ ['/browse-review', async (req, res) => {
185
+ if (req.method !== 'POST') return send(res, 405, { error: 'POST only' })
186
+ const r = /** @type {any} */ (await reviewNow(ctx, { root, log: (/** @type {string} */ k, /** @type {unknown} */ m) => logLine('info', [k, String(m ?? '')], root) }))
187
+ return send(res, r.ok ? 200 : 409, r.ok ? r : { ...r, error: r.why || '这一趟没整理成' })
188
+ }],
189
+
190
+ ['/browse', async (req, res) => {
191
+ if (req.method === 'POST') {
192
+ const { events } = await readEvents(root)
193
+ const { config } = await loadConfig(root)
194
+ const dk = dateKey()
195
+ const model = deriveSelf(events, { growthDays: config?.growthDays })
196
+ const r = /** @type {any} */ (await quietBrowse(root, model, config, dk, { events, force: true }, (/** @type {string} */ k, /** @type {unknown} */ m) => logLine('info', [k, String(m ?? '')], root)))
197
+ const picks = r.picks ?? []
198
+ return send(res, r.ok ? 200 : 409, {
199
+ ok: r.ok,
200
+ count: picks.length,
201
+ titles: picks.map((/** @type {any} */ p) => String(p.title || p.bvid || '')).filter(Boolean).slice(0, 5),
202
+ note: r.note || '',
203
+ error: r.ok ? undefined : (r.note || '这一趟没刷成'),
204
+ })
205
+ }
206
+ const { events } = await readEvents(root)
207
+ const { config } = await loadConfig(root)
208
+ const dk = dateKey()
209
+ const items = itemsFromEvents(events, dk)
210
+ const used = browseCountToday(events, dk)
211
+ const seen = seenOn(events, dk)
212
+ const lookedAll = []
213
+ for (const e of events) {
214
+ if (e?.type !== 'meta') continue
215
+ const t = String(e.text ?? '')
216
+ if (t.startsWith('looked:')) lookedAll.push(t.slice(7).trim().split(/\s+/)[0])
217
+ }
218
+ send(res, 200, {
219
+ enabled: Boolean(config?.browse?.enabled),
220
+ perDay: Number(config?.browse?.perDay ?? 0),
221
+ usedToday: used,
222
+ topN: Number(config?.browse?.topN ?? 0),
223
+ keywords: config?.browse?.keywords ?? [],
224
+ items,
225
+ watched: seen.watched,
226
+ watchedCount: seen.watched.length,
227
+ glancedCount: seen.glanced.length,
228
+ handed: seen.handed,
229
+ lookedCount: lookedAll.length,
230
+ lookedRecent: lookedAll.slice(-20).reverse(),
231
+ avoidKeywords: config?.avoid?.keywords ?? [],
232
+ avoidMids: config?.avoid?.upMids ?? [],
233
+ minDuration: Number(config?.avoid?.minDuration ?? 0),
234
+ })
235
+ }],
236
+
237
+ ['/history', async (req, res) => {
238
+ const url = new URL(req.url ?? '/', 'http://x')
239
+ const days = Math.max(1, Math.min(366, Number(url.searchParams.get('days')) || 14))
240
+ const { events } = await readEvents(root)
241
+ const groups = historyFromEvents(events, { days })
242
+ const total = groups.reduce((a, g) => a + g.items.length, 0)
243
+ send(res, 200, { days, total, groups })
244
+ }],
245
+
246
+ ['/away', async (_req, res) => {
247
+ send(res, 200, await readAway(root))
248
+ }],
249
+
250
+ ['/cover', async (req, res) => {
251
+ const m = String(req.url ?? '').match(/^\/dsh-fish\/cover\/(BV[0-9A-Za-z]{10})/)
252
+ if (!m) { send(res, 404, { error: 'no cover' }); return }
253
+ const file = coverPath(root, m[1]) || (await lazyCover(root, m[1]))
254
+ if (!file) { send(res, 404, { error: 'no cover' }); return }
255
+ try {
256
+ const buf = fs.readFileSync(file)
257
+ const ext = (file.split('.').pop() || '').toLowerCase()
258
+ const ct = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg'
259
+ res.writeHead(200, {
260
+ 'content-type': ct,
261
+ 'content-length': buf.length,
262
+ 'cache-control': 'private, max-age=86400',
263
+ })
264
+ res.end(buf)
265
+ } catch {
266
+ send(res, 404, { error: 'no cover' })
267
+ }
268
+ }],
269
+
270
+ ['/risk', async (req, res) => {
271
+ if (req.method === 'POST') {
272
+ /** @type {{ clear?: unknown }} */
273
+ let body = {}
274
+ try {
275
+ const raw = await readBody(req)
276
+ body = raw ? JSON.parse(raw) : {}
277
+ } catch (err) {
278
+ if (sentTooLarge(res, err)) return
279
+ body = {}
280
+ }
281
+ const cleared = Boolean(body?.clear)
282
+ if (cleared) clearRisk(root)
283
+ send(res, 200, { ...riskState(root), memory: memoryCooldown(), cleared })
284
+ return
285
+ }
286
+ send(res, 200, { ...riskState(root), memory: memoryCooldown() })
287
+ }],
288
+
289
+ ['/comment', async (_req, res) => {
290
+ const { events } = await readEvents(root)
291
+ const { config } = await loadConfig(root)
292
+ const dk = dateKey()
293
+ const c = config.comment ?? {}
294
+ const online = biliOn(config)
295
+ /** @type {any[]} */
296
+ let replies = []
297
+ if (c.enabled === true && online) {
298
+ replies = await scanReplies({ root, events, dateKey: dk }).catch(() => [])
299
+ }
300
+ send(res, 200, {
301
+ enabled: c.enabled === true,
302
+ online,
303
+ perDay: Number(c.perDay ?? 0),
304
+ usedToday: commentCountToday(events, dk),
305
+ replyPerDay: Number(c.replyPerDay ?? 0),
306
+ replyUsedToday: replyCountToday(events, dk),
307
+ replyToReplies: c.replyToReplies !== false,
308
+ scanEveryMin: Number(c.scanEveryMin ?? 30),
309
+ window: c.window ?? [],
310
+ mine: herComments(events, dk),
311
+ waiting: replies.slice(0, 5).map((x) => ({ rpid: x.rpid, bvid: x.bvid, user: x.user, text: x.text, fromOwner: x.fromOwner === true })),
312
+ waitingCount: replies.length,
313
+ waitingOwnerCount: replies.filter((x) => x.fromOwner === true).length,
314
+ })
315
+ }],
316
+
317
+ ['/at', async (req, res) => {
318
+ if (req.method !== 'GET') return send(res, 405, { error: '只支持 GET' })
319
+ const { events } = await readEvents(root)
320
+ const { config } = await loadConfig(root)
321
+ const a = config.at ?? {}
322
+ send(res, 200, {
323
+ enabled: a.enabled === true,
324
+ online: biliOn(config),
325
+ repliedToOthers: repliedToOthers(events),
326
+ usedToday: mentionsToday(events, dateKey()),
327
+ perDayMax: Number(a.perDayMax ?? 20),
328
+ })
329
+ }],
330
+ ]
331
+ }