dsh-lamplit 0.0.0-stage → 0.1.2

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/lib/api.js ADDED
@@ -0,0 +1,749 @@
1
+ /**
2
+ * `/lamplit/api/*` 路由。
3
+ *
4
+ * 只有同源 fetch 会打到这里;不需要 CORS,也不往外网暴露额外信息。
5
+ * 响应统一 `{ok:true, ...}` / `{ok:false, code, error}`。
6
+ */
7
+ import fsp from 'node:fs/promises'
8
+ import path from 'node:path'
9
+ import crypto from 'node:crypto'
10
+
11
+ import { createAi } from './ai.js'
12
+ import { parseEpub } from './epub.js'
13
+ import { ProviderError, extractBookId } from './http.js'
14
+ import { parseMarkdown } from './markdown.js'
15
+ import { Notes, notesToMarkdown, shelfToMarkdown } from './notes.js'
16
+ import { Store } from './store.js'
17
+ import { parsePlainText } from './txt.js'
18
+ import { createFanqieProvider } from './providers/fanqie.js'
19
+ import { completeQrLogin, startQrLogin } from './vendor/weread/qr-login.js'
20
+ import { createWereadProvider } from './providers/weread.js'
21
+
22
+ const PREFIX = '/lamplit'
23
+ const MAX_BODY_BYTES = 120 * 1024 * 1024
24
+
25
+ /** PDF 分析器按需加载:没导入 PDF 的书不需要付这份启动成本。 */
26
+ let pdfAnalyzer
27
+ async function loadPdfAnalyzer() {
28
+ if (pdfAnalyzer === undefined) {
29
+ const module = await import('./pdf.js')
30
+ pdfAnalyzer = module.analyzePdf
31
+ }
32
+ return pdfAnalyzer
33
+ }
34
+
35
+ function json(payload, status = 200) {
36
+ return new Response(JSON.stringify(payload), {
37
+ status,
38
+ headers: {
39
+ 'content-type': 'application/json; charset=utf-8',
40
+ 'cache-control': 'no-store',
41
+ },
42
+ })
43
+ }
44
+
45
+ function fail(code, message, status = 400, extra = {}) {
46
+ // 额外字段在前:`details.code` 之类的上游信息不能盖住我们自己的 code。
47
+ return json({ ...extra, ok: false, code, error: message }, status)
48
+ }
49
+
50
+ function tocOf(book, chapters) {
51
+ return chapters.map((chapter, index) => ({
52
+ index,
53
+ title: chapter.title || `第 ${index + 1} 章`,
54
+ l: 1,
55
+ chars: chapter.chars ?? 0,
56
+ locked: chapter.locked === true,
57
+ }))
58
+ }
59
+
60
+ function stripExtension(name) {
61
+ return String(name ?? '')
62
+ .replace(/\.[^.]+$/, '')
63
+ .trim()
64
+ }
65
+
66
+ function kindOf(name) {
67
+ const extension = String(name ?? '').toLowerCase().match(/\.([a-z0-9]+)$/)?.[1] ?? ''
68
+ if (extension === 'md' || extension === 'markdown' || extension === 'mdown') return 'md'
69
+ if (extension === 'txt' || extension === 'text') return 'txt'
70
+ if (extension === 'pdf') return 'pdf'
71
+ if (extension === 'epub') return 'epub'
72
+ if (extension === 'mobi' || extension === 'azw' || extension === 'azw3' || extension === 'kfx' || extension === 'lit') {
73
+ return 'kindle'
74
+ }
75
+ return ''
76
+ }
77
+
78
+ /** 从最近在读的书里挑一句 12–80 字的正文,按天固定,不重复。 */
79
+ async function dailyQuote(store) {
80
+ const books = (await store.books()).slice().sort((left, right) => (right.lastOpenedAt || right.addedAt) - (left.lastOpenedAt || left.addedAt))
81
+ const today = new Date()
82
+ const seed = today.getFullYear() * 1000 + today.getMonth() * 40 + today.getDate()
83
+ for (const book of books.slice(0, 6)) {
84
+ const loaded = await store.readBook(book.id)
85
+ const chapters = loaded?.chapters ?? []
86
+ if (chapters.length === 0) continue
87
+ const order = [chapters[book.progress?.chapterIndex ?? 0], ...chapters].filter(Boolean)
88
+ for (const chapter of order.slice(0, 8)) {
89
+ const lines = (chapter.blocks ?? [])
90
+ .filter((block) => block.t === 'p' && typeof block.x === 'string' && block.x.length >= 12 && block.x.length <= 80)
91
+ .map((block) => block.x)
92
+ if (lines.length === 0) continue
93
+ return {
94
+ text: lines[seed % lines.length],
95
+ bookId: book.id,
96
+ bookTitle: book.title,
97
+ author: book.author ?? '',
98
+ chapterTitle: chapter.title ?? '',
99
+ }
100
+ }
101
+ }
102
+ return null
103
+ }
104
+
105
+ function importedBook(parsed, { name, source = 'local', sourceId = null, format, sourceFile = null }) {
106
+ return {
107
+ title: parsed.title || stripExtension(name) || '未命名',
108
+ author: parsed.author ?? '',
109
+ source,
110
+ sourceId,
111
+ format,
112
+ sourceFile,
113
+ chapters: parsed.chapters,
114
+ }
115
+ }
116
+
117
+ export function createApi({ ctx, config = {} }) {
118
+ const store = new Store({ root: typeof config.root === 'string' && config.root !== '' ? config.root : undefined })
119
+ const notes = new Notes(store.storageDir)
120
+ const ai = createAi({ ctx })
121
+ const providers = {
122
+ weread: createWereadProvider({ readRecord: () => store.providerRecord('weread') }),
123
+ fanqie: createFanqieProvider({ readRecord: () => store.providerRecord('fanqie') }),
124
+ }
125
+
126
+ const logger = ctx?.logger
127
+
128
+ /** 扫码会话:uid → 后台登录任务的状态。 */
129
+ const qrSessions = new Map()
130
+
131
+ /**
132
+ * 在线目录清洗:去掉「封面/版权信息」这类占位章,并把连续同名章合并成最后一条
133
+ * (微信读书里常见「南山经(标题页)+ 南山经(正文)」两连,留着两个目录项很别扭)。
134
+ */
135
+ function normalizeOnlineToc(chapters) {
136
+ const skip = new Set(['封面', '版权信息', '扉页', '插页', '目录'])
137
+ const flat = (chapters || []).filter((chapter) => !skip.has(String(chapter.title || '').trim()))
138
+ const out = []
139
+ for (const chapter of flat) {
140
+ const previous = out[out.length - 1]
141
+ if (previous && String(previous.title).trim() === String(chapter.title).trim()) out[out.length - 1] = chapter
142
+ else out.push(chapter)
143
+ }
144
+ return out
145
+ }
146
+
147
+ /** 在线来源的书第一次被打开时,把目录补上(同步阶段只写 metadata)。 */
148
+ async function ensureToc(book) {
149
+ if (book.source === 'local' || !book.sourceId) return null
150
+ const provider = providers[book.source]
151
+ if (!provider) return null
152
+ const toc = await provider.toc({ bookId: book.sourceId })
153
+ const chapters = normalizeOnlineToc(toc.chapters)
154
+ await store.putBook({
155
+ id: book.id,
156
+ title: book.title,
157
+ author: book.author,
158
+ cover: book.cover,
159
+ source: book.source,
160
+ sourceId: book.sourceId,
161
+ format: 'online',
162
+ chapters: chapters.map((chapter) => ({
163
+ title: chapter.title,
164
+ chapterId: chapter.chapterId,
165
+ locked: chapter.locked === true,
166
+ blocks: null,
167
+ })),
168
+ })
169
+ return { ...toc, chapters }
170
+ }
171
+
172
+ /** 拉一次书架并把没见过的书写进书架(扫码成功后也自动跑一次)。 */
173
+ async function syncShelf(providerId) {
174
+ const provider = providers[providerId]
175
+ let shelf = []
176
+ try {
177
+ shelf = await provider.shelf()
178
+ } catch (error) {
179
+ await store.patchProvider(providerId, { error: error?.message ?? String(error) })
180
+ throw error
181
+ }
182
+ const written = await store.putOnlineBooks(providerId, shelf)
183
+ const added = written.filter((entry) => entry.created).length
184
+ const state = await store.patchProvider(providerId, { error: null, lastSyncAt: Date.now() })
185
+ return { provider: state, added, updated: written.length - added, shelf }
186
+ }
187
+
188
+ async function handle(request) {
189
+ let url
190
+ try {
191
+ url = new URL(request.url)
192
+ } catch {
193
+ return fail('BADREQ', '请求地址不合法。', 400)
194
+ }
195
+ if (!url.pathname.startsWith(PREFIX)) return fail('NOTFOUND', '没有这个接口。', 404)
196
+ const route = url.pathname.slice(PREFIX.length) || '/'
197
+ const method = request.method.toUpperCase()
198
+
199
+ try {
200
+ return await dispatch({ method, route, url, request })
201
+ } catch (error) {
202
+ if (error instanceof ProviderError) {
203
+ return fail(error.code, error.message, error.code === 'AUTH' ? 401 : 400, error.details)
204
+ }
205
+ logger?.warn?.('[lamplit] %s %s 失败:%s', method, route, error?.stack ?? String(error))
206
+ return fail('INTERNAL', error?.message ?? String(error), 500)
207
+ }
208
+ }
209
+
210
+ async function readBody(request) {
211
+ const length = Number(request.headers.get('content-length') ?? 0)
212
+ if (Number.isFinite(length) && length > MAX_BODY_BYTES) {
213
+ throw new ProviderError('BADREQ', '文件太大了(上限 120MB)。')
214
+ }
215
+ const text = await request.text()
216
+ if (text.trim() === '') return {}
217
+ try {
218
+ return JSON.parse(text)
219
+ } catch {
220
+ throw new ProviderError('BADREQ', '请求体不是合法 JSON。')
221
+ }
222
+ }
223
+
224
+ /** 解析一个文件;返回 { book, toc, warnings, pages } 或抛 ProviderError。 */
225
+ async function importBuffer(buffer, name) {
226
+ const kind = kindOf(name)
227
+ const fallbackTitle = stripExtension(name)
228
+
229
+ if (kind === 'kindle') {
230
+ throw new ProviderError(
231
+ 'FORMAT',
232
+ 'MOBI / AZW3 / KFX 是亚马逊私有容器,常规阅读器也是先转格式再读。用 Calibre 的 ebook-convert 把它转成 EPUB,再导入灯下。',
233
+ )
234
+ }
235
+ if (kind === '') throw new ProviderError('FORMAT', '支持 .md / .txt / .pdf / .epub。')
236
+
237
+ if (kind === 'md') {
238
+ const parsed = parseMarkdown(buffer.toString('utf8'), { fallbackTitle })
239
+ const book = await store.putBook(importedBook(parsed, { name, format: 'md' }))
240
+ return { book, parsed }
241
+ }
242
+ if (kind === 'txt') {
243
+ const parsed = parsePlainText(buffer.toString('utf8'), { fallbackTitle })
244
+ const book = await store.putBook(importedBook(parsed, { name, format: 'txt' }))
245
+ return { book, parsed }
246
+ }
247
+ if (kind === 'epub') {
248
+ let parsed
249
+ try {
250
+ parsed = parseEpub(buffer)
251
+ } catch (error) {
252
+ throw new ProviderError('FORMAT', `这本 EPUB 读不动:${error?.message ?? String(error)}`)
253
+ }
254
+ const book = await store.putBook(importedBook(parsed, { name, format: 'epub' }))
255
+ return { book, parsed }
256
+ }
257
+
258
+ // PDF:有文字层就排版,没有就走影印渲染。
259
+ const analyze = await loadPdfAnalyzer()
260
+ const analysis = analyze(new Uint8Array(buffer), { fallbackTitle })
261
+ if (analysis.mode === 'scan') {
262
+ const book = await store.putBook({
263
+ title: analysis.title || fallbackTitle || '影印 PDF',
264
+ author: '',
265
+ source: 'local',
266
+ sourceId: null,
267
+ format: 'pdf-scan',
268
+ chapters: [],
269
+ pages: analysis.pageCount,
270
+ })
271
+ await store.saveFile(book.id, buffer, 'pdf')
272
+ return { book: { ...book, pages: analysis.pageCount }, parsed: { chapters: [], warnings: analysis.warnings } }
273
+ }
274
+ const book = await store.putBook({
275
+ ...importedBook(analysis, { name, format: 'pdf' }),
276
+ pages: analysis.pageCount,
277
+ })
278
+ return { book, parsed: { ...analysis, warnings: analysis.warnings } }
279
+ }
280
+
281
+ async function dispatch({ method, route, url, request }) {
282
+ // ---- 状态与设置 ---------------------------------------------------------
283
+ if (method === 'GET' && route === '/api/state') {
284
+ const snapshot = await store.stateSnapshot()
285
+ const counts = await notes.counts()
286
+ return json({
287
+ ok: true,
288
+ ...snapshot,
289
+ shelf: snapshot.shelf.map((book) => ({ ...book, notes: counts.get(book.id) ?? 0 })),
290
+ })
291
+ }
292
+ if (method === 'POST' && route === '/api/settings') {
293
+ const body = await readBody(request)
294
+ const settings = await store.patchSettings(body.patch ?? body)
295
+ return json({ ok: true, settings })
296
+ }
297
+
298
+ // ---- 导入 ---------------------------------------------------------------
299
+ if (method === 'POST' && route === '/api/import') {
300
+ const body = await readBody(request)
301
+ const name = String(body.name ?? '').trim()
302
+ const base64 = String(body.dataBase64 ?? '')
303
+ if (base64 === '') throw new ProviderError('BADREQ', '文件内容是空的。')
304
+ const buffer = Buffer.from(base64, 'base64')
305
+ if (buffer.byteLength === 0) throw new ProviderError('BADREQ', '文件解码后是空的。')
306
+ const { book, parsed } = await importBuffer(buffer, name)
307
+ const loaded = await store.readBook(book.id)
308
+ return json({
309
+ ok: true,
310
+ book,
311
+ toc: tocOf(book, loaded?.chapters ?? []),
312
+ warnings: parsed.warnings ?? [],
313
+ pages: parsed.pageCount ?? book.pages ?? 0,
314
+ })
315
+ }
316
+
317
+ if (method === 'POST' && route === '/api/import-path') {
318
+ const body = await readBody(request)
319
+ const filePath = String(body.path ?? '').trim()
320
+ if (filePath === '') throw new ProviderError('BADREQ', '缺少文件路径。')
321
+ const stats = await fsp.stat(filePath).catch(() => null)
322
+ if (!stats || !stats.isFile()) throw new ProviderError('NOTFOUND', `找不到文件:${filePath}`)
323
+ if (stats.size > MAX_BODY_BYTES) throw new ProviderError('BADREQ', '文件超过 120MB。')
324
+ const buffer = await fsp.readFile(filePath)
325
+ const { book, parsed } = await importBuffer(buffer, path.basename(filePath))
326
+ const loaded = await store.readBook(book.id)
327
+ return json({ ok: true, book, toc: tocOf(book, loaded?.chapters ?? []), warnings: parsed.warnings ?? [] })
328
+ }
329
+
330
+ // 粘贴正文:番茄正文有字体反爬时的逃生口,也方便贴一段文章。
331
+ if (method === 'POST' && route === '/api/import-text') {
332
+ const body = await readBody(request)
333
+ const text = String(body.text ?? '').trim()
334
+ if (text === '') throw new ProviderError('BADREQ', '正文是空的。')
335
+ const title = String(body.title ?? '').trim() || '粘贴的一章'
336
+ const parsed = parsePlainText(text, { fallbackTitle: title, author: String(body.author ?? '').trim() })
337
+ const book = await store.putBook(importedBook(parsed, { name: `${title}.txt`, format: 'txt', source: 'local' }))
338
+ const loaded = await store.readBook(book.id)
339
+ return json({ ok: true, book, toc: tocOf(book, loaded?.chapters ?? []) })
340
+ }
341
+
342
+ // ---- 原始文件(影印 PDF 用) -------------------------------------------
343
+ const fileMatch = /^\/api\/book\/([A-Za-z0-9_]+)\/file$/.exec(route)
344
+ if (fileMatch && method === 'GET') {
345
+ const id = fileMatch[1]
346
+ const book = await store.book(id)
347
+ if (book === null) return fail('NOTFOUND', '没有这本书。', 404)
348
+ const file = store.filePath(id, 'pdf')
349
+ const stats = await fsp.stat(file).catch(() => null)
350
+ if (!stats) return fail('NOTFOUND', '这本书没有保存原始文件。', 404)
351
+ const data = await fsp.readFile(file)
352
+ const total = data.byteLength
353
+ const range = /bytes=(\d*)-(\d*)/.exec(request.headers.get('range') ?? '')
354
+ if (range) {
355
+ const start = range[1] === '' ? Math.max(total - Number(range[2] || 0), 0) : Number(range[1])
356
+ const end = range[2] === '' ? total - 1 : Math.min(Number(range[2]), total - 1)
357
+ if (start > end || start >= total) {
358
+ return new Response(null, { status: 416, headers: { 'content-range': `bytes */${total}` } })
359
+ }
360
+ const slice = data.subarray(start, end + 1)
361
+ return new Response(slice, {
362
+ status: 206,
363
+ headers: {
364
+ 'content-type': 'application/pdf',
365
+ 'content-length': String(slice.byteLength),
366
+ 'content-range': `bytes ${start}-${end}/${total}`,
367
+ 'accept-ranges': 'bytes',
368
+ 'cache-control': 'private, max-age=3600',
369
+ },
370
+ })
371
+ }
372
+ return new Response(data, {
373
+ status: 200,
374
+ headers: {
375
+ 'content-type': 'application/pdf',
376
+ 'content-length': String(total),
377
+ 'content-disposition': `inline; filename="${encodeURIComponent(book.title)}.pdf"`,
378
+ 'accept-ranges': 'bytes',
379
+ 'cache-control': 'private, max-age=3600',
380
+ },
381
+ })
382
+ }
383
+
384
+ // ---- 今日一句(从你自己在读的书里取,不编) ----------------------------
385
+ if (method === 'GET' && route === '/api/quote') {
386
+ const quote = await dailyQuote(store)
387
+ return json({ ok: true, quote })
388
+ }
389
+
390
+ // ---- 导出 ---------------------------------------------------------------
391
+ if (method === 'GET' && route === '/api/notes/export') {
392
+ const bookId = url.searchParams.get('bookId') ?? undefined
393
+ const items = await notes.list({ bookId })
394
+ const book = bookId ? await store.book(bookId) : null
395
+ const markdown = notesToMarkdown(items, { bookTitle: book?.title })
396
+ const stamp = new Date().toISOString().slice(0, 10)
397
+ return json({
398
+ ok: true,
399
+ count: items.length,
400
+ filename: `${book ? book.title : '灯下'}-笔记-${stamp}.md`,
401
+ markdown,
402
+ })
403
+ }
404
+ if (method === 'GET' && route === '/api/shelf/export') {
405
+ const shelf = (await store.books()).map((book) => ({ ...book })).sort((left, right) => (right.lastOpenedAt || right.addedAt) - (left.lastOpenedAt || left.addedAt))
406
+ const stamp = new Date().toISOString().slice(0, 10)
407
+ return json({ ok: true, filename: `灯下书单-${stamp}.md`, markdown: shelfToMarkdown(shelf) })
408
+ }
409
+
410
+ // ---- 笔记 ---------------------------------------------------------------
411
+ if (route === '/api/notes' && method === 'GET') {
412
+ const bookId = url.searchParams.get('bookId') ?? undefined
413
+ const items = await notes.list({ bookId })
414
+ return json({ ok: true, notes: items })
415
+ }
416
+ if (route === '/api/notes' && method === 'POST') {
417
+ const body = await readBody(request)
418
+ if (!body.bookId) return fail('BADREQ', '缺少 bookId。', 400)
419
+ if (String(body.quote ?? '').trim() === '' && String(body.note ?? '').trim() === '') {
420
+ return fail('BADREQ', '引文和笔记都是空的。', 400)
421
+ }
422
+ const book = await store.book(String(body.bookId))
423
+ // 章节名缺了就补上:导出和笔记列表都要靠它定位。
424
+ let chapterTitle = String(body.chapterTitle ?? '').trim()
425
+ const chapterIndex = Number(body.chapterIndex) || 0
426
+ if (chapterTitle === '') {
427
+ const loaded = await store.readBook(String(body.bookId))
428
+ chapterTitle = loaded?.chapters?.[chapterIndex]?.title ?? ''
429
+ }
430
+ const note = await notes.add({
431
+ ...body,
432
+ chapterIndex,
433
+ chapterTitle,
434
+ bookTitle: book?.title ?? '',
435
+ })
436
+ return json({ ok: true, note })
437
+ }
438
+ const noteMatch = /^\/api\/notes\/([A-Za-z0-9_]+)$/.exec(route)
439
+ if (noteMatch && method === 'DELETE') {
440
+ const removed = await notes.remove(noteMatch[1])
441
+ if (!removed) return fail('NOTFOUND', '没有这条笔记。', 404)
442
+ return json({ ok: true })
443
+ }
444
+
445
+ // ---- 划词 AI ------------------------------------------------------------
446
+ if (method === 'POST' && route === '/api/ai/ask') {
447
+ const body = await readBody(request)
448
+ // 界面只带 bookId,书名在这里补齐,提示词里才有上下文。
449
+ let bookTitle = String(body.bookTitle ?? '').trim()
450
+ if (bookTitle === '' && body.bookId) {
451
+ const book = await store.book(String(body.bookId))
452
+ bookTitle = book?.title ?? ''
453
+ }
454
+ let chapterTitle = String(body.contextTitle ?? body.chapterTitle ?? '')
455
+ if (chapterTitle === '' && body.bookId !== undefined) {
456
+ const loaded = await store.readBook(String(body.bookId))
457
+ const index = Number(body.chapterIndex)
458
+ if (Number.isFinite(index)) chapterTitle = loaded?.chapters?.[index]?.title ?? ''
459
+ }
460
+ const result = await ai.ask({
461
+ text: body.text,
462
+ mode: body.mode,
463
+ bookTitle,
464
+ chapterTitle,
465
+ })
466
+ return json({ ok: true, ...result })
467
+ }
468
+
469
+ // ---- 单本书 -------------------------------------------------------------
470
+ const bookMatch = /^\/api\/book\/([A-Za-z0-9_]+)(\/chapter\/(\d+))?(\/finished)?$/.exec(route)
471
+ if (bookMatch) {
472
+ const id = bookMatch[1]
473
+ if (bookMatch[4] && method === 'POST') {
474
+ const body = await readBody(request)
475
+ const book = await store.setFinished(id, body.finished === true)
476
+ if (book === null) return fail('NOTFOUND', '没有这本书。', 404)
477
+ return json({ ok: true, book })
478
+ }
479
+ if (bookMatch[2] && method === 'GET') {
480
+ const index = Number(bookMatch[3])
481
+ const loaded = await store.readBook(id)
482
+ if (loaded === null) return fail('NOTFOUND', '没有这本书。', 404)
483
+ const { book, chapters } = loaded
484
+ let chapter = chapters[index]
485
+ if (!chapter) return fail('NOTFOUND', `没有第 ${index + 1} 章。`, 404)
486
+
487
+ if (chapter.blocks === null) {
488
+ if (book.source === 'local') {
489
+ chapter = { ...chapter, blocks: [] }
490
+ } else {
491
+ const provider = providers[book.source]
492
+ if (!provider) throw new ProviderError('UPSTREAM', `不认识来源:${book.source}`)
493
+ const fetched = await provider.chapter({ book, chapter })
494
+ chapter = (await store.patchChapter(id, index, fetched.blocks, fetched.title)) ?? {
495
+ ...chapter,
496
+ blocks: fetched.blocks,
497
+ }
498
+ }
499
+ }
500
+ const bookNotes = await notes.list({ bookId: id })
501
+ return json({
502
+ ok: true,
503
+ book,
504
+ chapter: {
505
+ index,
506
+ title: chapter.title,
507
+ blocks: chapter.blocks ?? [],
508
+ chars: chapter.chars ?? 0,
509
+ locked: chapter.locked === true,
510
+ },
511
+ prev: index > 0 ? index - 1 : null,
512
+ next: index + 1 < chapters.length ? index + 1 : null,
513
+ total: chapters.length,
514
+ notes: bookNotes.filter((note) => note.chapterIndex === index),
515
+ })
516
+ }
517
+ if (method === 'GET') {
518
+ let loaded = await store.readBook(id)
519
+ if (loaded === null) return fail('NOTFOUND', '没有这本书。', 404)
520
+ let tocError = null
521
+ const online = loaded.book.source !== 'local'
522
+ const needsToc = loaded.chapters.length === 0
523
+ // 旧目录里可能残留「封面」或重复标题(早期同步留下的),顺手洗一遍。
524
+ const needsClean =
525
+ online &&
526
+ !needsToc &&
527
+ (new Set(['封面', '版权信息', '扉页', '插页', '目录']).has(String(loaded.chapters[0]?.title ?? '').trim()) ||
528
+ loaded.chapters.some((chapter, index) => index > 0 && String(chapter.title) === String(loaded.chapters[index - 1].title)))
529
+ if (online && (needsToc || needsClean)) {
530
+ // 同步只存了书目:第一次打开时补目录,别让用户看到一本空书。
531
+ try {
532
+ await ensureToc(loaded.book)
533
+ loaded = await store.readBook(id)
534
+ } catch (error) {
535
+ tocError = error?.message ?? String(error)
536
+ }
537
+ }
538
+ await store.touch(id)
539
+ return json({
540
+ ok: true,
541
+ book: loaded.book,
542
+ toc: tocOf(loaded.book, loaded.chapters),
543
+ chaptersReady: loaded.chapters.filter((chapter) => Array.isArray(chapter.blocks)).length,
544
+ tocError,
545
+ })
546
+ }
547
+ if (method === 'DELETE') {
548
+ const removed = await store.deleteBook(id)
549
+ if (!removed) return fail('NOTFOUND', '没有这本书。', 404)
550
+ await notes.removeBook(id)
551
+ return json({ ok: true })
552
+ }
553
+ }
554
+
555
+ if (method === 'POST' && route === '/api/progress') {
556
+ const body = await readBody(request)
557
+ const book = await store.updateProgress({
558
+ bookId: String(body.bookId ?? ''),
559
+ chapterIndex: body.chapterIndex,
560
+ percent: body.percent,
561
+ seconds: body.seconds,
562
+ })
563
+ if (book === null) return fail('NOTFOUND', '没有这本书。', 404)
564
+ return json({ ok: true, book })
565
+ }
566
+
567
+ // ---- 来源 ---------------------------------------------------------------
568
+ const providerMatch = /^\/api\/provider\/(weread|fanqie)(\/([a-z-]+))?$/.exec(route)
569
+ if (providerMatch) {
570
+ const providerId = providerMatch[1]
571
+ const provider = providers[providerId]
572
+ const action = providerMatch[3] ?? ''
573
+ if (!provider) return fail('NOTFOUND', '未知来源。', 404)
574
+
575
+ if (action === 'login' && method === 'POST') {
576
+ const body = await readBody(request)
577
+ const result = await provider.login({ cookie: String(body.cookie ?? ''), apiKey: String(body.apiKey ?? '') })
578
+ const state = await store.patchProvider(providerId, {
579
+ cookie: String(body.cookie ?? '').trim(),
580
+ apiKey: String(body.apiKey ?? '').trim(),
581
+ account: result.account ?? '',
582
+ error: null,
583
+ lastSyncAt: Date.now(),
584
+ })
585
+ return json({ ok: true, provider: state, shelfCount: result.shelfCount ?? 0 })
586
+ }
587
+
588
+ if (action === 'logout' && method === 'POST') {
589
+ const state = await store.patchProvider(providerId, { cookie: '', apiKey: '', account: '', error: null })
590
+ return json({ ok: true, provider: state })
591
+ }
592
+
593
+ if (action === 'sync' && method === 'POST') {
594
+ const result = await syncShelf(providerId)
595
+ return json({ ok: true, ...result })
596
+ }
597
+
598
+ // ---- 扫码登录(微信读书)------------------------------------------
599
+ if (providerId === 'weread' && action === 'qr-start' && method === 'POST') {
600
+ for (const [key, entry] of qrSessions) {
601
+ if (Date.now() - entry.startedAt > 6 * 60 * 1000) qrSessions.delete(key)
602
+ }
603
+ let started
604
+ try {
605
+ started = await startQrLogin(undefined)
606
+ } catch (error) {
607
+ throw new ProviderError('NET', `拿不到微信读书登录二维码:${error?.message ?? String(error)}`)
608
+ }
609
+ const entry = { status: 'waiting', startedAt: Date.now(), provider: null, error: null, added: 0 }
610
+ qrSessions.set(started.uid, entry)
611
+ completeQrLogin(started.uid, AbortSignal.timeout(240_000))
612
+ .then(async (result) => {
613
+ const vid = result.vid === undefined || result.vid === null ? '' : String(result.vid)
614
+ await store.patchProvider('weread', {
615
+ cookie: result.cookie,
616
+ apiKey: '',
617
+ account: vid === '' ? '已连接' : `账号 ${vid.slice(0, 6)}…`,
618
+ error: null,
619
+ lastSyncAt: Date.now(),
620
+ })
621
+ // 扫完先把「已登录」告诉界面,再去拉书架:70 多本要几秒,别让人干等。
622
+ entry.provider = await store.patchProvider('weread', { error: null, lastSyncAt: Date.now() })
623
+ entry.status = 'authed'
624
+ try {
625
+ entry.status = 'syncing'
626
+ const synced = await syncShelf('weread')
627
+ entry.provider = synced.provider
628
+ entry.added = synced.added
629
+ entry.status = 'done'
630
+ } catch (error) {
631
+ entry.provider = await store.patchProvider('weread', { error: error?.message ?? String(error) })
632
+ entry.status = 'done'
633
+ }
634
+ })
635
+ .catch((error) => {
636
+ if (entry.status === 'authed' || entry.status === 'syncing') {
637
+ entry.error = error?.message ?? String(error)
638
+ entry.status = 'authed'
639
+ } else {
640
+ entry.status = 'error'
641
+ entry.error = error?.message ?? String(error)
642
+ }
643
+ })
644
+ return json({ ok: true, uid: started.uid, qrSvg: started.qrSvg, expiresAt: started.expiresAt })
645
+ }
646
+
647
+ if (providerId === 'weread' && action === 'qr-status' && method === 'GET') {
648
+ const uid = url.searchParams.get('uid') ?? ''
649
+ const entry = qrSessions.get(uid)
650
+ if (!entry) return json({ ok: true, status: 'expired' })
651
+ if (entry.status === 'done') {
652
+ qrSessions.delete(uid)
653
+ return json({ ok: true, status: 'done', provider: entry.provider, added: entry.added })
654
+ }
655
+ if (entry.status === 'authed' || entry.status === 'syncing') {
656
+ return json({ ok: true, status: 'syncing', provider: entry.provider, added: entry.added })
657
+ }
658
+ if (entry.status === 'error') {
659
+ qrSessions.delete(uid)
660
+ return json({ ok: false, status: 'error', code: 'AUTH', error: entry.error })
661
+ }
662
+ return json({ ok: true, status: 'waiting' })
663
+ }
664
+
665
+ if (action === 'toc' && method === 'GET') {
666
+ const bookId = url.searchParams.get('bookId') ?? ''
667
+ if (bookId === '') return fail('BADREQ', '缺少 bookId。', 400)
668
+ const toc = await provider.toc({ bookId })
669
+ return json({ ok: true, ...toc })
670
+ }
671
+
672
+ if (action === 'open' && method === 'POST') {
673
+ const body = await readBody(request)
674
+ const raw = String(body.bookId ?? '').trim()
675
+ const bookId = providerId === 'fanqie' ? extractBookId(raw) || raw : raw
676
+ if (bookId === '') return fail('BADREQ', '缺少 bookId 或链接。', 400)
677
+ const toc = await provider.toc({ bookId })
678
+ const cleaned = normalizeOnlineToc(toc.chapters)
679
+ const book = await store.putBook({
680
+ title: body.title || toc.title || bookId,
681
+ author: body.author || toc.author || '',
682
+ cover: toc.cover ?? body.cover ?? null,
683
+ source: providerId,
684
+ sourceId: String(bookId),
685
+ format: 'online',
686
+ chapters: cleaned.map((chapter) => ({
687
+ title: chapter.title,
688
+ chapterId: chapter.chapterId,
689
+ locked: chapter.locked === true,
690
+ blocks: null,
691
+ })),
692
+ })
693
+ const loaded = await store.readBook(book.id)
694
+ return json({ ok: true, book, toc: tocOf(book, loaded?.chapters ?? []) })
695
+ }
696
+
697
+ if (action === 'search' && method === 'GET') {
698
+ const query = (url.searchParams.get('q') ?? '').trim()
699
+ if (query === '') return fail('BADREQ', '缺少关键词。', 400)
700
+ if (typeof provider.search !== 'function') {
701
+ return fail(
702
+ 'UNSUPPORTED',
703
+ providerId === 'fanqie'
704
+ ? '番茄的搜索接口有滑块验证,灯下不绕过它;请粘贴书籍链接添加。'
705
+ : '这个来源暂不支持站内搜索。',
706
+ 400,
707
+ )
708
+ }
709
+ const results = await provider.search(query)
710
+ return json({ ok: true, results })
711
+ }
712
+
713
+ return fail('NOTFOUND', `来源接口不存在:${providerId}/${action}`, 404)
714
+ }
715
+
716
+ // 诊断:宿主是不是 Electron、能不能开登录窗口。给「扫码/一键登录」用。
717
+ if (method === 'GET' && route === '/api/diag') {
718
+ let electron = null
719
+ try {
720
+ const mod = await import('electron')
721
+ const face = mod && typeof mod.default === 'object' && mod.default !== null ? mod.default : mod
722
+ electron = {
723
+ browserWindow: typeof face.BrowserWindow === 'function',
724
+ session: typeof face.session === 'object',
725
+ viaDefault: face !== mod,
726
+ keys: Object.keys(face).slice(0, 12),
727
+ }
728
+ } catch (error) {
729
+ electron = { error: String(error?.message ?? error) }
730
+ }
731
+ return json({
732
+ ok: true,
733
+ versions: { electron: process.versions.electron ?? null, node: process.versions.node },
734
+ electron,
735
+ })
736
+ }
737
+
738
+ if (method === 'GET' && route === '/api/health') {
739
+ return json({ ok: true, at: Date.now(), random: crypto.randomBytes(4).toString('hex') })
740
+ }
741
+
742
+ return fail('NOTFOUND', `没有这个接口:${method} ${route}`, 404)
743
+ }
744
+
745
+ return {
746
+ storageDir: store.storageDir,
747
+ handle,
748
+ }
749
+ }