@ssamurias/dsh-fish 1.0.8 → 1.1.0
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.
- package/AGENTS.md +368 -338
- package/CHANGELOG.md +113 -0
- package/README.md +377 -352
- package/RELEASE-NOTES-1.0.9.md +79 -0
- package/RELEASE-NOTES-1.1.0.md +55 -0
- package/docs//350/256/244/344/272/272/345/210/244/346/215/256.md +112 -0
- package/lib/appoint.js +106 -22
- package/lib/ask.js +2 -1
- package/lib/autobackup.js +4 -0
- package/lib/capture.js +16 -0
- package/lib/claim.js +103 -0
- package/lib/client/00-shell.js +630 -0
- package/lib/client/01-state-load.js +901 -0
- package/lib/client/02-actions.js +670 -0
- package/lib/client/03-widgets-header.js +721 -0
- package/lib/client/04-pressure-lab.js +891 -0
- package/lib/client/05-pressure-charts.js +431 -0
- package/lib/client/06-tab-status-grow.js +468 -0
- package/lib/client/07-tab-home-bili.js +610 -0
- package/lib/client/08-tab-memory-plugins.js +756 -0
- package/lib/client/09-tab-outing.js +710 -0
- package/lib/client/10-data-handlers.js +519 -0
- package/lib/client/11-tab-data-frame.js +749 -0
- package/lib/client/12-pressure-chip-mount.js +565 -0
- package/lib/client.js +477 -47
- package/lib/comment.js +18 -3
- package/lib/derive.js +262 -22
- package/lib/doing.js +31 -15
- package/lib/env.d.ts +224 -0
- package/lib/events.js +5 -2
- package/lib/guess.js +29 -0
- package/lib/health.js +75 -0
- package/lib/hear.js +67 -0
- package/lib/herpeople.js +159 -0
- package/lib/history.js +27 -5
- package/lib/home.js +12 -1
- package/lib/identity.js +23 -0
- package/lib/index.js +34 -18
- package/lib/look.js +3 -2
- package/lib/make.js +60 -12
- package/lib/markup.js +61 -23
- package/lib/observe-bili.js +334 -0
- package/lib/observe-config.js +223 -0
- package/lib/observe-data.js +522 -0
- package/lib/observe-home.js +384 -0
- package/lib/observe-http.js +250 -0
- package/lib/observe-outing.js +650 -0
- package/lib/observe-state.js +419 -0
- package/lib/observe-trip.js +286 -0
- package/lib/observe.js +99 -3574
- package/lib/people.js +514 -0
- package/lib/peopledoc.js +112 -0
- package/lib/persona.js +324 -42
- package/lib/restrict.js +74 -3
- package/lib/say.js +71 -1
- package/lib/scheduler.js +23 -3
- package/lib/schedules.js +97 -0
- package/lib/schema.js +11 -4
- package/lib/scrub.js +3 -3
- package/lib/selfdoc.js +19 -2
- package/lib/settings.js +112 -11
- package/lib/stance.js +47 -3
- package/lib/status.js +14 -5
- package/lib/sub.js +1 -1
- package/lib/tenant.js +35 -7
- package/lib/turns.js +51 -4
- package/lib/types.d.ts +515 -0
- package/lib/voices.js +3 -0
- package/lib/watch.js +1 -1
- package/lib/wiki.js +131 -25
- package/lib/works.js +120 -45
- package/package.json +1 -1
- package/scripts/build-client.mjs +83 -0
- package/scripts/sync-pressure-formulas.mjs +12 -15
|
@@ -0,0 +1,334 @@
|
|
|
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
|
+
// 搜索词在这边筛(2026-11-24,用户 m02329):365 天全量最多约七万条,
|
|
241
|
+
// 先整段发到浏览器再让前端过滤是白烧带宽;截 80 字防止有人拿它当注入口。
|
|
242
|
+
const q = String(url.searchParams.get('q') ?? '').trim().slice(0, 80)
|
|
243
|
+
const { events } = await readEvents(root)
|
|
244
|
+
const groups = historyFromEvents(events, { days, q })
|
|
245
|
+
const total = groups.reduce((a, g) => a + g.items.length, 0)
|
|
246
|
+
send(res, 200, { days, q, total, groups })
|
|
247
|
+
}],
|
|
248
|
+
|
|
249
|
+
['/away', async (_req, res) => {
|
|
250
|
+
send(res, 200, await readAway(root))
|
|
251
|
+
}],
|
|
252
|
+
|
|
253
|
+
['/cover', async (req, res) => {
|
|
254
|
+
const m = String(req.url ?? '').match(/^\/dsh-fish\/cover\/(BV[0-9A-Za-z]{10})/)
|
|
255
|
+
if (!m) { send(res, 404, { error: 'no cover' }); return }
|
|
256
|
+
const file = coverPath(root, m[1]) || (await lazyCover(root, m[1]))
|
|
257
|
+
if (!file) { send(res, 404, { error: 'no cover' }); return }
|
|
258
|
+
try {
|
|
259
|
+
const buf = fs.readFileSync(file)
|
|
260
|
+
const ext = (file.split('.').pop() || '').toLowerCase()
|
|
261
|
+
const ct = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg'
|
|
262
|
+
res.writeHead(200, {
|
|
263
|
+
'content-type': ct,
|
|
264
|
+
'content-length': buf.length,
|
|
265
|
+
'cache-control': 'private, max-age=86400',
|
|
266
|
+
})
|
|
267
|
+
res.end(buf)
|
|
268
|
+
} catch {
|
|
269
|
+
send(res, 404, { error: 'no cover' })
|
|
270
|
+
}
|
|
271
|
+
}],
|
|
272
|
+
|
|
273
|
+
['/risk', async (req, res) => {
|
|
274
|
+
if (req.method === 'POST') {
|
|
275
|
+
/** @type {{ clear?: unknown }} */
|
|
276
|
+
let body = {}
|
|
277
|
+
try {
|
|
278
|
+
const raw = await readBody(req)
|
|
279
|
+
body = raw ? JSON.parse(raw) : {}
|
|
280
|
+
} catch (err) {
|
|
281
|
+
if (sentTooLarge(res, err)) return
|
|
282
|
+
body = {}
|
|
283
|
+
}
|
|
284
|
+
const cleared = Boolean(body?.clear)
|
|
285
|
+
if (cleared) clearRisk(root)
|
|
286
|
+
send(res, 200, { ...riskState(root), memory: memoryCooldown(), cleared })
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
send(res, 200, { ...riskState(root), memory: memoryCooldown() })
|
|
290
|
+
}],
|
|
291
|
+
|
|
292
|
+
['/comment', async (_req, res) => {
|
|
293
|
+
const { events } = await readEvents(root)
|
|
294
|
+
const { config } = await loadConfig(root)
|
|
295
|
+
const dk = dateKey()
|
|
296
|
+
const c = config.comment ?? {}
|
|
297
|
+
const online = biliOn(config)
|
|
298
|
+
/** @type {any[]} */
|
|
299
|
+
let replies = []
|
|
300
|
+
if (c.enabled === true && online) {
|
|
301
|
+
replies = await scanReplies({ root, events, dateKey: dk }).catch(() => [])
|
|
302
|
+
}
|
|
303
|
+
send(res, 200, {
|
|
304
|
+
enabled: c.enabled === true,
|
|
305
|
+
online,
|
|
306
|
+
perDay: Number(c.perDay ?? 0),
|
|
307
|
+
usedToday: commentCountToday(events, dk),
|
|
308
|
+
replyPerDay: Number(c.replyPerDay ?? 0),
|
|
309
|
+
replyUsedToday: replyCountToday(events, dk),
|
|
310
|
+
replyToReplies: c.replyToReplies !== false,
|
|
311
|
+
scanEveryMin: Number(c.scanEveryMin ?? 30),
|
|
312
|
+
window: c.window ?? [],
|
|
313
|
+
mine: herComments(events, dk),
|
|
314
|
+
waiting: replies.slice(0, 5).map((x) => ({ rpid: x.rpid, bvid: x.bvid, user: x.user, text: x.text, fromOwner: x.fromOwner === true })),
|
|
315
|
+
waitingCount: replies.length,
|
|
316
|
+
waitingOwnerCount: replies.filter((x) => x.fromOwner === true).length,
|
|
317
|
+
})
|
|
318
|
+
}],
|
|
319
|
+
|
|
320
|
+
['/at', async (req, res) => {
|
|
321
|
+
if (req.method !== 'GET') return send(res, 405, { error: '只支持 GET' })
|
|
322
|
+
const { events } = await readEvents(root)
|
|
323
|
+
const { config } = await loadConfig(root)
|
|
324
|
+
const a = config.at ?? {}
|
|
325
|
+
send(res, 200, {
|
|
326
|
+
enabled: a.enabled === true,
|
|
327
|
+
online: biliOn(config),
|
|
328
|
+
repliedToOthers: repliedToOthers(events),
|
|
329
|
+
usedToday: mentionsToday(events, dateKey()),
|
|
330
|
+
perDayMax: Number(a.perDayMax ?? 20),
|
|
331
|
+
})
|
|
332
|
+
}],
|
|
333
|
+
]
|
|
334
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* observe-config.js —— 观测台生长环境配置、工具白名单与规则裁决路由
|
|
4
|
+
*
|
|
5
|
+
* 路由:
|
|
6
|
+
* /config · /tools · /rules · /decide
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { readEvents } from './store.js'
|
|
10
|
+
import { loadConfig, updateConfig, configFileInfo, validateToolNames, sanitizeToolNames, windowProblem } from './settings.js'
|
|
11
|
+
import { fillSelf, selfPronounFor } from './selfpronoun.js'
|
|
12
|
+
import { deriveSelf } from './derive.js'
|
|
13
|
+
import { noteSpeakEnabled, speakOn } from './speak.js'
|
|
14
|
+
import { noteKeepVersions } from './make.js'
|
|
15
|
+
import { refreshSelfDoc } from './selfdoc.js'
|
|
16
|
+
import { rulesByLayer } from './rules.js'
|
|
17
|
+
import { ruleStatus, offerHistory, pendingOffer, offerLimits } from './unlock.js'
|
|
18
|
+
import { recordGrant } from './grant.js'
|
|
19
|
+
import { readRestrictState, knownToolNames, ownLayerNames, blockedTools, herToolsNow, herSceneToolsNow, currentAllowTools, refreshToolRestrict } from './restrict.js'
|
|
20
|
+
import { bridgeUrl } from './bridgeserve.js'
|
|
21
|
+
import { logLine } from './log.js'
|
|
22
|
+
import { send, readBody } from './observe-http.js'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 这一局收窄真在管的那两份名单(/tools 用)。
|
|
26
|
+
* @returns {{ allowNow: string[]|null, effective: string[]|null, skipped: string[], skippedSure: boolean|null }}
|
|
27
|
+
*/
|
|
28
|
+
export function toolsNowOf() {
|
|
29
|
+
const allowNow = currentAllowTools()
|
|
30
|
+
const R = /** @type {any} */ (readRestrictState())
|
|
31
|
+
const applied = allowNow !== null && Number(R?.applied) > 0
|
|
32
|
+
return {
|
|
33
|
+
allowNow,
|
|
34
|
+
effective: applied && Array.isArray(R.effective) ? R.effective.slice() : null,
|
|
35
|
+
skipped: applied && Array.isArray(R.skipped) ? R.skipped.slice() : [],
|
|
36
|
+
skippedSure: applied ? R.skippedSure !== false : null,
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {import('./types.js').ObserveEnv} env
|
|
42
|
+
* @returns {import('./types.js').ObserveRouteEntry[]}
|
|
43
|
+
*/
|
|
44
|
+
export function buildConfigRoutes(env) {
|
|
45
|
+
const { ctx, root, syncBridgePort } = env
|
|
46
|
+
|
|
47
|
+
return [
|
|
48
|
+
['/config', async (req, res) => {
|
|
49
|
+
if (req.method === 'GET') {
|
|
50
|
+
const { config } = await loadConfig(root)
|
|
51
|
+
const info = await configFileInfo(root)
|
|
52
|
+
return send(res, 200, { config, file: info })
|
|
53
|
+
}
|
|
54
|
+
if (req.method === 'POST' || req.method === 'PUT') {
|
|
55
|
+
const body = await readBody(req)
|
|
56
|
+
let patch
|
|
57
|
+
try { patch = JSON.parse(body || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
|
|
58
|
+
const strictTools = patch.strictTools === true
|
|
59
|
+
delete patch.strictTools
|
|
60
|
+
// 白名单:只允许改"环境",不允许任何指向她本人的键(test/p5.test.mjs 反查这张表)
|
|
61
|
+
const allowed = ['growthDays', 'wakesPerDay', 'window', 'daily', 'diary', 'absenceAfterDays', 'avoid', 'browse', 'bili', 'video', 'comment', 'at', 'people', 'notify', 'chat', 'rooms', 'memory', 'tools', 'observe', 'ui', 'proactive', 'drive', 'interest', 'dream', 'works', 'owner', 'self', 'backup', 'cloud', 'bridge']
|
|
62
|
+
const bad = Object.keys(patch).filter((k) => !allowed.includes(k))
|
|
63
|
+
if (bad.length) {
|
|
64
|
+
logLine('warn', [
|
|
65
|
+
'/config 保存被白名单挡回:',
|
|
66
|
+
`拒了 ${bad.join('、')}`,
|
|
67
|
+
`提交的键 ${Object.keys(patch).join('、')}`,
|
|
68
|
+
], root)
|
|
69
|
+
return send(res, 400, { error: `这一版还不支持保存:${bad.join('、')}` })
|
|
70
|
+
}
|
|
71
|
+
/** @type {[string, unknown][]} */
|
|
72
|
+
const ranges = [
|
|
73
|
+
[fillSelf('{S}醒着的时间段', selfPronounFor(root)), patch.window],
|
|
74
|
+
['上网时段', patch.browse?.window],
|
|
75
|
+
['评论时段', patch.comment?.window],
|
|
76
|
+
]
|
|
77
|
+
for (const [label, w] of ranges) {
|
|
78
|
+
if (w === undefined || w === null) continue
|
|
79
|
+
const problem = windowProblem(w)
|
|
80
|
+
if (problem) return send(res, 400, { error: `${label}:${problem}` })
|
|
81
|
+
}
|
|
82
|
+
/** @type {string[]} */
|
|
83
|
+
let droppedTools = []
|
|
84
|
+
if (patch.tools && patch.tools.allow !== undefined) {
|
|
85
|
+
if (strictTools) {
|
|
86
|
+
const check = validateToolNames(patch.tools.allow, knownToolNames(ctx))
|
|
87
|
+
if (!check.ok) {
|
|
88
|
+
logLine('warn', ['/config 保存被工具名校验挡回:', `不存在的名字 ${check.unknown.join('、')}`], root)
|
|
89
|
+
return send(res, 400, {
|
|
90
|
+
error: `这些工具名不存在:${check.unknown.join('、')}`,
|
|
91
|
+
unknown: check.unknown,
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
patch.tools.allow = check.names
|
|
95
|
+
} else {
|
|
96
|
+
const clean = sanitizeToolNames(patch.tools.allow, knownToolNames(ctx))
|
|
97
|
+
patch.tools.allow = clean.names
|
|
98
|
+
droppedTools = clean.dropped
|
|
99
|
+
if (droppedTools.length) {
|
|
100
|
+
logLine('warn', [
|
|
101
|
+
'/config 里的工具名在这台机器上不存在,已跳过:',
|
|
102
|
+
droppedTools.join('、'),
|
|
103
|
+
`保留 ${clean.names.length} 个`,
|
|
104
|
+
], root)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const before = await loadConfig(root).catch(() => null)
|
|
109
|
+
const next = await updateConfig(patch, root)
|
|
110
|
+
const beforeAllow = JSON.stringify(before?.config?.tools?.allow ?? [])
|
|
111
|
+
const nextAllow = JSON.stringify(next?.tools?.allow ?? [])
|
|
112
|
+
let toolsLive = null
|
|
113
|
+
if (beforeAllow !== nextAllow) {
|
|
114
|
+
try {
|
|
115
|
+
const r = /** @type {any} */ (refreshToolRestrict({ extra: next?.tools?.allow ?? [] }))
|
|
116
|
+
toolsLive = { ok: r?.ok === true, deferred: r?.deferred?.length ?? 0 }
|
|
117
|
+
logLine('info', [
|
|
118
|
+
'tools.allow 已当场生效',
|
|
119
|
+
`allow=${(next?.tools?.allow ?? []).join(',') || '(空)'}`,
|
|
120
|
+
`换刀=${r?.applied?.length ?? 0}`,
|
|
121
|
+
r?.deferred?.length ? `延后=${r.deferred.length}` : '',
|
|
122
|
+
], root)
|
|
123
|
+
} catch (err) {
|
|
124
|
+
logLine('warn', ['白名单热更新没成(下次新建会话照样生效):', String(/** @type {any} */ (err)?.message ?? err).slice(0, 200)], root)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
await refreshSelfDoc(root).catch(() => {})
|
|
128
|
+
noteSpeakEnabled(speakOn(next))
|
|
129
|
+
// 工具说明跟着「保留旧版」开关走:保存完就换文字,下一轮她读到的说明和盘上一致。
|
|
130
|
+
noteKeepVersions(next?.works?.keepVersions !== false)
|
|
131
|
+
const wasVisible = before?.config?.diary?.visible === true
|
|
132
|
+
const nowVisible = next?.diary?.visible === true
|
|
133
|
+
if (wasVisible !== nowVisible) {
|
|
134
|
+
logLine('info', [
|
|
135
|
+
'diary.visible',
|
|
136
|
+
wasVisible ? 'on' : 'off',
|
|
137
|
+
'->',
|
|
138
|
+
nowVisible ? 'on' : 'off',
|
|
139
|
+
`by=${Object.keys(patch).join(',')}`,
|
|
140
|
+
], root)
|
|
141
|
+
}
|
|
142
|
+
const beforePort = Number(before?.config?.bridge?.port) || 0
|
|
143
|
+
const nextPort = Number(next?.bridge?.port) || 0
|
|
144
|
+
if (beforePort !== nextPort) {
|
|
145
|
+
try {
|
|
146
|
+
syncBridgePort(nextPort, '设置页')
|
|
147
|
+
} catch (err) {
|
|
148
|
+
logLine('warn', ['桥接投递口热更新没成:', String(/** @type {any} */ (err)?.message ?? err).slice(0, 200)], root)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
const c = /** @type {any} */ (next ?? {})
|
|
153
|
+
const on = (/** @type {unknown} */ v) => (v === true ? 'on' : 'off')
|
|
154
|
+
logLine('info', [
|
|
155
|
+
'config',
|
|
156
|
+
`by=${Object.keys(patch).join(',')}`,
|
|
157
|
+
`bili=${on(c.bili?.enabled)}`,
|
|
158
|
+
`comment=${on(c.comment?.enabled)}`,
|
|
159
|
+
`perDay=${Number(c.comment?.perDay) || 0}`,
|
|
160
|
+
`reply=${on(c.comment?.replyToReplies)}`,
|
|
161
|
+
`browse=${on(c.browse?.enabled)}`,
|
|
162
|
+
`proactive=${on(c.proactive?.enabled)}`,
|
|
163
|
+
`bridge=${Number(c.bridge?.port) || 0}`,
|
|
164
|
+
], root)
|
|
165
|
+
} catch { /* 快照失败不影响保存 */ }
|
|
166
|
+
return send(res, 200, { ok: true, config: next, droppedTools, toolsLive, bridge: bridgeUrl() })
|
|
167
|
+
}
|
|
168
|
+
send(res, 405, { error: 'method not allowed' })
|
|
169
|
+
}],
|
|
170
|
+
|
|
171
|
+
['/tools', async (req, res) => {
|
|
172
|
+
if (req.method !== 'GET') return send(res, 405, { error: 'method not allowed' })
|
|
173
|
+
const known = knownToolNames(ctx)
|
|
174
|
+
return send(res, 200, {
|
|
175
|
+
ok: Boolean(known && known.length),
|
|
176
|
+
known: known ?? [],
|
|
177
|
+
ownLayer: ownLayerNames(),
|
|
178
|
+
blocked: blockedTools(),
|
|
179
|
+
herTools: herToolsNow(),
|
|
180
|
+
herSceneTools: herSceneToolsNow(),
|
|
181
|
+
...toolsNowOf(),
|
|
182
|
+
})
|
|
183
|
+
}],
|
|
184
|
+
|
|
185
|
+
['/rules', async (req, res) => {
|
|
186
|
+
if (req.method !== 'GET') return send(res, 405, { error: 'method not allowed' })
|
|
187
|
+
const { events } = await readEvents(root).catch(() => ({ events: [] }))
|
|
188
|
+
const { config } = await loadConfig(root)
|
|
189
|
+
const model = deriveSelf(events, config)
|
|
190
|
+
return send(res, 200, {
|
|
191
|
+
layers: rulesByLayer(),
|
|
192
|
+
status: ruleStatus(events, model, Date.now(), offerLimits(config)),
|
|
193
|
+
history: offerHistory(events).slice(-20),
|
|
194
|
+
pending: (() => {
|
|
195
|
+
const p = pendingOffer(events, Date.now(), offerLimits(config))
|
|
196
|
+
return p ? { id: p.id, rule: p.grant?.rule || '', why: p.text || '' } : null
|
|
197
|
+
})(),
|
|
198
|
+
offersOn: config?.rules?.offers !== false,
|
|
199
|
+
})
|
|
200
|
+
}],
|
|
201
|
+
|
|
202
|
+
['/decide', async (req, res) => {
|
|
203
|
+
if (req.method !== 'POST') return send(res, 405, { error: 'method not allowed' })
|
|
204
|
+
const raw = await readBody(req)
|
|
205
|
+
let body
|
|
206
|
+
try { body = JSON.parse(raw || '{}') } catch { return send(res, 400, { error: 'body 不是合法 JSON' }) }
|
|
207
|
+
const verdict = body.verdict === 'approve' || body.verdict === 'reject' ? body.verdict : null
|
|
208
|
+
if (!verdict) return send(res, 400, { error: 'verdict 只能是 approve 或 reject' })
|
|
209
|
+
const { events } = await readEvents(root).catch(() => ({ events: [] }))
|
|
210
|
+
const held = await loadConfig(root).catch(() => ({ config: null }))
|
|
211
|
+
const p = pendingOffer(events, Date.now(), offerLimits(held.config ?? undefined))
|
|
212
|
+
if (!p) return send(res, 409, { error: '现在没有待裁决的申请' })
|
|
213
|
+
const r = await recordGrant(root, {
|
|
214
|
+
offerId: p.id,
|
|
215
|
+
rule: p.grant?.rule || '',
|
|
216
|
+
verdict,
|
|
217
|
+
reason: typeof body.reason === 'string' ? body.reason : '',
|
|
218
|
+
})
|
|
219
|
+
if (!r.ok) return send(res, 400, { error: r.error })
|
|
220
|
+
return send(res, 200, { ok: true, verdict })
|
|
221
|
+
}],
|
|
222
|
+
]
|
|
223
|
+
}
|