dsh-half-page 0.3.51 → 0.4.43
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/README.md +10 -2
- package/client.js +995 -672
- package/index.js +1143 -126
- package/package.json +7 -2
package/index.js
CHANGED
|
@@ -1,18 +1,56 @@
|
|
|
1
1
|
// dsh-half-page · 半页(自己的读书与写字)
|
|
2
2
|
// 宿主侧:书库、切章、读后感、进度;客户端面板读 HTTP 路由。
|
|
3
|
-
import {
|
|
3
|
+
import {readFile, writeFile, mkdir, readdir, stat, rename, open, unlink, copyFile, appendFile} from 'node:fs/promises'
|
|
4
4
|
import { readFileSync } from 'node:fs'
|
|
5
|
+
import { spawn } from 'node:child_process'
|
|
5
6
|
import { join, basename, dirname, extname, resolve, relative, isAbsolute } from 'node:path'
|
|
6
|
-
import {
|
|
7
|
+
import {homedir, tmpdir} from 'node:os'
|
|
7
8
|
import { fileURLToPath } from 'node:url'
|
|
8
9
|
import { readTimeline, newestSessionId } from './lib/session-probe.js'
|
|
9
10
|
import { loadCreateUserMessage, SOURCE_KIND } from './lib/notice.js'
|
|
10
11
|
|
|
12
|
+
/**
|
|
13
|
+
* 路由准入(工单-HTTP路由准入,2026-11-26)。
|
|
14
|
+
*
|
|
15
|
+
* 宿主契约:register({ auth }) 的 auth 可以是
|
|
16
|
+
* 'anonymous' | 'required' | 'deny',或 (request) => policy;
|
|
17
|
+
* request 里有 { headers, method, url, transport }。
|
|
18
|
+
*
|
|
19
|
+
* 规则:请求带 Origin/Referer 且跟 Host 对不上 → 拒;Origin 是 "null"
|
|
20
|
+
* (沙箱页面 / data: / file:)→ 拒;没带来源(curl、本地脚本、同源导航)
|
|
21
|
+
* 或来源就是本服务的 Host → 放行。面板在同源 iframe 里跑,功能不变。
|
|
22
|
+
*/
|
|
23
|
+
export function sameSiteAuth(request) {
|
|
24
|
+
const headers = request?.headers
|
|
25
|
+
const read = (name) => {
|
|
26
|
+
if (!headers) return undefined
|
|
27
|
+
if (typeof headers.get === 'function') return headers.get(name) ?? undefined
|
|
28
|
+
const value = headers[name] ?? headers[name.toLowerCase()] ?? headers[name.toUpperCase()]
|
|
29
|
+
return Array.isArray(value) ? value[0] : value
|
|
30
|
+
}
|
|
31
|
+
const host = String(read('host') || '')
|
|
32
|
+
const source = String(read('origin') || read('referer') || '')
|
|
33
|
+
if (!source) return 'anonymous'
|
|
34
|
+
if (source === 'null') return 'deny'
|
|
35
|
+
try {
|
|
36
|
+
const url = new URL(source)
|
|
37
|
+
if (host && url.host === host) return 'anonymous'
|
|
38
|
+
// 同一个本机服务、但 Host 头缺失(HTTP/1.0、某些本地代理)
|
|
39
|
+
if (!host && (url.hostname === '127.0.0.1' || url.hostname === 'localhost')) return 'anonymous'
|
|
40
|
+
return 'deny'
|
|
41
|
+
} catch {
|
|
42
|
+
return 'deny'
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
11
47
|
export const inject = ['webServer', 'tools', 'systemPrompt', 'agents', 'sessions']
|
|
12
48
|
|
|
13
49
|
const HOME = process.env.USERPROFILE || process.env.HOME || homedir()
|
|
14
|
-
|
|
15
|
-
const
|
|
50
|
+
// 跟宿主的 DSH_HOME 走:有人把它设到别的盘时,数据和插件不能分家(心跳就是这么写的)
|
|
51
|
+
const DSH_HOME = process.env.DSH_HOME || join(HOME, '.dsh')
|
|
52
|
+
const CONFIG = join(DSH_HOME, 'reading.config.json')
|
|
53
|
+
const DEFAULT_DIR = join(DSH_HOME, 'reading')
|
|
16
54
|
|
|
17
55
|
const CH_RE = /^[ \t\u3000]*(第[0-90-9一二三四五六七八九十百千两零〇]+[章节回][^\n]{0,30})$/m
|
|
18
56
|
const CH_LINE_RE = /^[ \t\u3000]*(第[0-90-9一二三四五六七八九十百千两零〇]+[章节回][^\n]{0,30})$/gm
|
|
@@ -121,6 +159,211 @@ export async function saveState(dir, st) {
|
|
|
121
159
|
await writeJson(join(dir, 'state.json'), st)
|
|
122
160
|
}
|
|
123
161
|
|
|
162
|
+
/* ---------------- 一个书房,多个读者 ----------------
|
|
163
|
+
* 旧版本只有书级进度(books[id].readThrough/next/noteUntil),等于「这台机器上所有读者共用一条进度」。
|
|
164
|
+
* 现在加一层 readers[<读者 id>]:每个读者各有一份进度,书级只留「读得最远」(furthest)。
|
|
165
|
+
* 读者 id 就是会话 id;拿不到会话就落到 LEGACY_READER(老数据迁移过来的那份)。
|
|
166
|
+
* 读后感仍然只有一个 读后感.md,靠署名区分——不要拆成多个文件。
|
|
167
|
+
*/
|
|
168
|
+
export const LEGACY_READER = '__legacy__'
|
|
169
|
+
/** 那份「所有人都从这儿接」的书签,面板上叫什么。以前叫「默认读者」,容易被当成一个人;它其实是书级进度。 */
|
|
170
|
+
export const LEGACY_READER_NAME = '读书总进度'
|
|
171
|
+
/** 读者 id → 名字的临时表:建分片时顺手把名字写对,别把会话 id 当名字存进去。 */
|
|
172
|
+
export const READER_NAMES = new Map()
|
|
173
|
+
|
|
174
|
+
/** 老状态没有 readers:把 books[id] 现有进度抄成「总读书进度」,幂等。
|
|
175
|
+
* 一本书都没读过(新机器第一次装)就不建这一份——不然别人装上会看见一个空的「总读书进度」。 */
|
|
176
|
+
export function migrateReaders(st) {
|
|
177
|
+
if (!st || typeof st !== 'object') return st
|
|
178
|
+
if (st.readers && typeof st.readers === 'object') {
|
|
179
|
+
if (st.readers[LEGACY_READER]) st.readers[LEGACY_READER].name = LEGACY_READER_NAME
|
|
180
|
+
return st
|
|
181
|
+
}
|
|
182
|
+
const legacy = { name: LEGACY_READER_NAME, books: {} }
|
|
183
|
+
for (const [id, rec] of Object.entries(st.books || {})) {
|
|
184
|
+
const has = (Number(rec.readThrough) || 0) > 0 || (Number(rec.noteUntil) || 0) > 0
|
|
185
|
+
|| (Number(rec.next) || 1) > 1 || Boolean(rec.lastReadAt)
|
|
186
|
+
if (!Number.isFinite(Number(rec.furthest))) rec.furthest = Number(rec.readThrough) || 0
|
|
187
|
+
if (!has) continue
|
|
188
|
+
legacy.books[id] = {
|
|
189
|
+
readThrough: Number(rec.readThrough) || 0,
|
|
190
|
+
next: Number(rec.next) || 1,
|
|
191
|
+
noteUntil: Number(rec.noteUntil) || 0,
|
|
192
|
+
lastReadAt: rec.lastReadAt || '',
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
st.readers = Object.keys(legacy.books).length > 0 ? { [LEGACY_READER]: legacy } : {}
|
|
196
|
+
return st
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 某个读者的分片(没有就建)。name 只是给人看的。 */
|
|
200
|
+
export function readerShard(st, rid, name) {
|
|
201
|
+
migrateReaders(st)
|
|
202
|
+
const key = String(rid || LEGACY_READER)
|
|
203
|
+
const r = st.readers[key] || (st.readers[key] = { name: name || (key === LEGACY_READER ? LEGACY_READER_NAME : key), books: {} })
|
|
204
|
+
if (name && r.name !== name) r.name = name
|
|
205
|
+
return r
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** 某个读者在某本书上的进度(没有就建空的;空分片先继承书级那份,等于「你还没动过,从大家读到的地方接」)。 */
|
|
209
|
+
export function readerBook(st, rid, id) {
|
|
210
|
+
const shard = readerShard(st, rid, READER_NAMES.get(String(rid)) || '')
|
|
211
|
+
const own = shard.books[id]
|
|
212
|
+
if (own) return own
|
|
213
|
+
const base = st.books?.[id] || {}
|
|
214
|
+
return (shard.books[id] = {
|
|
215
|
+
readThrough: Number(base.readThrough) || 0,
|
|
216
|
+
next: Number(base.next) || 1,
|
|
217
|
+
noteUntil: Number(base.noteUntil) || 0,
|
|
218
|
+
lastReadAt: base.lastReadAt || '',
|
|
219
|
+
})
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** 读进度但不建:面板/书架扫一遍时用,避免给没读过的书建空分片。没有分片就继承书级。 */
|
|
223
|
+
/** 只看这位读者自己的分片:没读过返回 null(不继承书级)。面板「我读到哪」用它,避免把书级进度当成我的。 */
|
|
224
|
+
export function readerOwnBook(st, rid, id) {
|
|
225
|
+
migrateReaders(st)
|
|
226
|
+
const b = st.readers?.[String(rid || LEGACY_READER)]?.books?.[id]
|
|
227
|
+
if (!b) return null
|
|
228
|
+
return {
|
|
229
|
+
readThrough: Number(b.readThrough) || 0,
|
|
230
|
+
next: Number(b.next) || 1,
|
|
231
|
+
noteUntil: Number(b.noteUntil) || 0,
|
|
232
|
+
lastReadAt: b.lastReadAt || '',
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export function readerBookRead(st, rid, id) {
|
|
237
|
+
migrateReaders(st)
|
|
238
|
+
const b = st.readers?.[String(rid || LEGACY_READER)]?.books?.[id]
|
|
239
|
+
if (b) {
|
|
240
|
+
return {
|
|
241
|
+
readThrough: Number(b.readThrough) || 0,
|
|
242
|
+
next: Number(b.next) || 1,
|
|
243
|
+
noteUntil: Number(b.noteUntil) || 0,
|
|
244
|
+
lastReadAt: b.lastReadAt || '',
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const base = st.books?.[id] || {}
|
|
248
|
+
return {
|
|
249
|
+
readThrough: Number(base.readThrough) || 0,
|
|
250
|
+
next: Number(base.next) || 1,
|
|
251
|
+
noteUntil: Number(base.noteUntil) || 0,
|
|
252
|
+
lastReadAt: base.lastReadAt || '',
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 书级「读得最远」:所有读者里最大的 readThrough,只增不减。 */
|
|
257
|
+
export function furthestOf(st, id) {
|
|
258
|
+
migrateReaders(st)
|
|
259
|
+
let far = Number(st.books?.[id]?.furthest) || 0
|
|
260
|
+
for (const r of Object.values(st.readers || {})) {
|
|
261
|
+
far = Math.max(far, Number(r.books?.[id]?.readThrough) || 0)
|
|
262
|
+
}
|
|
263
|
+
const rec = st.books?.[id]
|
|
264
|
+
if (rec) {
|
|
265
|
+
far = Math.max(far, Number(rec.readThrough) || 0)
|
|
266
|
+
rec.furthest = far
|
|
267
|
+
}
|
|
268
|
+
return far
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** 书级「读得最远」是谁读的:返回 { name, readThrough };没人读过就返回总进度那个名字。 */
|
|
272
|
+
export function furthestReaderOf(st, id) {
|
|
273
|
+
migrateReaders(st)
|
|
274
|
+
const far = furthestOf(st, id)
|
|
275
|
+
let best = null
|
|
276
|
+
for (const [rid, r] of Object.entries(st.readers || {})) {
|
|
277
|
+
if (rid === LEGACY_READER) continue
|
|
278
|
+
const n = Number(r.books?.[id]?.readThrough) || 0
|
|
279
|
+
if (n > 0 && (!best || n > best.readThrough)) best = { id: rid, name: r.name || rid, readThrough: n }
|
|
280
|
+
}
|
|
281
|
+
// 书级数字比所有读者分片都高(那条会话不在了),就没有具体的人可报
|
|
282
|
+
if (!best || best.readThrough < far) return { id: LEGACY_READER, name: LEGACY_READER_NAME, readThrough: far }
|
|
283
|
+
return { id: best.id, name: best.name, readThrough: far }
|
|
284
|
+
}
|
|
285
|
+
/** 面板 / 工具都要的读者一览:id、名字、每本书读到哪。
|
|
286
|
+
* 「默认读者」没有会话在用,它的分片停在迁移那一刻;但它代表的那条书签(书级 next/readThrough)
|
|
287
|
+
* 是所有人共用、一直在往前走的,所以这里给它显示书级那份——否则面板上会显得它永远没动。 */
|
|
288
|
+
export function readerSummary(st) {
|
|
289
|
+
migrateReaders(st)
|
|
290
|
+
const out = []
|
|
291
|
+
for (const [id, r] of Object.entries(st.readers || {})) {
|
|
292
|
+
const books = {}
|
|
293
|
+
let lastAt = 0
|
|
294
|
+
const readingOf = id === LEGACY_READER ? (st.books || {}) : (r.books || {})
|
|
295
|
+
for (const [bid, b] of Object.entries(readingOf)) {
|
|
296
|
+
books[bid] = { readThrough: Number(b.readThrough) || 0, next: Number(b.next) || 1, noteUntil: Number(b.noteUntil) || 0 }
|
|
297
|
+
const at = typeof b.lastReadAt === 'number' ? b.lastReadAt : Date.parse(String(b.lastReadAt || ''))
|
|
298
|
+
if (Number.isFinite(at) && at > lastAt) lastAt = at
|
|
299
|
+
}
|
|
300
|
+
// 一本都没读过的读者不往面板上摆(新机器、或刚建分片还没读);手动加的读者例外——加它就是为让它出现
|
|
301
|
+
if (Object.keys(books).length === 0 && !r.manual) continue
|
|
302
|
+
out.push({ id, name: r.name || id, books, today: readTodayOf(st, id), lastAt, manual: r.manual === true })
|
|
303
|
+
}
|
|
304
|
+
return out.sort((a, b) => (a.id === LEGACY_READER ? -1 : b.id === LEGACY_READER ? 1 : 0))
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** 这个读者最后读过的那本书(按分片里的 lastReadAt 取最大);没有就空串。 */
|
|
308
|
+
export function lastReadBookOf(st, rid) {
|
|
309
|
+
const key = String(rid || LEGACY_READER)
|
|
310
|
+
const books = st?.readers?.[key]?.books || {}
|
|
311
|
+
let best = ''
|
|
312
|
+
let at = ''
|
|
313
|
+
for (const [bid, b] of Object.entries(books)) {
|
|
314
|
+
const when = String(b?.lastReadAt || '')
|
|
315
|
+
if (!when) continue
|
|
316
|
+
if (when >= at) { at = when; best = bid }
|
|
317
|
+
}
|
|
318
|
+
if (best) return best
|
|
319
|
+
// 兜底:老分片没记 lastReadAt(早期版本 / 被回灌坏过)。挑读得最远的那本,
|
|
320
|
+
// 再不行看整机书级,最后才回落面板当前那本——总之别因为缺一个时间戳就报「不知道读哪本」。
|
|
321
|
+
let far = ''
|
|
322
|
+
let farN = 0
|
|
323
|
+
const pick = (obj) => {
|
|
324
|
+
for (const [bid, b] of Object.entries(obj || {})) {
|
|
325
|
+
const n = Math.max(Number(b?.readThrough) || 0, Number(b?.furthest) || 0)
|
|
326
|
+
if (n > farN) { farN = n; far = bid }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
pick(books)
|
|
330
|
+
if (far) return far
|
|
331
|
+
pick(st?.books)
|
|
332
|
+
if (far) return far
|
|
333
|
+
return String(st?.current || '') || Object.keys(st?.books || {})[0] || ''
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** 简单文件锁:读后感是「读进来—改—写回去」,两个窗口同时写会丢一条。
|
|
337
|
+
* 拿不到就一直等(上限 20 秒),超时才放弃——宁可慢一点,也不许两段同时写同一个文件。
|
|
338
|
+
* 锁文件超过 30 秒没被删,当上一个进程死掉了,直接接管。 */
|
|
339
|
+
async function withFileLock(target, fn, tries = 800) {
|
|
340
|
+
const lock = target + '.lock'
|
|
341
|
+
let handle = null
|
|
342
|
+
for (let i = 0; i < tries; i += 1) {
|
|
343
|
+
try {
|
|
344
|
+
handle = await open(lock, 'wx')
|
|
345
|
+
break
|
|
346
|
+
} catch {
|
|
347
|
+
try {
|
|
348
|
+
const info = await stat(lock)
|
|
349
|
+
if (Date.now() - info.mtimeMs > 30 * 1000) {
|
|
350
|
+
await unlink(lock)
|
|
351
|
+
continue
|
|
352
|
+
}
|
|
353
|
+
} catch {}
|
|
354
|
+
await new Promise((r) => setTimeout(r, 15 + Math.floor(Math.random() * 25)))
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
try {
|
|
358
|
+
return await fn()
|
|
359
|
+
} finally {
|
|
360
|
+
if (handle) {
|
|
361
|
+
try { await handle.close() } catch {}
|
|
362
|
+
try { await unlink(lock) } catch {}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
124
367
|
/** 把整本书切成章:返回 [{title, start, end}] */
|
|
125
368
|
export function splitChapters(text) {
|
|
126
369
|
const idx = []
|
|
@@ -202,6 +445,67 @@ export function studyStateOf(st, now = Date.now()) {
|
|
|
202
445
|
}
|
|
203
446
|
}
|
|
204
447
|
|
|
448
|
+
/** 一条书房时间:字段齐全、缺的给默认;came from state.study.slots 或旧配置合成 */
|
|
449
|
+
export function normaliseStudySlot(raw, cfg, i = 0) {
|
|
450
|
+
const s = raw || {}
|
|
451
|
+
const mode = s.mode === 'day' || s.mode === 'week' ? s.mode : studyModeOf(cfg)
|
|
452
|
+
const dBudget = Math.min(7, Math.max(1, Math.floor(Number(s.per) || (mode === 'day' ? studyPerDayOf(cfg) : studyPerWeekOf(cfg)))))
|
|
453
|
+
return {
|
|
454
|
+
id: String(s.id || ('slot-' + (i + 1))),
|
|
455
|
+
enabled: s.enabled === true,
|
|
456
|
+
from: String(s.from ?? ''),
|
|
457
|
+
to: String(s.to ?? ''),
|
|
458
|
+
mode,
|
|
459
|
+
per: dBudget,
|
|
460
|
+
session: String(s.session ?? ''),
|
|
461
|
+
lastAt: Number(s.lastAt) || 0,
|
|
462
|
+
week: String(s.week || ''),
|
|
463
|
+
weekCount: Number(s.weekCount) || 0,
|
|
464
|
+
day: String(s.day || ''),
|
|
465
|
+
dayCount: Number(s.dayCount) || 0,
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** state.study.slots;一条都没有时用旧配置合成一条(老用户行为不变) */
|
|
470
|
+
export function studySlotsOf(st, cfg) {
|
|
471
|
+
const raw = Array.isArray(st?.study?.slots) ? st.study.slots : []
|
|
472
|
+
if (raw.length) return raw.map((s, i) => normaliseStudySlot(s, cfg, i))
|
|
473
|
+
return [normaliseStudySlot({
|
|
474
|
+
id: 'slot-1',
|
|
475
|
+
enabled: cfg?.studyEnabled === true,
|
|
476
|
+
from: cfg?.studyFrom ?? '',
|
|
477
|
+
to: cfg?.studyTo ?? '',
|
|
478
|
+
mode: studyModeOf(cfg),
|
|
479
|
+
per: studyModeOf(cfg) === 'day' ? studyPerDayOf(cfg) : studyPerWeekOf(cfg),
|
|
480
|
+
session: cfg?.studySession ?? '',
|
|
481
|
+
}, cfg, 0)]
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** 把一条 slot 摊成 decideStudy 认的 cfg 形状 */
|
|
485
|
+
export function slotCfgOf(slot) {
|
|
486
|
+
return {
|
|
487
|
+
studyEnabled: slot.enabled === true,
|
|
488
|
+
studyFrom: slot.from,
|
|
489
|
+
studyTo: slot.to,
|
|
490
|
+
studyMode: slot.mode,
|
|
491
|
+
studyPerDay: slot.per,
|
|
492
|
+
studyPerWeek: slot.per,
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** 一条 slot 自己的计数(跨周/跨天归零) */
|
|
497
|
+
export function slotStudyOf(slot, now = Date.now()) {
|
|
498
|
+
const week = weekKeyOf(now)
|
|
499
|
+
const day = localDayOf(now)
|
|
500
|
+
return {
|
|
501
|
+
lastAt: Number(slot.lastAt) || 0,
|
|
502
|
+
week,
|
|
503
|
+
weekCount: slot.week === week ? Number(slot.weekCount) || 0 : 0,
|
|
504
|
+
day,
|
|
505
|
+
dayCount: slot.day === day ? Number(slot.dayCount) || 0 : 0,
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
205
509
|
/** 今天有没有读过(任一书的 lastReadAt 落在本地今天) */
|
|
206
510
|
export function readSomethingToday(st, now = Date.now()) {
|
|
207
511
|
const day = localDayOf(now)
|
|
@@ -511,6 +815,26 @@ export function readToday(st) {
|
|
|
511
815
|
return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
|
|
512
816
|
}
|
|
513
817
|
|
|
818
|
+
/** 记一格读书:全局 log + 这位读者自己的 rlog(两边都记,退章时一起退) */
|
|
819
|
+
export function bumpLog(st, t, id, readerId, inc = 1) {
|
|
820
|
+
const rid = readerId || LEGACY_READER
|
|
821
|
+
st.log = st.log || {}
|
|
822
|
+
st.log[t] = st.log[t] || {}
|
|
823
|
+
st.log[t][id] = Math.max(0, (Number(st.log[t][id]) || 0) + inc)
|
|
824
|
+
st.rlog = st.rlog || {}
|
|
825
|
+
st.rlog[t] = st.rlog[t] || {}
|
|
826
|
+
st.rlog[t][rid] = st.rlog[t][rid] || {}
|
|
827
|
+
st.rlog[t][rid][id] = Math.max(0, (Number(st.rlog[t][rid][id]) || 0) + inc)
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** 某位读者今天读了几章(按 rlog)。老账只有全局 log,所以「读书总进度」在没分片时回落到全局;具体读者记 0。 */
|
|
831
|
+
export function readTodayOf(st, readerId) {
|
|
832
|
+
const t = today()
|
|
833
|
+
const row = (st.rlog && st.rlog[t] && st.rlog[t][readerId]) || null
|
|
834
|
+
if (!row) return readerId === LEGACY_READER ? readToday(st) : 0
|
|
835
|
+
return Object.values(row).reduce((a, b) => a + (Number(b) || 0), 0)
|
|
836
|
+
}
|
|
837
|
+
|
|
514
838
|
export async function notesPath(dir) {
|
|
515
839
|
return join(dir, '读后感.md')
|
|
516
840
|
}
|
|
@@ -538,32 +862,35 @@ async function latestSessionTitle() {
|
|
|
538
862
|
|
|
539
863
|
export async function appendNote(dir, bookTitle, chapterTitle, lines, by) {
|
|
540
864
|
const p = await notesPath(dir)
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
const next = raw.slice(at0).search(/^##\s+/m)
|
|
558
|
-
if (next < 0) {
|
|
559
|
-
raw = raw.replace(/\s*$/, '') + '\n' + block
|
|
865
|
+
// 同一秒两个窗口写会丢一条:整段「读—改—写」放进锁里(锁是 p + '.lock')
|
|
866
|
+
return withFileLock(p, async () => {
|
|
867
|
+
let raw = ''
|
|
868
|
+
try { raw = await readFile(p, 'utf8') } catch {}
|
|
869
|
+
const esc = bookTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
870
|
+
let block = `\n### ${chapterTitle}\n` + lines.map((l) => `- ${l}`).join('\n') + '\n'
|
|
871
|
+
if (by) {
|
|
872
|
+
const d = new Date()
|
|
873
|
+
const pad = (n) => String(n).padStart(2, '0')
|
|
874
|
+
const ts = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
|
875
|
+
block += `- \u21b3 \u6765\u81ea\uff1a${by} \u00b7 ${ts}\n`
|
|
876
|
+
}
|
|
877
|
+
const headRe = new RegExp(`^##\\s+${esc}\\s*$`, 'm')
|
|
878
|
+
const m = headRe.exec(raw)
|
|
879
|
+
if (!m) {
|
|
880
|
+
raw = (raw.trim() ? raw.replace(/\s*$/, '') + '\n\n' : '') + `## ${bookTitle}\n` + block
|
|
560
881
|
} else {
|
|
561
|
-
const
|
|
562
|
-
|
|
882
|
+
const at0 = m.index + m[0].length
|
|
883
|
+
const next = raw.slice(at0).search(/^##\s+/m)
|
|
884
|
+
if (next < 0) {
|
|
885
|
+
raw = raw.replace(/\s*$/, '') + '\n' + block
|
|
886
|
+
} else {
|
|
887
|
+
const at = at0 + next
|
|
888
|
+
raw = raw.slice(0, at).replace(/\s*$/, '') + '\n' + block + '\n' + raw.slice(at)
|
|
889
|
+
}
|
|
563
890
|
}
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
891
|
+
await writeFile(p, raw, 'utf8')
|
|
892
|
+
return p
|
|
893
|
+
})
|
|
567
894
|
}
|
|
568
895
|
|
|
569
896
|
/* ---------------- 图片:作品与画 ------------------
|
|
@@ -741,6 +1068,55 @@ export function apply(ctx, rawConfig) {
|
|
|
741
1068
|
return out
|
|
742
1069
|
}
|
|
743
1070
|
|
|
1071
|
+
/** 这一拍是谁在读:会话 id 当读者 id,标题当名字;没有会话就是老数据那份「默认读者」。 */
|
|
1072
|
+
const READER_NAME_CACHE = new Map()
|
|
1073
|
+
/** 名字看起来就是会话 id(而不是人给的名字):这种不能拿来当读者名显示。 */
|
|
1074
|
+
function nameIsId(name, id) {
|
|
1075
|
+
const s = String(name || '').trim()
|
|
1076
|
+
if (!s || s === id) return true
|
|
1077
|
+
return /^session-[0-9a-f-]{8,}$/i.test(s)
|
|
1078
|
+
}
|
|
1079
|
+
async function readerOf(exec) {
|
|
1080
|
+
const sid = exec?.agent?.session?.id || exec?.agent?.id || ''
|
|
1081
|
+
if (!sid) return { id: LEGACY_READER, name: LEGACY_READER_NAME }
|
|
1082
|
+
let name = READER_NAME_CACHE.get(sid)
|
|
1083
|
+
if (!name) {
|
|
1084
|
+
const header = exec?.agent?.session?.header || {}
|
|
1085
|
+
name = header.title || exec?.agent?.session?.title || ''
|
|
1086
|
+
if (nameIsId(name, sid)) name = await sessionTitleOf(sid)
|
|
1087
|
+
if (nameIsId(name, sid)) name = '会话 ' + String(sid).slice(-8)
|
|
1088
|
+
READER_NAME_CACHE.set(sid, name)
|
|
1089
|
+
READER_NAMES.set(String(sid), name)
|
|
1090
|
+
}
|
|
1091
|
+
return { id: String(sid), name }
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
/** 面板用的读者一览:顺手把「名字还存成会话 id」的那些补成真名字,并写回 state。 */
|
|
1095
|
+
async function readersFor(dir, st) {
|
|
1096
|
+
const list = readerSummary(st)
|
|
1097
|
+
let fixed = false
|
|
1098
|
+
for (const r of list) {
|
|
1099
|
+
if (r.id === LEGACY_READER) continue
|
|
1100
|
+
if (!nameIsId(r.name, r.id)) continue
|
|
1101
|
+
let real = await sessionTitleOf(r.id)
|
|
1102
|
+
if (nameIsId(real, r.id)) real = '会话 ' + String(r.id).slice(-8)
|
|
1103
|
+
r.name = real
|
|
1104
|
+
if (st.readers?.[r.id]) st.readers[r.id].name = real
|
|
1105
|
+
READER_NAME_CACHE.set(r.id, real)
|
|
1106
|
+
READER_NAMES.set(r.id, real)
|
|
1107
|
+
fixed = true
|
|
1108
|
+
}
|
|
1109
|
+
if (fixed) await saveState(dir, st)
|
|
1110
|
+
return list
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/** 面板传过来的读者(下拉选的);没有就用默认读者 */
|
|
1114
|
+
function readerParam(st, url) {
|
|
1115
|
+
const asked = String(url.searchParams.get('reader') || '').trim()
|
|
1116
|
+
if (asked && st.readers && st.readers[asked]) return { id: asked, name: st.readers[asked].name || asked }
|
|
1117
|
+
return { id: LEGACY_READER, name: (st.readers?.[LEGACY_READER]?.name) || LEGACY_READER_NAME }
|
|
1118
|
+
}
|
|
1119
|
+
|
|
744
1120
|
/** 只投那一句;成功才返回 { ok, at } */
|
|
745
1121
|
async function deliverStudy(sessionId) {
|
|
746
1122
|
const agent = await resolveAgent(sessionId)
|
|
@@ -769,26 +1145,43 @@ export function apply(ctx, rawConfig) {
|
|
|
769
1145
|
studyBusy = true
|
|
770
1146
|
try {
|
|
771
1147
|
const cfgNow = await config()
|
|
772
|
-
if (cfgNow.studyEnabled !== true) return
|
|
773
1148
|
const dir = cfgNow.dir
|
|
774
1149
|
const st = await loadState(dir)
|
|
775
1150
|
const now = Date.now()
|
|
776
|
-
const study = studyStateOf(st, now)
|
|
777
1151
|
if (readSomethingToday(st, now)) return
|
|
778
|
-
const
|
|
779
|
-
|
|
780
|
-
const
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
1152
|
+
const slots = studySlotsOf(st, cfgNow)
|
|
1153
|
+
let changed = false
|
|
1154
|
+
for (const slot of slots) {
|
|
1155
|
+
if (slot.enabled !== true) continue
|
|
1156
|
+
const w = studyWindowOf(slotCfgOf(slot))
|
|
1157
|
+
if (!w) continue
|
|
1158
|
+
if (!inStudyWindow(w, new Date(now))) continue
|
|
1159
|
+
const counters = slotStudyOf(slot, now)
|
|
1160
|
+
const sessionId = slot.session || await newestSessionId(SESSIONS_ROOT)
|
|
1161
|
+
if (!sessionId) continue
|
|
1162
|
+
const timeline = await readTimeline(SESSIONS_ROOT, sessionId, { tailFrames: 200 })
|
|
1163
|
+
const verdict = decideStudy({ cfg: slotCfgOf(slot), study: counters, now, timeline })
|
|
1164
|
+
if (!verdict.ok) continue
|
|
1165
|
+
const sent = await deliverStudy(sessionId)
|
|
1166
|
+
if (!sent.ok) continue
|
|
1167
|
+
slot.lastAt = sent.at
|
|
1168
|
+
slot.week = counters.week
|
|
1169
|
+
slot.weekCount = counters.weekCount + 1
|
|
1170
|
+
slot.day = counters.day
|
|
1171
|
+
slot.dayCount = counters.dayCount + 1
|
|
1172
|
+
changed = true
|
|
1173
|
+
}
|
|
1174
|
+
if (!changed) return
|
|
785
1175
|
await ensureDir(dir)
|
|
786
|
-
st.study = {
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
1176
|
+
st.study = { ...(st.study || {}), slots }
|
|
1177
|
+
// 顶上那几个旧字段跟着第一条走,面板/老代码读到的不至于错乱
|
|
1178
|
+
const first = slots[0]
|
|
1179
|
+
if (first) {
|
|
1180
|
+
st.study.lastAt = first.lastAt
|
|
1181
|
+
st.study.week = first.week
|
|
1182
|
+
st.study.weekCount = first.weekCount
|
|
1183
|
+
st.study.day = first.day
|
|
1184
|
+
st.study.dayCount = first.dayCount
|
|
792
1185
|
}
|
|
793
1186
|
await saveState(dir, st)
|
|
794
1187
|
} catch {
|
|
@@ -810,10 +1203,26 @@ export function apply(ctx, rawConfig) {
|
|
|
810
1203
|
}
|
|
811
1204
|
})
|
|
812
1205
|
|
|
1206
|
+
let namesRepaired = false
|
|
813
1207
|
const stateOf = async () => {
|
|
814
1208
|
const { dir, perDay } = await config()
|
|
815
1209
|
await ensureDir(dir)
|
|
816
1210
|
const st = await loadState(dir)
|
|
1211
|
+
// 一次性把「名字存成会话 id」的读者修回标题(每个进程只做一次)
|
|
1212
|
+
if (!namesRepaired) {
|
|
1213
|
+
namesRepaired = true
|
|
1214
|
+
let fixed = false
|
|
1215
|
+
for (const [id, r] of Object.entries(st.readers || {})) {
|
|
1216
|
+
if (id === LEGACY_READER) continue
|
|
1217
|
+
if (!nameIsId(r.name, id)) { READER_NAMES.set(id, r.name); continue }
|
|
1218
|
+
let real = await sessionTitleOf(id)
|
|
1219
|
+
if (nameIsId(real, id)) real = '会话 ' + String(id).slice(-8)
|
|
1220
|
+
r.name = real
|
|
1221
|
+
READER_NAMES.set(id, real)
|
|
1222
|
+
fixed = true
|
|
1223
|
+
}
|
|
1224
|
+
if (fixed) await saveState(dir, st)
|
|
1225
|
+
}
|
|
817
1226
|
const shelf = await listBooks(dir)
|
|
818
1227
|
return { dir, perDay, st, shelf, today: today(), readToday: readToday(st) }
|
|
819
1228
|
}
|
|
@@ -821,11 +1230,16 @@ export function apply(ctx, rawConfig) {
|
|
|
821
1230
|
// 面板读取
|
|
822
1231
|
ctx.effect(() =>
|
|
823
1232
|
ctx.webServer.register({
|
|
1233
|
+
auth: sameSiteAuth,
|
|
824
1234
|
kind: 'exact',
|
|
825
1235
|
path: '/dsh-reading.state',
|
|
826
1236
|
async handler(req, res) {
|
|
827
|
-
const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
|
|
1237
|
+
const { dir, perDay, st, shelf, readToday: rt } = await stateOf()
|
|
1238
|
+
let localVersion = ''
|
|
1239
|
+
try { localVersion = JSON.parse(await readFile(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8')).version || '' } catch {}
|
|
1240
|
+
|
|
828
1241
|
const cfgNow = await config()
|
|
1242
|
+
const rid0 = readerParam(st, new URL(req.url || '/', 'http://localhost')).id
|
|
829
1243
|
const books = []
|
|
830
1244
|
for (const b of shelf) {
|
|
831
1245
|
const rec = st.books[b.id] || {}
|
|
@@ -836,6 +1250,16 @@ export function apply(ctx, rawConfig) {
|
|
|
836
1250
|
chapters = (toc && toc.chapters && toc.chapters.length) || 0
|
|
837
1251
|
} catch {}
|
|
838
1252
|
}
|
|
1253
|
+
const ownShard = readerOwnBook(st, rid0, b.id)
|
|
1254
|
+
const mineN = Number(ownShard && ownShard.readThrough) || 0
|
|
1255
|
+
let mineTitle = ''
|
|
1256
|
+
if (mineN > 0) {
|
|
1257
|
+
try {
|
|
1258
|
+
const toc = await readTocOnly(dir, b.id)
|
|
1259
|
+
const ch = toc && toc.chapters && toc.chapters[mineN - 1]
|
|
1260
|
+
mineTitle = (ch && ch.title) || ''
|
|
1261
|
+
} catch {}
|
|
1262
|
+
}
|
|
839
1263
|
books.push({
|
|
840
1264
|
id: b.id,
|
|
841
1265
|
title: rec.title || b.id,
|
|
@@ -843,6 +1267,10 @@ export function apply(ctx, rawConfig) {
|
|
|
843
1267
|
mtime: b.mtime,
|
|
844
1268
|
chapters,
|
|
845
1269
|
readThrough: rec.readThrough || 0,
|
|
1270
|
+
mineReadThrough: mineN,
|
|
1271
|
+
mineChapterTitle: mineTitle,
|
|
1272
|
+
furthest: furthestOf(st, b.id),
|
|
1273
|
+
furthestReader: furthestReaderOf(st, b.id),
|
|
846
1274
|
next: rec.next || 1,
|
|
847
1275
|
lastReadAt: rec.lastReadAt || '',
|
|
848
1276
|
current: st.current === b.id,
|
|
@@ -856,6 +1284,8 @@ export function apply(ctx, rawConfig) {
|
|
|
856
1284
|
const liveSessions = await liveSessionList()
|
|
857
1285
|
res.end(JSON.stringify({
|
|
858
1286
|
ok: true, dir, perDay, today: today(), readToday: rt, current: st.current, books, notes,
|
|
1287
|
+
version: localVersion,
|
|
1288
|
+
readers: await readersFor(dir, st), liveSessions,
|
|
859
1289
|
noteSort: Number(cfgNow.noteSort) || 0,
|
|
860
1290
|
study: {
|
|
861
1291
|
enabled: cfgNow.studyEnabled === true,
|
|
@@ -869,24 +1299,487 @@ export function apply(ctx, rawConfig) {
|
|
|
869
1299
|
dayCount: st2.dayCount,
|
|
870
1300
|
session: cfgNow.studySession || '',
|
|
871
1301
|
sessions: liveSessions,
|
|
1302
|
+
slots: studySlotsOf(st, cfgNow).map((s, i) => {
|
|
1303
|
+
const c = slotStudyOf(s, Date.now())
|
|
1304
|
+
return {
|
|
1305
|
+
id: s.id, index: i, enabled: s.enabled, from: s.from, to: s.to, mode: s.mode, per: s.per,
|
|
1306
|
+
session: s.session, sessionName: (liveSessions.find((x) => x.id === s.session) || {}).title || '',
|
|
1307
|
+
lastAt: c.lastAt, dayCount: c.dayCount, weekCount: c.weekCount,
|
|
1308
|
+
}
|
|
1309
|
+
}),
|
|
872
1310
|
},
|
|
873
1311
|
}))
|
|
874
1312
|
},
|
|
875
1313
|
}),
|
|
876
1314
|
)
|
|
877
1315
|
|
|
1316
|
+
// 保存「书房时间」列表(每条:启用/时段/频率/叫哪条会话)
|
|
1317
|
+
ctx.effect(() =>
|
|
1318
|
+
ctx.webServer.register({
|
|
1319
|
+
auth: sameSiteAuth,
|
|
1320
|
+
kind: 'exact',
|
|
1321
|
+
path: '/dsh-reading.restore',
|
|
1322
|
+
async handler(req, res) {
|
|
1323
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1324
|
+
const fail = (msg) => { try { res.end(JSON.stringify({ ok: false, error: String(msg) })) } catch {} }
|
|
1325
|
+
try {
|
|
1326
|
+
let body = ''
|
|
1327
|
+
for await (const c of req) body += c
|
|
1328
|
+
let j = {}
|
|
1329
|
+
try { j = JSON.parse(body || '{}') || {} } catch { return fail('不是合法的 JSON') }
|
|
1330
|
+
let src = j.json
|
|
1331
|
+
if (typeof src === 'string') { try { src = JSON.parse(src) } catch { return fail('这个文件不是半页的备份') } }
|
|
1332
|
+
if (!src || typeof src !== 'object') return fail('这个文件不是半页的备份')
|
|
1333
|
+
const prog = src.progress && typeof src.progress === 'object' ? src.progress : (src.books ? src : null)
|
|
1334
|
+
const notes = typeof src.notes === 'string' ? src.notes : ''
|
|
1335
|
+
if (!prog && !notes) return fail('文件里既没有读后感,也没有进度')
|
|
1336
|
+
if (prog && (!prog.books || typeof prog.books !== 'object')) return fail('进度里没有 books')
|
|
1337
|
+
// 防御:/dsh-reading.state 返回的 readers 是数组(给面板看的视图),若有人把那份响应当备份回灌,
|
|
1338
|
+
// 这里先把它归成 { <sid>: {name, books} },否则 state.json 会被写坏、所有分片查不到。
|
|
1339
|
+
if (prog && Array.isArray(prog.readers)) {
|
|
1340
|
+
const fixed = {}
|
|
1341
|
+
prog.readers.forEach((item, i) => {
|
|
1342
|
+
if (!item || typeof item !== 'object') return
|
|
1343
|
+
const rawId = String(item.id || '')
|
|
1344
|
+
const key = /^(session-|manual-|__legacy__)/.test(rawId) ? rawId : 'manual-restored-' + i
|
|
1345
|
+
fixed[key] = { name: String(item.name || key), books: item.books && typeof item.books === 'object' ? item.books : {} }
|
|
1346
|
+
})
|
|
1347
|
+
prog.readers = fixed
|
|
1348
|
+
}
|
|
1349
|
+
// 防御二:books 同样可能是数组(/dsh-reading.state 的响应就是数组形态),先归成 { <id>: {...} },
|
|
1350
|
+
// 否则 state.json 的 books 变成数组,之后书级 readThrough/lastReadAt 全写不进(数组挂字符串键会被 JSON 丢掉)。
|
|
1351
|
+
if (prog && Array.isArray(prog.books)) {
|
|
1352
|
+
const fixedBooks = {}
|
|
1353
|
+
for (const b of prog.books) {
|
|
1354
|
+
if (!b || typeof b !== 'object' || !b.id) continue
|
|
1355
|
+
fixedBooks[String(b.id)] = {
|
|
1356
|
+
id: String(b.id),
|
|
1357
|
+
title: String(b.title || b.id),
|
|
1358
|
+
chapters: Number(b.chapters) || 0,
|
|
1359
|
+
readThrough: Number(b.readThrough) || 0,
|
|
1360
|
+
next: Number(b.next) || 1,
|
|
1361
|
+
lastReadAt: b.lastReadAt || '',
|
|
1362
|
+
noteUntil: Number(b.noteUntil) || 0,
|
|
1363
|
+
furthest: Number(b.furthest) || Number(b.readThrough) || 0,
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
prog.books = fixedBooks
|
|
1367
|
+
}
|
|
1368
|
+
const { dir, st } = await stateOf()
|
|
1369
|
+
await ensureDir(dir)
|
|
1370
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
1371
|
+
const backups = []
|
|
1372
|
+
if (prog) {
|
|
1373
|
+
const bak = 'state.json.bak-restore-' + stamp
|
|
1374
|
+
try { await copyFile(join(dir, 'state.json'), join(dir, bak)); backups.push(bak) } catch {}
|
|
1375
|
+
const merged = {
|
|
1376
|
+
...st,
|
|
1377
|
+
current: typeof prog.current === 'string' && prog.current ? prog.current : st.current,
|
|
1378
|
+
books: prog.books,
|
|
1379
|
+
readers: prog.readers && typeof prog.readers === 'object' ? prog.readers : st.readers,
|
|
1380
|
+
log: prog.log && typeof prog.log === 'object' ? prog.log : st.log,
|
|
1381
|
+
rlog: prog.rlog && typeof prog.rlog === 'object' ? prog.rlog : st.rlog,
|
|
1382
|
+
}
|
|
1383
|
+
migrateReaders(merged)
|
|
1384
|
+
await saveState(dir, merged)
|
|
1385
|
+
}
|
|
1386
|
+
let noteLines = 0
|
|
1387
|
+
if (notes) {
|
|
1388
|
+
const np = await notesPath(dir)
|
|
1389
|
+
const bak = '读后感.md.bak-restore-' + stamp
|
|
1390
|
+
try { await copyFile(np, join(dir, bak)); backups.push(bak) } catch {}
|
|
1391
|
+
await writeFile(np, notes, 'utf8')
|
|
1392
|
+
noteLines = notes.split(/\r?\n/).filter((l) => /^[-*]\s+/.test(l)).length
|
|
1393
|
+
}
|
|
1394
|
+
res.end(JSON.stringify({ ok: true, books: prog ? Object.keys(prog.books || {}).length : 0, notes: noteLines, backups }))
|
|
1395
|
+
} catch (e) { fail((e && e.stack) || (e && e.message) || e) }
|
|
1396
|
+
},
|
|
1397
|
+
}),
|
|
1398
|
+
)
|
|
1399
|
+
|
|
1400
|
+
// 保存「书房时间」列表(每条:启用/时段/频率/叫哪条会话)
|
|
1401
|
+
ctx.effect(() =>
|
|
1402
|
+
ctx.webServer.register({
|
|
1403
|
+
auth: sameSiteAuth,
|
|
1404
|
+
kind: 'exact',
|
|
1405
|
+
path: '/dsh-reading.study',
|
|
1406
|
+
async handler(req, res) {
|
|
1407
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1408
|
+
let body = ''
|
|
1409
|
+
try { for await (const c of req) body += c } catch {}
|
|
1410
|
+
let j = {}
|
|
1411
|
+
try { j = JSON.parse(body || '{}') || {} } catch {}
|
|
1412
|
+
if (!Array.isArray(j.slots)) return res.end(JSON.stringify({ ok: false, error: 'slots 要是数组' }))
|
|
1413
|
+
const cfgNow = await config()
|
|
1414
|
+
const { dir, st } = await stateOf()
|
|
1415
|
+
const prev = studySlotsOf(st, cfgNow)
|
|
1416
|
+
const byId = new Map(prev.map((s) => [s.id, s]))
|
|
1417
|
+
const slots = j.slots.slice(0, 12).map((raw, i) => {
|
|
1418
|
+
const slot = normaliseStudySlot(raw, cfgNow, i)
|
|
1419
|
+
const old = byId.get(slot.id)
|
|
1420
|
+
if (old) {
|
|
1421
|
+
// 计数跟 id 走:改时段/换会话都不清零,删掉重加才是新的
|
|
1422
|
+
slot.lastAt = old.lastAt
|
|
1423
|
+
slot.week = old.week
|
|
1424
|
+
slot.weekCount = old.weekCount
|
|
1425
|
+
slot.day = old.day
|
|
1426
|
+
slot.dayCount = old.dayCount
|
|
1427
|
+
}
|
|
1428
|
+
return slot
|
|
1429
|
+
})
|
|
1430
|
+
await ensureDir(dir)
|
|
1431
|
+
st.study = { ...(st.study || {}), slots }
|
|
1432
|
+
const first = slots[0]
|
|
1433
|
+
if (first) {
|
|
1434
|
+
st.study.lastAt = first.lastAt
|
|
1435
|
+
st.study.week = first.week
|
|
1436
|
+
st.study.weekCount = first.weekCount
|
|
1437
|
+
st.study.day = first.day
|
|
1438
|
+
st.study.dayCount = first.dayCount
|
|
1439
|
+
}
|
|
1440
|
+
await saveState(dir, st)
|
|
1441
|
+
res.end(JSON.stringify({ ok: true, slots: slots.length }))
|
|
1442
|
+
},
|
|
1443
|
+
}),
|
|
1444
|
+
)
|
|
1445
|
+
|
|
1446
|
+
// 备份到文件:面板在 iframe 里,<a download> 不会弹保存框,所以由服务端写盘、把路径回给面板
|
|
1447
|
+
ctx.effect(() =>
|
|
1448
|
+
ctx.webServer.register({
|
|
1449
|
+
auth: sameSiteAuth,
|
|
1450
|
+
kind: 'exact',
|
|
1451
|
+
path: '/dsh-reading.backupFile',
|
|
1452
|
+
async handler(req, res) {
|
|
1453
|
+
try {
|
|
1454
|
+
const { appendFile: af } = await import('node:fs/promises')
|
|
1455
|
+
const { tmpdir: td } = await import('node:os')
|
|
1456
|
+
const { join: jn } = await import('node:path')
|
|
1457
|
+
await af(jn(td(), 'hp-backup-hit.log'), new Date().toISOString() + ' ' + req.method + ' origin=' + (req.headers.origin || '-') + ' host=' + (req.headers.host || '-') + '\n')
|
|
1458
|
+
} catch {}
|
|
1459
|
+
|
|
1460
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1461
|
+
try {
|
|
1462
|
+
const { dir, st } = await stateOf()
|
|
1463
|
+
await ensureDir(dir)
|
|
1464
|
+
let notes = ''
|
|
1465
|
+
try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
|
|
1466
|
+
const payload = { kind: 'dsh-half-page-backup', version: 1, at: new Date().toISOString(), notes, progress: st }
|
|
1467
|
+
const bdir = join(dir, 'backups')
|
|
1468
|
+
await mkdir(bdir, { recursive: true })
|
|
1469
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
|
|
1470
|
+
const out = join(bdir, '半页备份-' + stamp + '.json')
|
|
1471
|
+
const text = JSON.stringify(payload, null, 2)
|
|
1472
|
+
await writeFile(out, text, 'utf8')
|
|
1473
|
+
res.end(JSON.stringify({ ok: true, path: out, bytes: Buffer.byteLength(text) }))
|
|
1474
|
+
} catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
|
|
1475
|
+
},
|
|
1476
|
+
}),
|
|
1477
|
+
)
|
|
1478
|
+
|
|
1479
|
+
// 读一个备份文件(面板读不到本地磁盘,只能让宿主读)
|
|
1480
|
+
ctx.effect(() =>
|
|
1481
|
+
ctx.webServer.register({
|
|
1482
|
+
auth: sameSiteAuth,
|
|
1483
|
+
kind: 'exact',
|
|
1484
|
+
path: '/dsh-reading.readFile',
|
|
1485
|
+
async handler(req, res) {
|
|
1486
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1487
|
+
try {
|
|
1488
|
+
const u = new URL(req.url || '/', 'http://localhost')
|
|
1489
|
+
const p = String(u.searchParams.get('path') || '').trim().replace(/^"|"$/g, '')
|
|
1490
|
+
if (!p) throw new Error('要一个文件路径')
|
|
1491
|
+
const s2 = await stat(p)
|
|
1492
|
+
if (!s2.isFile()) throw new Error('不是文件')
|
|
1493
|
+
if (s2.size > 50 * 1024 * 1024) throw new Error('文件太大(超过 50MB)')
|
|
1494
|
+
const text = await readFile(p, 'utf8')
|
|
1495
|
+
res.end(JSON.stringify({ ok: true, text }))
|
|
1496
|
+
} catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
|
|
1497
|
+
},
|
|
1498
|
+
}),
|
|
1499
|
+
)
|
|
1500
|
+
|
|
1501
|
+
// 在资源管理器里选中一个文件(面板点「在文件夹里打开」时用)
|
|
1502
|
+
ctx.effect(() =>
|
|
1503
|
+
ctx.webServer.register({
|
|
1504
|
+
auth: sameSiteAuth,
|
|
1505
|
+
kind: 'exact',
|
|
1506
|
+
path: '/dsh-reading.reveal',
|
|
1507
|
+
async handler(req, res) {
|
|
1508
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1509
|
+
try {
|
|
1510
|
+
let body = ''
|
|
1511
|
+
for await (const c of req) body += c
|
|
1512
|
+
const j = JSON.parse(body || '{}') || {}
|
|
1513
|
+
const p = String(j.path || '').trim()
|
|
1514
|
+
if (!p) throw new Error('要一个文件路径')
|
|
1515
|
+
if (!isAbsolute(p)) throw new Error('要绝对路径')
|
|
1516
|
+
const s2 = await stat(p)
|
|
1517
|
+
if (!s2.isFile()) throw new Error('不是文件')
|
|
1518
|
+
if (process.platform === 'win32') {
|
|
1519
|
+
spawn('explorer.exe', ['/select,' + p], { detached: true, stdio: 'ignore' }).unref()
|
|
1520
|
+
} else if (process.platform === 'darwin') {
|
|
1521
|
+
spawn('open', ['-R', p], { detached: true, stdio: 'ignore' }).unref()
|
|
1522
|
+
} else {
|
|
1523
|
+
spawn('xdg-open', [dirname(p)], { detached: true, stdio: 'ignore' }).unref()
|
|
1524
|
+
}
|
|
1525
|
+
res.end(JSON.stringify({ ok: true, path: p }))
|
|
1526
|
+
} catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
|
|
1527
|
+
},
|
|
1528
|
+
}),
|
|
1529
|
+
)
|
|
1530
|
+
|
|
1531
|
+
// 查 npm 上最新版(面板「检测更新」用)
|
|
1532
|
+
const checkUpdate = async () => {
|
|
1533
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
1534
|
+
|
|
1535
|
+
let current = ''
|
|
1536
|
+
try {
|
|
1537
|
+
current = JSON.parse(await readFile(join(here, 'package.json'), 'utf8')).version || ''
|
|
1538
|
+
} catch { /* 拿不到就只说最新版 */ }
|
|
1539
|
+
let latest = ''
|
|
1540
|
+
try {
|
|
1541
|
+
const res = await fetch('https://registry.npmjs.org/dsh-half-page/latest', { headers: { accept: 'application/json' } })
|
|
1542
|
+
if (res.ok) latest = String((await res.json()).version || '')
|
|
1543
|
+
} catch { /* 离线 */ }
|
|
1544
|
+
const cmp = (a, b) => {
|
|
1545
|
+
const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0)
|
|
1546
|
+
const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0)
|
|
1547
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
|
|
1548
|
+
const d = (pa[i] || 0) - (pb[i] || 0)
|
|
1549
|
+
if (d) return d > 0 ? 1 : -1
|
|
1550
|
+
}
|
|
1551
|
+
return 0
|
|
1552
|
+
}
|
|
1553
|
+
const order = current && latest ? cmp(current, latest) : 0
|
|
1554
|
+
return { ok: true, current, latest, ahead: order > 0, outdated: order < 0, command: 'dsh plugin add dsh-half-page@latest' }
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
ctx.effect(() =>
|
|
1558
|
+
ctx.webServer.register({
|
|
1559
|
+
auth: sameSiteAuth,
|
|
1560
|
+
kind: 'exact',
|
|
1561
|
+
path: '/dsh-reading.update',
|
|
1562
|
+
async handler(req, res) {
|
|
1563
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1564
|
+
try { res.end(JSON.stringify(await checkUpdate())) } catch (e) {
|
|
1565
|
+
res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
|
|
1566
|
+
}
|
|
1567
|
+
},
|
|
1568
|
+
}),
|
|
1569
|
+
)
|
|
1570
|
+
|
|
1571
|
+
// 弹系统「另存为」对话框:让用户自己选放哪(面板在 iframe 里不能自己弹)
|
|
1572
|
+
// 对话框脚本内嵌,运行时落到临时目录:不依赖安装位置的 toolkit(换机器也能用)
|
|
1573
|
+
// 对话框脚本内嵌,运行时落到临时目录:不依赖安装位置的 toolkit(换机器也能用)
|
|
1574
|
+
const hpDialogOverlay = (mode, suggested, source) => {
|
|
1575
|
+
const q = (s) => "'" + String(s || '').replace(/'/g, "''") + "'"
|
|
1576
|
+
return [
|
|
1577
|
+
'Add-Type -AssemblyName System.Windows.Forms | Out-Null',
|
|
1578
|
+
'Add-Type -AssemblyName System.Drawing | Out-Null',
|
|
1579
|
+
`$Mode = ${q(mode)}`,
|
|
1580
|
+
`$Suggested = ${q(suggested)}`,
|
|
1581
|
+
`$Source = ${q(source)}`,
|
|
1582
|
+
'$owner = New-Object System.Windows.Forms.Form',
|
|
1583
|
+
'$owner.TopMost = $true',
|
|
1584
|
+
'$owner.ShowInTaskbar = $false',
|
|
1585
|
+
'$owner.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None',
|
|
1586
|
+
'$owner.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen',
|
|
1587
|
+
'$owner.Size = New-Object System.Drawing.Size(1,1)',
|
|
1588
|
+
'$owner.Opacity = 0',
|
|
1589
|
+
'$owner.Show()',
|
|
1590
|
+
'$owner.Activate()',
|
|
1591
|
+
'try {',
|
|
1592
|
+
' if ($Mode -eq "save") {',
|
|
1593
|
+
' $dlg = New-Object System.Windows.Forms.SaveFileDialog',
|
|
1594
|
+
' $dlg.Filter = "JSON (*.json)|*.json|All files (*.*)|*.*"',
|
|
1595
|
+
' $dlg.FileName = $Suggested',
|
|
1596
|
+
' $dlg.OverwritePrompt = $true',
|
|
1597
|
+
' } else {',
|
|
1598
|
+
' $dlg = New-Object System.Windows.Forms.OpenFileDialog',
|
|
1599
|
+
' $dlg.Filter = "JSON (*.json)|*.json|All files (*.*)|*.*"',
|
|
1600
|
+
' }',
|
|
1601
|
+
' $r = $dlg.ShowDialog($owner)',
|
|
1602
|
+
' if ($r -ne [System.Windows.Forms.DialogResult]::OK) { $owner.Close(); Write-Output "CANCELLED"; exit 0 }',
|
|
1603
|
+
' $target = $dlg.FileName',
|
|
1604
|
+
' if ($Mode -eq "save" -and $Source -ne "") { Copy-Item -LiteralPath $Source -Destination $target -Force }',
|
|
1605
|
+
' $owner.Close()',
|
|
1606
|
+
' Write-Output $target',
|
|
1607
|
+
' exit 0',
|
|
1608
|
+
'} catch {',
|
|
1609
|
+
' $owner.Close()',
|
|
1610
|
+
' Write-Output ("ERROR " + $_.Exception.Message)',
|
|
1611
|
+
' exit 1',
|
|
1612
|
+
'}',
|
|
1613
|
+
'',
|
|
1614
|
+
].join('\r\n')
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
const hpDialogLog = async (line) => {
|
|
1618
|
+
try {
|
|
1619
|
+
await appendFile(join(tmpdir(), 'hp-dialog.log'), new Date().toISOString() + ' ' + line + '\n')
|
|
1620
|
+
} catch {}
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
const runDialog = (mode, suggested, source) => new Promise((resolve2) => {
|
|
1624
|
+
let p
|
|
1625
|
+
try {
|
|
1626
|
+
const script = hpDialogOverlay(mode, suggested, source)
|
|
1627
|
+
const b64 = Buffer.from(script, 'utf16le').toString('base64')
|
|
1628
|
+
p = spawn('powershell.exe', ['-NoProfile', '-STA', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', b64], { windowsHide: true })
|
|
1629
|
+
} catch (e) {
|
|
1630
|
+
hpDialogLog('spawn-throw ' + String((e && e.message) || e))
|
|
1631
|
+
resolve2({ ok: false, error: String((e && e.message) || e) })
|
|
1632
|
+
return
|
|
1633
|
+
}
|
|
1634
|
+
let out = ''
|
|
1635
|
+
let err = ''
|
|
1636
|
+
p.stdout.on('data', (d) => { out += String(d) })
|
|
1637
|
+
p.stderr.on('data', (d) => { err += String(d) })
|
|
1638
|
+
p.on('error', (e) => {
|
|
1639
|
+
hpDialogLog('spawn-error ' + String((e && e.message) || e))
|
|
1640
|
+
resolve2({ ok: false, error: String((e && e.message) || e) })
|
|
1641
|
+
})
|
|
1642
|
+
p.on('close', (code) => {
|
|
1643
|
+
const line = out.trim().split(/\r?\n/).filter(Boolean).pop() || ''
|
|
1644
|
+
hpDialogLog('mode=' + mode + ' exit=' + code + ' out=' + JSON.stringify(line).slice(0, 200) + ' err=' + JSON.stringify(err.trim()).slice(0, 300))
|
|
1645
|
+
if (!line || line === 'CANCELLED') resolve2({ ok: false, cancelled: true })
|
|
1646
|
+
else if (line.startsWith('ERROR')) resolve2({ ok: false, error: line.slice(6).trim() })
|
|
1647
|
+
else resolve2({ ok: true, path: line })
|
|
1648
|
+
})
|
|
1649
|
+
})
|
|
1650
|
+
|
|
1651
|
+
ctx.effect(() =>
|
|
1652
|
+
ctx.webServer.register({
|
|
1653
|
+
auth: sameSiteAuth,
|
|
1654
|
+
kind: 'exact',
|
|
1655
|
+
path: '/dsh-reading.saveAs',
|
|
1656
|
+
async handler(req, res) {
|
|
1657
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1658
|
+
try {
|
|
1659
|
+
const { dir, st } = await stateOf()
|
|
1660
|
+
await ensureDir(dir)
|
|
1661
|
+
let notes = ''
|
|
1662
|
+
try { notes = await readFile(await notesPath(dir), 'utf8') } catch {}
|
|
1663
|
+
const payload = { kind: 'dsh-half-page-backup', version: 1, at: new Date().toISOString(), notes, progress: st }
|
|
1664
|
+
const tmpDir = join(dir, 'backups')
|
|
1665
|
+
await mkdir(tmpDir, { recursive: true })
|
|
1666
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
|
|
1667
|
+
const tmp = join(tmpDir, '.tmp-export-' + stamp + '.json')
|
|
1668
|
+
await writeFile(tmp, JSON.stringify(payload, null, 2), 'utf8')
|
|
1669
|
+
const name = '半页备份-' + stamp.slice(0, 10) + '.json'
|
|
1670
|
+
const r = await runDialog('save', name, tmp)
|
|
1671
|
+
try { await unlink(tmp) } catch {}
|
|
1672
|
+
res.end(JSON.stringify(r))
|
|
1673
|
+
} catch (e) { res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) })) }
|
|
1674
|
+
},
|
|
1675
|
+
}),
|
|
1676
|
+
)
|
|
1677
|
+
|
|
1678
|
+
// 弹「打开」对话框,返回选中的备份文件路径
|
|
1679
|
+
ctx.effect(() =>
|
|
1680
|
+
ctx.webServer.register({
|
|
1681
|
+
auth: sameSiteAuth,
|
|
1682
|
+
kind: 'exact',
|
|
1683
|
+
path: '/dsh-reading.pickFile',
|
|
1684
|
+
async handler(req, res) {
|
|
1685
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1686
|
+
try { res.end(JSON.stringify(await runDialog('open'))) } catch (e) {
|
|
1687
|
+
res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
|
|
1688
|
+
}
|
|
1689
|
+
},
|
|
1690
|
+
}),
|
|
1691
|
+
)
|
|
1692
|
+
|
|
1693
|
+
// 手动新增一位读者(给还没读过书的会话先占个位置;也可以纯手动起个名字)
|
|
1694
|
+
ctx.effect(() =>
|
|
1695
|
+
ctx.webServer.register({
|
|
1696
|
+
auth: sameSiteAuth,
|
|
1697
|
+
kind: 'exact',
|
|
1698
|
+
path: '/dsh-reading.addReader',
|
|
1699
|
+
async handler(req, res) {
|
|
1700
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1701
|
+
let body = ''
|
|
1702
|
+
try { for await (const c of req) body += c } catch {}
|
|
1703
|
+
let j = {}
|
|
1704
|
+
try { j = JSON.parse(body || '{}') || {} } catch {}
|
|
1705
|
+
const { dir, st } = await stateOf()
|
|
1706
|
+
migrateReaders(st)
|
|
1707
|
+
st.readers = st.readers || {}
|
|
1708
|
+
const sid = String(j.sessionId || '').trim()
|
|
1709
|
+
let name = String(j.name || '').trim()
|
|
1710
|
+
if (!sid && !name) return res.end(JSON.stringify({ ok: false, error: '要么选一条会话,要么写个名字' }))
|
|
1711
|
+
let id = sid
|
|
1712
|
+
if (!id) {
|
|
1713
|
+
// 纯手动读者:给个稳定的 id,不跟任何会话绑
|
|
1714
|
+
id = 'manual-' + Date.now().toString(36)
|
|
1715
|
+
if (!name) name = '读者 ' + id.slice(-4)
|
|
1716
|
+
} else if (!name) {
|
|
1717
|
+
const t = await sessionTitleOf(sid)
|
|
1718
|
+
name = nameIsId(t, sid) ? ('会话 ' + sid.slice(-8)) : (t || ('会话 ' + sid.slice(-8)))
|
|
1719
|
+
}
|
|
1720
|
+
if (st.readers[id]) return res.end(JSON.stringify({ ok: true, existed: true, id, name: st.readers[id].name || name }))
|
|
1721
|
+
st.readers[id] = { name, books: {}, manual: !sid }
|
|
1722
|
+
READER_NAMES.set(id, name)
|
|
1723
|
+
await saveState(dir, st)
|
|
1724
|
+
res.end(JSON.stringify({ ok: true, id, name, manual: !sid }))
|
|
1725
|
+
},
|
|
1726
|
+
}),
|
|
1727
|
+
)
|
|
1728
|
+
|
|
1729
|
+
// 把手里的书签直接接到「全机读得最远」那一步(他自己的分片,不影响别人)
|
|
1730
|
+
ctx.effect(() =>
|
|
1731
|
+
ctx.webServer.register({
|
|
1732
|
+
auth: sameSiteAuth,
|
|
1733
|
+
kind: 'exact',
|
|
1734
|
+
path: '/dsh-reading.adopt',
|
|
1735
|
+
async handler(req, res) {
|
|
1736
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1737
|
+
const url = new URL(req.url, 'http://x')
|
|
1738
|
+
const { dir, st } = await stateOf()
|
|
1739
|
+
migrateReaders(st)
|
|
1740
|
+
const id = url.searchParams.get('book') || st.current
|
|
1741
|
+
if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
|
|
1742
|
+
const reader = readerParam(st, url)
|
|
1743
|
+
const far = furthestOf(st, id)
|
|
1744
|
+
if (!far) return res.end(JSON.stringify({ ok: false, error: '这本书还没有任何进度' }))
|
|
1745
|
+
const own = readerBook(st, reader.id, id)
|
|
1746
|
+
own.readThrough = far
|
|
1747
|
+
own.next = far + 1
|
|
1748
|
+
own.lastReadAt = new Date().toISOString()
|
|
1749
|
+
st.books[id].readThrough = Math.max(Number(st.books[id].readThrough) || 0, far)
|
|
1750
|
+
st.books[id].next = Math.min(Number(st.books[id].chapters) || Infinity, far + 1)
|
|
1751
|
+
furthestOf(st, id)
|
|
1752
|
+
await saveState(dir, st)
|
|
1753
|
+
res.end(JSON.stringify({ ok: true, reader: reader.name, book: id, readThrough: far, next: far + 1 }))
|
|
1754
|
+
},
|
|
1755
|
+
}),
|
|
1756
|
+
)
|
|
1757
|
+
|
|
878
1758
|
// 把某本设为「正在读」
|
|
879
1759
|
ctx.effect(() =>
|
|
880
1760
|
ctx.webServer.register({
|
|
1761
|
+
auth: sameSiteAuth,
|
|
881
1762
|
kind: 'exact',
|
|
882
1763
|
path: '/dsh-reading.setCurrent',
|
|
883
1764
|
async handler(req, res) {
|
|
884
1765
|
const url = new URL(req.url, 'http://x')
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
if (
|
|
1766
|
+
// id 既可能来自 ?id=(老调用),也可能来自 POST 的 JSON body(面板点书名走这条)
|
|
1767
|
+
let id = url.searchParams.get('id') || ''
|
|
1768
|
+
if (!id) {
|
|
1769
|
+
let body = ''
|
|
1770
|
+
for await (const c of req) body += c
|
|
1771
|
+
try { id = String((JSON.parse(body || '{}') || {}).id || '') } catch {}
|
|
1772
|
+
}
|
|
1773
|
+
const { dir, st, shelf } = await stateOf()
|
|
1774
|
+
// 书架上的书不一定在 state.books 里(没读过就没条目),这里按书架兜底
|
|
1775
|
+
const onShelf = (shelf || []).find((b) => b && b.id === id)
|
|
1776
|
+
if (onShelf && !st.books[id]) {
|
|
1777
|
+
st.books[id] = { id, title: onShelf.id, file: onShelf.file, chapters: onShelf.chapters || 0, readThrough: 0, next: 1, lastReadAt: '' }
|
|
1778
|
+
}
|
|
1779
|
+
const exists = Boolean(st.books[id])
|
|
1780
|
+
if (exists) { st.current = id; await saveState(dir, st) }
|
|
888
1781
|
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
889
|
-
res.end(JSON.stringify({ ok:
|
|
1782
|
+
res.end(JSON.stringify({ ok: exists, current: st.current }))
|
|
890
1783
|
},
|
|
891
1784
|
}),
|
|
892
1785
|
)
|
|
@@ -894,6 +1787,7 @@ export function apply(ctx, rawConfig) {
|
|
|
894
1787
|
// 面板里直接读一章(不记账)
|
|
895
1788
|
ctx.effect(() =>
|
|
896
1789
|
ctx.webServer.register({
|
|
1790
|
+
auth: sameSiteAuth,
|
|
897
1791
|
kind: 'exact',
|
|
898
1792
|
path: '/dsh-reading.chapter',
|
|
899
1793
|
async handler(req, res) {
|
|
@@ -904,8 +1798,9 @@ export function apply(ctx, rawConfig) {
|
|
|
904
1798
|
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
905
1799
|
try {
|
|
906
1800
|
const info = await bookInfo(dir, id)
|
|
907
|
-
const
|
|
908
|
-
const
|
|
1801
|
+
const reader = readerParam(st, url)
|
|
1802
|
+
const mine = readerBookRead(st, reader.id, id)
|
|
1803
|
+
const ch = n > 0 ? Math.min(Math.max(1, n), info.chapters.length) : (mine.readThrough || 1)
|
|
909
1804
|
res.end(JSON.stringify({
|
|
910
1805
|
ok: true, book: id, chapter: ch, total: info.chapters.length,
|
|
911
1806
|
title: info.chapters[ch - 1]?.title || '', text: await chapterBody(dir, id, info, ch),
|
|
@@ -920,26 +1815,31 @@ export function apply(ctx, rawConfig) {
|
|
|
920
1815
|
// 面板里点「下一章」:记一次已读并推进
|
|
921
1816
|
ctx.effect(() =>
|
|
922
1817
|
ctx.webServer.register({
|
|
1818
|
+
auth: sameSiteAuth,
|
|
923
1819
|
kind: 'exact',
|
|
924
1820
|
path: '/dsh-reading.advance',
|
|
925
1821
|
async handler(req, res) {
|
|
926
1822
|
const url = new URL(req.url, 'http://x')
|
|
927
1823
|
const { dir, st, perDay, readToday: rt } = await stateOf()
|
|
928
1824
|
const id = url.searchParams.get('book') || st.current
|
|
929
|
-
const rec = st.books[id]
|
|
930
1825
|
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
931
|
-
if (!
|
|
1826
|
+
if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
|
|
1827
|
+
const reader = readerParam(st, url)
|
|
1828
|
+
const own = readerBook(st, reader.id, id)
|
|
1829
|
+
// 面板上点「从头读」:先把这份分片归零,再按一张张推进的方式读第 1 章
|
|
1830
|
+
if (url.searchParams.get('start') === '1') { own.readThrough = 0; own.next = 1 }
|
|
932
1831
|
const info = await bookInfo(dir, id)
|
|
933
|
-
const n = Math.min(info.chapters.length, (
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
1832
|
+
const n = Math.min(info.chapters.length, (own.readThrough || 0) + 1)
|
|
1833
|
+
own.readThrough = n
|
|
1834
|
+
own.next = Math.min(info.chapters.length, n + 1)
|
|
1835
|
+
own.lastReadAt = new Date().toISOString()
|
|
1836
|
+
st.books[id].readThrough = Math.max(Number(st.books[id].readThrough) || 0, n)
|
|
1837
|
+
st.books[id].next = Math.min(info.chapters.length, st.books[id].readThrough + 1)
|
|
1838
|
+
furthestOf(st, id)
|
|
937
1839
|
const t = today()
|
|
938
|
-
st
|
|
939
|
-
st.log[t] = st.log[t] || {}
|
|
940
|
-
st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
|
|
1840
|
+
bumpLog(st, t, id, reader.id, 1)
|
|
941
1841
|
await saveState(dir, st)
|
|
942
|
-
res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, readToday: rt + 1, perDay, left: Math.max(0, perDay - rt - 1) }))
|
|
1842
|
+
res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, readToday: rt + 1, perDay, left: Math.max(0, perDay - rt - 1), reader: reader.id, readThrough: own.readThrough }))
|
|
943
1843
|
},
|
|
944
1844
|
}),
|
|
945
1845
|
)
|
|
@@ -947,27 +1847,29 @@ export function apply(ctx, rawConfig) {
|
|
|
947
1847
|
// 面板里点「退一章」:退回上一章(手滑多点了一下能救回来)
|
|
948
1848
|
ctx.effect(() =>
|
|
949
1849
|
ctx.webServer.register({
|
|
1850
|
+
auth: sameSiteAuth,
|
|
950
1851
|
kind: 'exact',
|
|
951
1852
|
path: '/dsh-reading.back',
|
|
952
1853
|
async handler(req, res) {
|
|
953
1854
|
const url = new URL(req.url, 'http://x')
|
|
954
1855
|
const { dir, st } = await stateOf()
|
|
955
1856
|
const id = url.searchParams.get('book') || st.current
|
|
956
|
-
const rec = st.books[id]
|
|
957
1857
|
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
958
|
-
if (!
|
|
959
|
-
const
|
|
1858
|
+
if (!st.books[id]) return res.end(JSON.stringify({ ok: false, error: '没有这本书' }))
|
|
1859
|
+
const reader = readerParam(st, url)
|
|
1860
|
+
const own = readerBook(st, reader.id, id)
|
|
1861
|
+
const cur = Number(own.readThrough) || 0
|
|
960
1862
|
if (cur <= 1) return res.end(JSON.stringify({ ok: false, error: '已经在第 1 章了,退不动' }))
|
|
961
1863
|
const n = cur - 1
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
// 顺手把今天的计数退掉一格,免得「今天读了 21
|
|
1864
|
+
own.readThrough = n
|
|
1865
|
+
own.next = n + 1
|
|
1866
|
+
own.lastReadAt = new Date().toISOString()
|
|
1867
|
+
// 顺手把今天的计数退掉一格,免得「今天读了 21 章」虚高(全局与这位读者各退一格)
|
|
966
1868
|
const t = today()
|
|
967
|
-
|
|
1869
|
+
bumpLog(st, t, id, reader.id, -1)
|
|
968
1870
|
await saveState(dir, st)
|
|
969
1871
|
const info = await bookInfo(dir, id)
|
|
970
|
-
res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length }))
|
|
1872
|
+
res.end(JSON.stringify({ ok: true, chapter: n, total: info.chapters.length, reader: reader.id }))
|
|
971
1873
|
},
|
|
972
1874
|
}),
|
|
973
1875
|
)
|
|
@@ -1025,6 +1927,7 @@ async function signWork(rel, who) {
|
|
|
1025
1927
|
|
|
1026
1928
|
ctx.effect(() =>
|
|
1027
1929
|
ctx.webServer.register({
|
|
1930
|
+
auth: sameSiteAuth,
|
|
1028
1931
|
kind: 'exact',
|
|
1029
1932
|
path: '/dsh-reading.works',
|
|
1030
1933
|
async handler(req, res) {
|
|
@@ -1067,6 +1970,7 @@ async function signWork(rel, who) {
|
|
|
1067
1970
|
// 给面板读一张图(限制在上面那几个根里)
|
|
1068
1971
|
ctx.effect(() =>
|
|
1069
1972
|
ctx.webServer.register({
|
|
1973
|
+
auth: sameSiteAuth,
|
|
1070
1974
|
kind: 'exact',
|
|
1071
1975
|
path: '/dsh-reading.image',
|
|
1072
1976
|
async handler(req, res) {
|
|
@@ -1095,6 +1999,7 @@ async function signWork(rel, who) {
|
|
|
1095
1999
|
// 给一件作品署名
|
|
1096
2000
|
ctx.effect(() =>
|
|
1097
2001
|
ctx.webServer.register({
|
|
2002
|
+
auth: sameSiteAuth,
|
|
1098
2003
|
kind: 'exact',
|
|
1099
2004
|
path: '/dsh-reading.sign',
|
|
1100
2005
|
async handler(req, res) {
|
|
@@ -1120,6 +2025,7 @@ async function signWork(rel, who) {
|
|
|
1120
2025
|
// 取一个文本文件的正文(作品 / 读后感),供面板展示与复制
|
|
1121
2026
|
ctx.effect(() =>
|
|
1122
2027
|
ctx.webServer.register({
|
|
2028
|
+
auth: sameSiteAuth,
|
|
1123
2029
|
kind: 'exact',
|
|
1124
2030
|
path: '/dsh-reading.file',
|
|
1125
2031
|
async handler(req, res) {
|
|
@@ -1145,6 +2051,7 @@ async function signWork(rel, who) {
|
|
|
1145
2051
|
// 设置读写:perDay / notesEvery / quietFrom-quietTo / writing / favorites
|
|
1146
2052
|
ctx.effect(() =>
|
|
1147
2053
|
ctx.webServer.register({
|
|
2054
|
+
auth: sameSiteAuth,
|
|
1148
2055
|
kind: 'exact',
|
|
1149
2056
|
path: '/dsh-reading.config',
|
|
1150
2057
|
async handler(req, res) {
|
|
@@ -1171,6 +2078,7 @@ async function signWork(rel, who) {
|
|
|
1171
2078
|
// 面板里导入一本书(txt/md):body {path}
|
|
1172
2079
|
ctx.effect(() =>
|
|
1173
2080
|
ctx.webServer.register({
|
|
2081
|
+
auth: sameSiteAuth,
|
|
1174
2082
|
kind: 'exact',
|
|
1175
2083
|
path: '/dsh-reading.importText',
|
|
1176
2084
|
async handler(req, res) {
|
|
@@ -1194,6 +2102,7 @@ async function signWork(rel, who) {
|
|
|
1194
2102
|
|
|
1195
2103
|
ctx.effect(() =>
|
|
1196
2104
|
ctx.webServer.register({
|
|
2105
|
+
auth: sameSiteAuth,
|
|
1197
2106
|
path: '/dsh-reading.import',
|
|
1198
2107
|
async handler(req, res) {
|
|
1199
2108
|
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
@@ -1239,6 +2148,7 @@ async function signWork(rel, who) {
|
|
|
1239
2148
|
// 近况:一句状态 + 最近 7 天的读书/动笔时间线(只报事实,不编状态数值)
|
|
1240
2149
|
ctx.effect(() =>
|
|
1241
2150
|
ctx.webServer.register({
|
|
2151
|
+
auth: sameSiteAuth,
|
|
1242
2152
|
kind: 'exact',
|
|
1243
2153
|
path: '/dsh-reading.recent',
|
|
1244
2154
|
async handler(req, res) {
|
|
@@ -1248,17 +2158,69 @@ async function signWork(rel, who) {
|
|
|
1248
2158
|
let st = {}
|
|
1249
2159
|
try { st = JSON.parse(stripBom(await readFile(join(dir, 'state.json'), 'utf8'))) || {} } catch {}
|
|
1250
2160
|
const now = Date.now()
|
|
2161
|
+
migrateReaders(st)
|
|
2162
|
+
// 近况跟读者走:?reader=<rid> 给了就只报这位读者翻过的;给的是总进度就按书拆成「谁读到哪」
|
|
2163
|
+
let wanted = ''
|
|
2164
|
+
try { wanted = new URL(req.url, 'http://x').searchParams.get('reader') || '' } catch {}
|
|
2165
|
+
const readers = (st.readers && typeof st.readers === 'object') ? st.readers : {}
|
|
2166
|
+
const readerId = wanted && readers[wanted] ? wanted : ''
|
|
2167
|
+
const readerName = readerId ? (readers[readerId].name || readerId) : ''
|
|
2168
|
+
const perReader = []
|
|
2169
|
+
if (readerId) {
|
|
2170
|
+
if (readerId === LEGACY_READER) {
|
|
2171
|
+
for (const [rid, shard] of Object.entries(readers)) {
|
|
2172
|
+
if (rid === LEGACY_READER) continue
|
|
2173
|
+
const rb = (shard.books && shard.books[st.current]) || null
|
|
2174
|
+
if (!rb || !(Number(rb.readThrough) > 0)) continue
|
|
2175
|
+
perReader.push({ id: rid, name: shard.name || rid, readThrough: Number(rb.readThrough) || 0, lastReadAt: rb.lastReadAt || '' })
|
|
2176
|
+
}
|
|
2177
|
+
perReader.sort((a, b) => b.readThrough - a.readThrough)
|
|
2178
|
+
} else {
|
|
2179
|
+
const shard = readers[readerId]
|
|
2180
|
+
for (const [bid, rb] of Object.entries(shard.books || {})) {
|
|
2181
|
+
if (!(Number(rb.readThrough) > 0)) continue
|
|
2182
|
+
const bk = (st.books && st.books[bid]) || {}
|
|
2183
|
+
perReader.push({ id: bid, name: bk.title || bid, readThrough: Number(rb.readThrough) || 0, chapters: Number(bk.chapters) || 0, lastReadAt: rb.lastReadAt || '' })
|
|
2184
|
+
}
|
|
2185
|
+
perReader.sort((a, b) => String(b.lastReadAt).localeCompare(String(a.lastReadAt)))
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
1251
2188
|
const key = (t) => {
|
|
1252
2189
|
const d = new Date(t)
|
|
1253
2190
|
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 10)
|
|
1254
2191
|
}
|
|
1255
2192
|
const today = key(now)
|
|
1256
|
-
|
|
2193
|
+
// 给了读者就按读者的 rlog 记账;没给就还是全机 log
|
|
2194
|
+
let log = st.log || {}
|
|
2195
|
+
if (readerId) {
|
|
2196
|
+
const rl = st.rlog || {}
|
|
2197
|
+
log = {}
|
|
2198
|
+
for (const [k, byRid] of Object.entries(rl)) {
|
|
2199
|
+
const row = byRid && byRid[readerId]
|
|
2200
|
+
if (row) log[k] = row
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
1257
2203
|
const cur = (st.books && st.current && st.books[st.current]) || null
|
|
1258
|
-
|
|
1259
|
-
|
|
2204
|
+
// 近况说的是「这位读者最近在干什么」,不是面板上停在哪本:
|
|
2205
|
+
// 先找他最近读过的那本,找不到才用面板当前这本
|
|
2206
|
+
let focusId = st.current
|
|
2207
|
+
try {
|
|
2208
|
+
const lb = lastReadBookOf(st, readerId || LEGACY_READER)
|
|
2209
|
+
if (lb && st.books && st.books[lb]) focusId = lb
|
|
2210
|
+
} catch {}
|
|
2211
|
+
const focusRec = (st.books && st.books[focusId]) || null
|
|
2212
|
+
const ownShard = readerId && readerId !== LEGACY_READER ? readerBookRead(st, readerId, focusId) : null
|
|
2213
|
+
const view = ownShard || focusRec
|
|
2214
|
+
const todayCh = (log[today] && log[today][focusId]) || 0
|
|
2215
|
+
const lastRead = view && view.lastReadAt ? Date.parse(view.lastReadAt) : 0
|
|
1260
2216
|
const hoursAgo = lastRead ? Math.max(0, Math.round((now - lastRead) / 3600000)) : -1
|
|
1261
2217
|
|
|
2218
|
+
let lastDay = ''
|
|
2219
|
+
if (readerId) {
|
|
2220
|
+
const rl = st.rlog || {}
|
|
2221
|
+
for (const k of Object.keys(rl).sort()) { if (rl[k] && rl[k][readerId]) lastDay = k }
|
|
2222
|
+
}
|
|
2223
|
+
|
|
1262
2224
|
const days = []
|
|
1263
2225
|
for (let i = 0; i < 7; i++) {
|
|
1264
2226
|
const k = key(now - i * 86400000)
|
|
@@ -1289,20 +2251,25 @@ async function signWork(rel, who) {
|
|
|
1289
2251
|
const top = works[0] || null
|
|
1290
2252
|
|
|
1291
2253
|
let status = ''
|
|
1292
|
-
if (todayCh > 0)
|
|
2254
|
+
if (todayCh > 0) {
|
|
2255
|
+
const rawTitle = String((focusRec && focusRec.title) || focusId || '')
|
|
2256
|
+
const shownTitle = /^《/.test(rawTitle) ? rawTitle : '《' + rawTitle + '》'
|
|
2257
|
+
status = '今天在' + shownTitle + '翻了 ' + todayCh + ' 章,读到第 ' + ((view && view.readThrough) || 0) + ' 章。'
|
|
2258
|
+
}
|
|
1293
2259
|
else if (hoursAgo >= 0 && hoursAgo <= 48) status = '上次翻书是 ' + hoursAgo + ' 小时前。'
|
|
1294
2260
|
else if (hoursAgo > 48) status = '这两天没翻书。'
|
|
2261
|
+
else if (lastDay) status = '上次翻书是 ' + lastDay + '。'
|
|
1295
2262
|
if (top) {
|
|
1296
|
-
if (top.days === 0) status += '
|
|
1297
|
-
else if (top.days === 1) status += '
|
|
1298
|
-
else status += '
|
|
2263
|
+
if (top.days === 0) status += '今天有更新:《' + top.name + '》。'
|
|
2264
|
+
else if (top.days === 1) status += '昨天有更新:《' + top.name + '》。'
|
|
2265
|
+
else status += '上次更新是 ' + top.days + ' 天前的《' + top.name + '》。'
|
|
1299
2266
|
}
|
|
1300
2267
|
let mood = ''
|
|
1301
2268
|
if (todayCh >= 12) mood = '翻书翻得犯困'
|
|
1302
2269
|
else if (todayCh > 0) mood = works.some((w) => w.days === 0) ? '手痒,想写点东西' : '平静'
|
|
1303
2270
|
else if (hoursAgo < 0 || hoursAgo > 48) mood = '有点闷'
|
|
1304
2271
|
else mood = '没什么兴致'
|
|
1305
|
-
res.end(JSON.stringify({ ok: true, mood, status, today, todayChapters: todayCh, current: st.current || '', readThrough: (cur && cur.readThrough) || 0, hoursAgo, days, works: works.slice(0, 5) }))
|
|
2272
|
+
res.end(JSON.stringify({ ok: true, mood, status, today, todayChapters: todayCh, current: st.current || '', readThrough: (cur && cur.readThrough) || 0, hoursAgo, days, works: works.slice(0, 5), reader: readerId, readerName, perReader }))
|
|
1306
2273
|
} catch (e) {
|
|
1307
2274
|
res.end(JSON.stringify({ ok: false, error: String((e && e.message) || e) }))
|
|
1308
2275
|
}
|
|
@@ -1314,6 +2281,7 @@ async function signWork(rel, who) {
|
|
|
1314
2281
|
// 下架一本书:文件移到 books/.trash(可手工找回),state 记录清掉;读后感一律不动
|
|
1315
2282
|
ctx.effect(() =>
|
|
1316
2283
|
ctx.webServer.register({
|
|
2284
|
+
auth: sameSiteAuth,
|
|
1317
2285
|
kind: 'exact',
|
|
1318
2286
|
path: '/dsh-reading.removeBook',
|
|
1319
2287
|
async handler(req, res) {
|
|
@@ -1360,6 +2328,7 @@ async function signWork(rel, who) {
|
|
|
1360
2328
|
// 稿子状态:在写 / 写完了 / 搁下了(存在 reading.config.json 的 workStatus 里)
|
|
1361
2329
|
ctx.effect(() =>
|
|
1362
2330
|
ctx.webServer.register({
|
|
2331
|
+
auth: sameSiteAuth,
|
|
1363
2332
|
kind: 'exact',
|
|
1364
2333
|
path: '/dsh-reading.workstatus',
|
|
1365
2334
|
async handler(req, res) {
|
|
@@ -1388,6 +2357,7 @@ async function signWork(rel, who) {
|
|
|
1388
2357
|
// 读后感的排序方式(0=章节升 1=章节降 2=时间降),存在 reading.config.json 里
|
|
1389
2358
|
ctx.effect(() =>
|
|
1390
2359
|
ctx.webServer.register({
|
|
2360
|
+
auth: sameSiteAuth,
|
|
1391
2361
|
kind: 'exact',
|
|
1392
2362
|
path: '/dsh-reading.notesort',
|
|
1393
2363
|
async handler(req, res) {
|
|
@@ -1407,6 +2377,7 @@ async function signWork(rel, who) {
|
|
|
1407
2377
|
// 书籍状态:在读 / 已读完 / 弃坑(空 status 表示清掉)
|
|
1408
2378
|
ctx.effect(() =>
|
|
1409
2379
|
ctx.webServer.register({
|
|
2380
|
+
auth: sameSiteAuth,
|
|
1410
2381
|
kind: 'exact',
|
|
1411
2382
|
path: '/dsh-reading.bookstatus',
|
|
1412
2383
|
async handler(req, res) {
|
|
@@ -1441,7 +2412,9 @@ async function signWork(rel, who) {
|
|
|
1441
2412
|
'· 读后感不必一章一条:每读五六章写一段就够,标题会自动变成「第 23–27 章」;几千章的书也不会攒成几千条。',
|
|
1442
2413
|
'· 写读后感必须带 by(比如「鹿野」或你所在对话的名字);不带会被拒绝。面板每条下面会标出是谁写的——同一台机器上可能有好几个你,别让它们分不清。',
|
|
1443
2414
|
'· 写自己的作品也一样署名:文件开头写一行 `by: 你的名字`(或写完调 reading_sign);没署名的在面板上会标「未署名」。',
|
|
1444
|
-
'·
|
|
2415
|
+
'· 书是同一架,进度按读者分开:每条会话各有一份「读到哪」,互不踩;书上另记一个「全机读得最远」,面板里能看到谁读到哪。',
|
|
2416
|
+
'· 接着读:默认接你自己的位置;你还没读过这本书,就接全机读得最远的地方。想从别处起就传 chapter 指定章号。',
|
|
2417
|
+
'· 读哪一本由你决定,不由面板决定:面板上他选的「当前这本」只是他想看哪本,不会改变你读哪本;只有他明确说「你去读某一本」,才按他说的读。',
|
|
1445
2418
|
'· 装好之后可以问主人一次:要不要定个固定的读书时间;别自己偷偷建定时任务,也别反复问。',
|
|
1446
2419
|
].join('\n')
|
|
1447
2420
|
|
|
@@ -1483,11 +2456,13 @@ async function signWork(rel, who) {
|
|
|
1483
2456
|
+ '想知道「我现在读到哪、还能读几章」就用它。',
|
|
1484
2457
|
parameters: obj(),
|
|
1485
2458
|
output: textOut,
|
|
1486
|
-
async execute() {
|
|
2459
|
+
async execute(args, exec) {
|
|
1487
2460
|
const { dir, perDay, st, shelf, readToday: rt, today: t } = await stateOf()
|
|
2461
|
+
const reader = await readerOf(exec)
|
|
1488
2462
|
const books = []
|
|
1489
2463
|
for (const b of shelf) {
|
|
1490
2464
|
const r = st.books[b.id] || {}
|
|
2465
|
+
const mine = readerBookRead(st, reader.id, b.id)
|
|
1491
2466
|
let chapters = r.chapters || 0
|
|
1492
2467
|
if (!chapters) {
|
|
1493
2468
|
try {
|
|
@@ -1495,10 +2470,19 @@ async function signWork(rel, who) {
|
|
|
1495
2470
|
chapters = (toc && toc.chapters && toc.chapters.length) || 0
|
|
1496
2471
|
} catch {}
|
|
1497
2472
|
}
|
|
1498
|
-
books.push({
|
|
2473
|
+
books.push({
|
|
2474
|
+
id: b.id,
|
|
2475
|
+
chapters,
|
|
2476
|
+
readThrough: mine.readThrough,
|
|
2477
|
+
next: mine.next || 1,
|
|
2478
|
+
furthest: furthestOf(st, b.id),
|
|
2479
|
+
furthestReader: furthestReaderOf(st, b.id),
|
|
2480
|
+
lastReadAt: mine.lastReadAt || '',
|
|
2481
|
+
})
|
|
1499
2482
|
}
|
|
1500
2483
|
return {
|
|
1501
2484
|
dir,
|
|
2485
|
+
reader: reader.name,
|
|
1502
2486
|
today: t,
|
|
1503
2487
|
perDay,
|
|
1504
2488
|
readToday: rt,
|
|
@@ -1519,33 +2503,45 @@ async function signWork(rel, who) {
|
|
|
1519
2503
|
+ '超过每日上限时会提示,但仍允许读(上限是提醒不是锁)。'
|
|
1520
2504
|
+ '配置了静音时段时,这段时间内会被拒绝;真要读就传 force: true。',
|
|
1521
2505
|
parameters: obj({
|
|
1522
|
-
book: { type: 'string', description: '书名 id
|
|
2506
|
+
book: { type: 'string', description: '书名 id(不填=我刚读过的那本;都没读过就用书架当前那本,跟 reading_note 一致)' },
|
|
1523
2507
|
chapter: { type: 'number', description: '第几章(不填=接着上次的下一章)' },
|
|
1524
2508
|
force: { type: 'boolean', description: '静音时段内仍然要读,传 true(默认 false)' },
|
|
2509
|
+
from: { type: 'string', enum: ['me', 'book', 'start'], description: '不填 chapter 时从哪接着读:me=我上次的位置(默认)、book=这本书全机读得最远的地方、start=从头(第 1 章)' },
|
|
1525
2510
|
}),
|
|
1526
2511
|
output: textOut,
|
|
1527
|
-
async execute(args) {
|
|
2512
|
+
async execute(args, exec) {
|
|
1528
2513
|
if (args?.force !== true) {
|
|
1529
2514
|
const q = inQuietNow(await config())
|
|
1530
2515
|
if (q) throw new Error(`静音时段(${q.fromText}–${q.toText}),不自动读。真要读请传 force: true`)
|
|
1531
2516
|
}
|
|
1532
2517
|
const { dir, perDay, st, readToday: rt } = await stateOf()
|
|
1533
|
-
const
|
|
1534
|
-
|
|
2518
|
+
const reader = await readerOf(exec)
|
|
2519
|
+
// 取书口径跟 reading_note 一致:明说 > 我自己刚读的那本 > 全局当前那本
|
|
2520
|
+
const id = args?.book || lastReadBookOf(st, reader.id)
|
|
2521
|
+
if (!id) throw new Error('不知道读哪本:传 book,或先读过一本')
|
|
1535
2522
|
const info = await bookInfo(dir, id)
|
|
1536
2523
|
const rec = st.books[id] || (st.books[id] = { id, title: id, chapters: info.chapters.length, readThrough: 0, next: 1 })
|
|
1537
2524
|
rec.chapters = info.chapters.length
|
|
1538
|
-
const
|
|
2525
|
+
const own = readerBook(st, reader.id, id)
|
|
2526
|
+
// from:"start" = 明说从头读:先把自己这份归零,否则下面 max(mine, n) 会把它顶回书级进度(测试鱼 2026-11-27 测出来的)
|
|
2527
|
+
if (args?.from === 'start') { own.readThrough = 0; own.next = 1 }
|
|
2528
|
+
// 默认接着「我自己」上次的位置;我还没读过这本书就接书级的 next(换窗口能接着读)
|
|
2529
|
+
const mine = Number(own.readThrough) || 0
|
|
2530
|
+
// start=明说从头读;否则接着我自己,我没读过就接书级 next
|
|
2531
|
+
const startAt = args?.from === 'start' ? 1 : (args?.from === 'book' || !mine ? (rec.next || 1) : (own.next || mine + 1))
|
|
2532
|
+
const n = Number(args?.chapter) > 0 ? Math.floor(Number(args.chapter)) : startAt
|
|
1539
2533
|
if (n < 1 || n > info.chapters.length) throw new Error(`章号超出范围:1–${info.chapters.length}`)
|
|
1540
2534
|
const body = await chapterBody(dir, id, info, n)
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
2535
|
+
own.readThrough = Math.max(mine, n)
|
|
2536
|
+
own.next = Math.min(info.chapters.length, own.readThrough + 1)
|
|
2537
|
+
own.lastReadAt = new Date().toISOString()
|
|
2538
|
+
rec.readThrough = Math.max(Number(rec.readThrough) || 0, n)
|
|
2539
|
+
rec.next = Math.min(info.chapters.length, rec.readThrough + 1)
|
|
2540
|
+
rec.lastReadAt = own.lastReadAt
|
|
2541
|
+
furthestOf(st, id)
|
|
2542
|
+
// 读书不动「面板上正在显示的那本」:current 只在用户手动选书时改(2026-11-27)
|
|
1545
2543
|
const t = today()
|
|
1546
|
-
st
|
|
1547
|
-
st.log[t] = st.log[t] || {}
|
|
1548
|
-
st.log[t][id] = (Number(st.log[t][id]) || 0) + 1
|
|
2544
|
+
bumpLog(st, t, id, reader.id, 1)
|
|
1549
2545
|
await saveState(dir, st)
|
|
1550
2546
|
return {
|
|
1551
2547
|
book: id,
|
|
@@ -1554,7 +2550,10 @@ async function signWork(rel, who) {
|
|
|
1554
2550
|
chapters: info.chapters.length,
|
|
1555
2551
|
tocPath: info.tocPath || '',
|
|
1556
2552
|
chars: body.length,
|
|
1557
|
-
next:
|
|
2553
|
+
next: own.next,
|
|
2554
|
+
reader: reader.name,
|
|
2555
|
+
readThrough: own.readThrough,
|
|
2556
|
+
furthest: rec.furthest || own.readThrough,
|
|
1558
2557
|
perDay,
|
|
1559
2558
|
readToday: rt + 1,
|
|
1560
2559
|
left: Math.max(0, perDay - rt - 1),
|
|
@@ -1572,14 +2571,17 @@ async function signWork(rel, who) {
|
|
|
1572
2571
|
+ '适合自己把整章切出去读完之后补记——绕开 reading_next 也不会让进度停在旧章。'
|
|
1573
2572
|
+ '已读到只进不退(跳读可以,回退不会把进度改小)。',
|
|
1574
2573
|
parameters: obj({
|
|
1575
|
-
book: { type: 'string', description: '书名或书名片段,比如
|
|
2574
|
+
book: { type: 'string', description: '书名或书名片段,比如 雪中、诡秘之主(不填=我刚读过的那本)' },
|
|
1576
2575
|
chapter: { type: 'number', description: '刚读完的章号(从 1 开始)' },
|
|
1577
2576
|
todayCount: { type: 'number', description: '这一拍实际读了几章,默认 1,累加到今天的计数' },
|
|
1578
2577
|
}),
|
|
1579
2578
|
output: textOut,
|
|
1580
|
-
async execute(args) {
|
|
2579
|
+
async execute(args, exec) {
|
|
1581
2580
|
const { dir, st, shelf } = await stateOf()
|
|
1582
|
-
const
|
|
2581
|
+
const reader = await readerOf(exec)
|
|
2582
|
+
const wanted = args?.book || lastReadBookOf(st, reader.id)
|
|
2583
|
+
if (!wanted) throw new Error('不知道记哪本:传 book,或先读过一本')
|
|
2584
|
+
const id = resolveBookId(st, shelf, wanted)
|
|
1583
2585
|
// 只认已有章表里的章数;没有章表就不建,也不拦(reading_mark 不碰章表)
|
|
1584
2586
|
const toc = await readTocOnly(dir, id)
|
|
1585
2587
|
const chapters = toc ? toc.chapters.length : Number(st.books?.[id]?.chapters) || 0
|
|
@@ -1589,16 +2591,19 @@ async function signWork(rel, who) {
|
|
|
1589
2591
|
const incRaw = Math.floor(Number(args?.todayCount))
|
|
1590
2592
|
const inc = Number.isFinite(incRaw) && incRaw > 0 ? incRaw : 1
|
|
1591
2593
|
const rec = st.books[id] || (st.books[id] = { id, title: id, chapters, readThrough: 0, next: 1 })
|
|
1592
|
-
const
|
|
2594
|
+
const own = readerBook(st, reader.id, id)
|
|
2595
|
+
const before = Number(own.readThrough) || 0
|
|
1593
2596
|
if (chapters) rec.chapters = chapters
|
|
1594
|
-
|
|
2597
|
+
own.readThrough = Math.max(before, n)
|
|
2598
|
+
own.next = chapters ? Math.min(chapters, own.readThrough + 1) : own.readThrough + 1
|
|
2599
|
+
own.lastReadAt = new Date().toISOString()
|
|
2600
|
+
rec.readThrough = Math.max(Number(rec.readThrough) || 0, own.readThrough)
|
|
1595
2601
|
rec.next = chapters ? Math.min(chapters, rec.readThrough + 1) : rec.readThrough + 1
|
|
1596
|
-
rec.lastReadAt =
|
|
1597
|
-
st
|
|
2602
|
+
rec.lastReadAt = own.lastReadAt
|
|
2603
|
+
furthestOf(st, id)
|
|
2604
|
+
// 读书不动「面板上正在显示的那本」:current 只在用户手动选书时改(2026-11-27)
|
|
1598
2605
|
const t = today()
|
|
1599
|
-
st
|
|
1600
|
-
st.log[t] = st.log[t] || {}
|
|
1601
|
-
st.log[t][id] = (Number(st.log[t][id]) || 0) + inc
|
|
2606
|
+
bumpLog(st, t, id, reader.id, inc)
|
|
1602
2607
|
await saveState(dir, st)
|
|
1603
2608
|
const todayCount = Number(st.log[t][id]) || 0
|
|
1604
2609
|
// textOut 的 schema 是 object,必须返回对象(以前返回字符串,工具报 "value" must be an object)
|
|
@@ -1607,11 +2612,13 @@ async function signWork(rel, who) {
|
|
|
1607
2612
|
book: rec.title || id,
|
|
1608
2613
|
id,
|
|
1609
2614
|
before,
|
|
1610
|
-
readThrough:
|
|
1611
|
-
next:
|
|
2615
|
+
readThrough: own.readThrough,
|
|
2616
|
+
next: own.next,
|
|
1612
2617
|
chapters: chapters || null,
|
|
1613
2618
|
today: todayCount,
|
|
1614
|
-
|
|
2619
|
+
reader: reader.name,
|
|
2620
|
+
furthest: rec.furthest || own.readThrough,
|
|
2621
|
+
text: `ok readThrough ${before} -> ${own.readThrough} next ${own.next} today ${todayCount}`,
|
|
1615
2622
|
}
|
|
1616
2623
|
},
|
|
1617
2624
|
}),
|
|
@@ -1625,20 +2632,24 @@ async function signWork(rel, who) {
|
|
|
1625
2632
|
+ '默认按「上次写到哪 → 这次读到哪」自动起标题(如「第 23–27 章」),不必一章一条。'
|
|
1626
2633
|
+ '只记真的打动你的:一句话的判断、一个比喻、一处想不通。这不是交作业,想不出就不写。',
|
|
1627
2634
|
parameters: obj({
|
|
1628
|
-
book: { type: 'string', description: '书名 id
|
|
2635
|
+
book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
|
|
1629
2636
|
chapter: { type: 'string', description: '标题(不填=自动用「第 A–B 章」,A 是上次写到的下一章)' },
|
|
1630
2637
|
lines: { type: 'array', items: { type: 'string' }, description: '一到三条,每条一句,短。' },
|
|
1631
|
-
by: { type: 'string', description: '
|
|
2638
|
+
by: { type: 'string', description: '谁写的(必填,写你自己那个名字,比如「鹿野」「鹿野(DSH)」)' },
|
|
1632
2639
|
}),
|
|
1633
2640
|
output: textOut,
|
|
1634
|
-
async execute(args) {
|
|
2641
|
+
async execute(args, exec) {
|
|
1635
2642
|
const { dir, st } = await stateOf()
|
|
1636
|
-
const
|
|
1637
|
-
|
|
2643
|
+
const reader = await readerOf(exec)
|
|
2644
|
+
// 不填 book 时落到「我自己最后读过的那本」;别再拿全局 st.current——
|
|
2645
|
+
// 别人/别的窗口一读就把 current 改走了,读后感会落错书(2026-11-27 主对话测出来的)
|
|
2646
|
+
const id = args?.book || lastReadBookOf(st, reader.id)
|
|
2647
|
+
if (!id) throw new Error('不知道读哪本:传 book,或先读过一本')
|
|
1638
2648
|
const rec = st.books[id] || {}
|
|
1639
2649
|
const info = await bookInfo(dir, id)
|
|
1640
|
-
const
|
|
1641
|
-
const
|
|
2650
|
+
const own = readerBook(st, reader.id, id)
|
|
2651
|
+
const end = Number(own.readThrough) || 0
|
|
2652
|
+
const from = Number(own.noteUntil) || 0
|
|
1642
2653
|
// 默认按「一段」写:上次写到第 X 章,这次写到读到的地方,标题用「第 A–B 章」
|
|
1643
2654
|
const autoTitle = (from < end)
|
|
1644
2655
|
? (from + 1 === end ? `第 ${end} 章` : `第 ${from + 1}–${end} 章`)
|
|
@@ -1648,14 +2659,15 @@ async function signWork(rel, who) {
|
|
|
1648
2659
|
if (!lines.length) throw new Error('lines 不能为空')
|
|
1649
2660
|
const who = String(args?.by || '').trim()
|
|
1650
2661
|
if (!who) {
|
|
1651
|
-
throw new Error(
|
|
2662
|
+
throw new Error(`写读后感必须带 by(谁写的),比如 by: "${reader.name}";这不是流程,是为了让别人知道这句是谁读出来的。`)
|
|
1652
2663
|
}
|
|
1653
2664
|
const p = await appendNote(dir, rec.title || id, chTitle, lines, who)
|
|
1654
2665
|
if (end) {
|
|
1655
|
-
|
|
2666
|
+
own.noteUntil = end
|
|
2667
|
+
rec.noteUntil = Math.max(Number(rec.noteUntil) || 0, end)
|
|
1656
2668
|
await saveState(dir, st)
|
|
1657
2669
|
}
|
|
1658
|
-
return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length }
|
|
2670
|
+
return { ok: true, file: p, book: id, chapter: chTitle, lines: lines.length, reader: reader.name }
|
|
1659
2671
|
},
|
|
1660
2672
|
}),
|
|
1661
2673
|
)
|
|
@@ -1686,17 +2698,18 @@ async function signWork(rel, who) {
|
|
|
1686
2698
|
'在书里搜一个词或名字,返回它出现在第几章、那一行原文。想找“这句话在哪”“这个人第几章出场”时用它,比一页页翻省得多。',
|
|
1687
2699
|
parameters: obj({
|
|
1688
2700
|
query: { type: 'string', description: '要搜的词(人名、地名、一句话都行)' },
|
|
1689
|
-
book: { type: 'string', description: '书名 id
|
|
2701
|
+
book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
|
|
1690
2702
|
limit: { type: 'number', description: '最多几条,默认 8' },
|
|
1691
2703
|
}),
|
|
1692
2704
|
output: textOut,
|
|
1693
|
-
async execute(args) {
|
|
2705
|
+
async execute(args, exec) {
|
|
1694
2706
|
const q = String(args?.query || '').trim()
|
|
1695
2707
|
if (!q) throw new Error('需要 query')
|
|
1696
2708
|
const limit = Math.max(1, Math.min(30, Number(args?.limit) || 8))
|
|
1697
2709
|
const { dir, st } = await stateOf()
|
|
1698
|
-
const
|
|
1699
|
-
|
|
2710
|
+
const reader = await readerOf(exec)
|
|
2711
|
+
const id = args?.book || lastReadBookOf(st, reader.id)
|
|
2712
|
+
if (!id) throw new Error('不知道搜哪本:传 book,或先读过一本')
|
|
1700
2713
|
const { text, chapters } = await fullTextOf(dir, id)
|
|
1701
2714
|
const hits = []
|
|
1702
2715
|
let at = text.indexOf(q)
|
|
@@ -1730,16 +2743,18 @@ async function signWork(rel, who) {
|
|
|
1730
2743
|
description:
|
|
1731
2744
|
'把这本书已读的部分压成一页:读到第几章、读过哪些章名、每章自己写了几条批注。上一句“我读到哪了、想过什么”说不清时用它。',
|
|
1732
2745
|
parameters: obj({
|
|
1733
|
-
book: { type: 'string', description: '书名 id
|
|
2746
|
+
book: { type: 'string', description: '书名 id(不填=我刚读过的那本)' },
|
|
1734
2747
|
}),
|
|
1735
2748
|
output: textOut,
|
|
1736
|
-
async execute(args) {
|
|
2749
|
+
async execute(args, exec) {
|
|
1737
2750
|
const { dir, st } = await stateOf()
|
|
1738
|
-
const
|
|
1739
|
-
|
|
2751
|
+
const reader = await readerOf(exec)
|
|
2752
|
+
const id = args?.book || lastReadBookOf(st, reader.id)
|
|
2753
|
+
if (!id) throw new Error('不知道看哪本:传 book,或先读过一本')
|
|
1740
2754
|
const rec = st.books[id] || {}
|
|
1741
2755
|
const info = await bookInfo(dir, id)
|
|
1742
|
-
const
|
|
2756
|
+
const mine = readerBookRead(st, reader.id, id)
|
|
2757
|
+
const n = Number(mine.readThrough) || 0
|
|
1743
2758
|
const titles = info.chapters.slice(0, n).map((c, i) => ({ n: i + 1, title: c.title }))
|
|
1744
2759
|
const notes = {}
|
|
1745
2760
|
try {
|
|
@@ -1755,7 +2770,9 @@ async function signWork(rel, who) {
|
|
|
1755
2770
|
ok: true,
|
|
1756
2771
|
book: id,
|
|
1757
2772
|
title: rec.title || id,
|
|
2773
|
+
reader: reader.name,
|
|
1758
2774
|
readThrough: n,
|
|
2775
|
+
furthest: furthestOf(st, id),
|
|
1759
2776
|
total: info.chapters.length,
|
|
1760
2777
|
next: n + 1,
|
|
1761
2778
|
titles,
|
|
@@ -1764,4 +2781,4 @@ async function signWork(rel, who) {
|
|
|
1764
2781
|
},
|
|
1765
2782
|
}),
|
|
1766
2783
|
)
|
|
1767
|
-
}
|
|
2784
|
+
}
|