dsh-pdf-workbench 1.3.4 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,9 @@
8
8
  * GET /pdfdesk/pdf-ref that PDF as a workspace-relative path
9
9
  * GET /pdfdesk/cover a user-provided book cover image
10
10
  * GET /pdfdesk/context how full one session's context is
11
+ * GET /pdfdesk/questions one chapter's page-mark questions
12
+ * PUT /pdfdesk/questions replace one chapter's questions
13
+ * POST /pdfdesk/print-page one Markdown product as a printable HTML page
11
14
  * POST /pdfdesk/digest summarize a chapter's conversations
12
15
  * GET /pdfdesk/vendor/<file> the reader's pdf.js build
13
16
  * POST /pdfdesk/links attach an existing session to a chapter
@@ -22,19 +25,32 @@
22
25
  * @module dsh-pdf-workbench/routes
23
26
  */
24
27
  import { execFile } from 'node:child_process'
28
+ import { randomUUID } from 'node:crypto'
29
+ import { tmpdir } from 'node:os'
25
30
  import { existsSync } from 'node:fs'
26
31
  import { copyFile, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
27
32
  import { basename, dirname, extname, isAbsolute, join, relative } from 'node:path'
28
33
 
29
34
  import { chapterArtifactDir, countArtifacts, listArtifacts, readArtifact, resolveChapter } from './artifacts.js'
30
35
  import { pathSegment, readAnnotations, seedAnnotations, writeAnnotations } from './annotations.js'
36
+ import { readQuestions, writeQuestions } from './questions.js'
37
+ import { prepareChapterText } from './chapter-text.js'
38
+ import { boundarySeq, ensureBaseSession, ensureBranchSession } from './base-session.js'
39
+ import { clearSharedPrefixCache } from './chapter-sessions.js'
40
+ import { addAttachment, attachmentsDir, listAttachments, MAX_ATTACHMENT_BYTES, removeAttachment, safeAttachmentName } from './attachments.js'
41
+ import { convertPptToPdf, isPptPath, pdfNameForPpt } from './ppt.js'
42
+ import { MAX_FONT_BYTES, downloadFont, fontStatus, installFont, readFont, removeFont } from './fonts.js'
43
+ import { createBackup, importBackup, readBackup } from './backup.js'
44
+ import { importBookArchive } from './book-import.js'
45
+ import { markdownToHtml, printPageHtml } from './print.js'
31
46
  import { PLUGIN_VERSION } from './config.js'
32
47
  import { fail, isLoopback, isSameOrigin, readJson, sendBytes, sendJson } from './http.js'
33
48
  import { loadCatalog } from './index-source.js'
34
49
  import { readPageBlocks } from './blocks.js'
35
50
  import { translatePage } from './translate.js'
36
51
  import { startChapterJob } from './translate-job.js'
37
- import { artifactPdfPath, chapterPdfPath, readPdf } from './pdf-source.js'
52
+ import { artifactPdfPath, chapterPdfPath } from './pdf-source.js'
53
+ import { sendPdfFile, fileEtag, matchesEtag } from './pdf-stream.js'
38
54
  import { checkForUpdate } from './update.js'
39
55
  import { detectEnvironment } from './environment.js'
40
56
  import { renderMarkdown } from './render.js'
@@ -285,6 +301,7 @@ async function activeLibrary() {
285
301
  const url = new URL(request.url ?? '/', 'http://localhost')
286
302
  const path = url.pathname.replace(/\/+$/, '')
287
303
 
304
+
288
305
  // Features that need a catalog stop at a clear 409 instead of inventing a
289
306
  // default library. Library management, settings, static assets and session
290
307
  // bookkeeping remain available so the user can add the first library.
@@ -294,6 +311,9 @@ async function activeLibrary() {
294
311
  || path === `${PREFIX}/qa-persona`
295
312
  || path === `${PREFIX}/deepseek-key`
296
313
  || path.startsWith(`${PREFIX}/vendor/`)
314
+ || path === `${PREFIX}/font`
315
+ || path === `${PREFIX}/font/file`
316
+ || path === `${PREFIX}/backup/settings`
297
317
  || path === `${PREFIX}/state`
298
318
  || path === `${PREFIX}/pending`
299
319
  || path === `${PREFIX}/pending/remove`
@@ -304,6 +324,222 @@ async function activeLibrary() {
304
324
  return
305
325
  }
306
326
 
327
+ if (path === `${PREFIX}/backup`) {
328
+ if (request.method !== 'POST') {
329
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
330
+ return
331
+ }
332
+ const body = await mutationBody(request, response)
333
+ if (body === undefined) return
334
+ const record = body !== null && typeof body === 'object' ? body : {}
335
+ const action = typeof record.action === 'string' ? record.action : ''
336
+ try {
337
+ if (action === 'create') {
338
+ const source = record.include !== null && typeof record.include === 'object' ? record.include : {}
339
+ const include = {
340
+ sessions: source.sessions !== false,
341
+ workspace: source.workspace !== false,
342
+ pluginState: source.pluginState !== false,
343
+ libraryData: source.libraryData !== false,
344
+ settings: source.settings === true,
345
+ fonts: source.fonts === true,
346
+ projcache: source.projcache === true,
347
+ }
348
+ let list = []
349
+ if (libraries !== undefined && typeof libraries.list === 'function') {
350
+ const rows = await libraries.list().catch(() => [])
351
+ list = (Array.isArray(rows) ? rows : []).map(row => ({ id: row.id, name: row.name, libraryDir: row.libraryDir }))
352
+ } else {
353
+ const active = await activeLibrary()
354
+ list = [{ id: active.id, name: active.name, libraryDir: active.libraryDir }]
355
+ }
356
+ const backup = await createBackup({
357
+ dataDir: config.dataDir,
358
+ libraries: list,
359
+ include,
360
+ settings: include.settings && record.settings !== null && typeof record.settings === 'object' ? record.settings : undefined,
361
+ pluginVersion: PLUGIN_VERSION,
362
+ machine: { platform: process.platform, oldHome: process.env.USERPROFILE ?? process.env.HOME ?? '' },
363
+ })
364
+ sendJson(response, 200, {
365
+ ok: true,
366
+ name: backup.name,
367
+ bytes: backup.bytes,
368
+ files: backup.files,
369
+ included: backup.manifest.included,
370
+ download: `${PREFIX}/backup/file?name=${encodeURIComponent(backup.name)}`,
371
+ })
372
+ return
373
+ }
374
+ if (action === 'inspect') {
375
+ const source = typeof record.path === 'string' ? record.path : ''
376
+ if (source === '') {
377
+ fail(response, 400, 'invalid-path', '请选择迁移包文件')
378
+ return
379
+ }
380
+ const verified = await readBackup(source)
381
+ const included = verified.manifest.included ?? {}
382
+ sendJson(response, 200, {
383
+ ok: true,
384
+ manifest: {
385
+ format: verified.manifest.format,
386
+ createdAt: verified.manifest.createdAt,
387
+ plugin: verified.manifest.plugin ?? null,
388
+ machine: verified.manifest.machine ?? null,
389
+ included,
390
+ paths: verified.manifest.paths ?? null,
391
+ files: Array.isArray(verified.manifest.files) ? verified.manifest.files.length : 0,
392
+ },
393
+ })
394
+ return
395
+ }
396
+ if (action === 'import') {
397
+ const source = typeof record.path === 'string' ? record.path : ''
398
+ if (source === '') {
399
+ fail(response, 400, 'invalid-path', '请选择迁移包文件')
400
+ return
401
+ }
402
+ const roots = record.libraryRoots !== null && typeof record.libraryRoots === 'object' ? record.libraryRoots : {}
403
+ const report = await importBackup({
404
+ archivePath: source,
405
+ dataDir: config.dataDir,
406
+ libraryRoots: Object.fromEntries(Object.entries(roots).filter(([, value]) => typeof value === 'string' && value !== '')),
407
+ strategy: typeof record.strategy === 'string' ? record.strategy : 'merge',
408
+ })
409
+ sendJson(response, 200, { ok: true, report })
410
+ return
411
+ }
412
+ fail(response, 400, 'unknown-action', `未知的迁移操作:${action}`)
413
+ } catch (error) {
414
+ const message = String(error && error.message ? error.message : error)
415
+ fail(response, 500, 'backup-failed', message)
416
+ }
417
+ return
418
+ }
419
+
420
+ if (path === `${PREFIX}/backup/settings`) {
421
+ try {
422
+ const raw = await readFile(join(config.dataDir, 'backup', 'imported-settings.json'), 'utf8')
423
+ const parsed = JSON.parse(raw)
424
+ sendJson(response, 200, { ok: true, settings: parsed !== null && typeof parsed === 'object' ? parsed : {} })
425
+ } catch {
426
+ fail(response, 404, 'missing-settings', '没有导入的浏览器设置')
427
+ }
428
+ return
429
+ }
430
+
431
+ if (path === `${PREFIX}/backup/file`) {
432
+ const name = url.searchParams.get('name') ?? ''
433
+ if (!/^dsh-workbench-backup-[0-9-]+\.zip$/.test(name)) {
434
+ fail(response, 400, 'invalid-name', '迁移包名称不合法')
435
+ return
436
+ }
437
+ try {
438
+ const bytes = await readFile(join(config.dataDir, 'backup', name))
439
+ sendBytes(response, 200, bytes, 'application/zip', `attachment; filename="${name}"`)
440
+ } catch {
441
+ fail(response, 404, 'missing-file', '找不到这个迁移包')
442
+ }
443
+ return
444
+ }
445
+
446
+ if (path === `${PREFIX}/library-import`) {
447
+ if (request.method !== 'POST') {
448
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
449
+ return
450
+ }
451
+ const body = await mutationBody(request, response)
452
+ if (body === undefined) return
453
+ const record = body !== null && typeof body === 'object' ? body : {}
454
+ const source = typeof record.path === 'string' ? record.path : ''
455
+ if (source === '') {
456
+ fail(response, 400, 'invalid-path', '请选择书籍包 ZIP 文件')
457
+ return
458
+ }
459
+ const parts = typeof record.subdir === 'string'
460
+ ? record.subdir.split(/[\\/]+/).filter(part => part !== '' && part !== '.' && part !== '..')
461
+ : []
462
+ if (typeof record.subdir === 'string' && /(^|[\\/])\.\.([\\/]|$)/.test(record.subdir)) {
463
+ fail(response, 400, 'invalid-subdir', '子目录不能包含 ..')
464
+ return
465
+ }
466
+ try {
467
+ const library = await activeLibrary()
468
+ const base = record.target === 'whole'
469
+ ? join(library.libraryDir, '整本')
470
+ : (typeof library.fragmentDir === 'string' && library.fragmentDir !== '' ? library.fragmentDir : join(library.libraryDir, '分片'))
471
+ const targetDir = parts.length === 0 ? base : join(base, ...parts)
472
+ const report = await importBookArchive({
473
+ archivePath: source,
474
+ targetDir,
475
+ strategy: typeof record.strategy === 'string' ? record.strategy : 'merge',
476
+ })
477
+ sendJson(response, 200, { ok: true, report })
478
+ } catch (error) {
479
+ fail(response, 500, 'library-import-failed', String(error && error.message ? error.message : error))
480
+ }
481
+ return
482
+ }
483
+
484
+ if (path === `${PREFIX}/font`) {
485
+ if (request.method === 'GET') {
486
+ sendJson(response, 200, { ok: true, ...(await fontStatus(config.dataDir)) })
487
+ return
488
+ }
489
+ if (request.method !== 'POST') {
490
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET 或 POST')
491
+ return
492
+ }
493
+ if (!isSameOrigin(request)) {
494
+ fail(response, 403, 'cross-origin', '拒绝跨站写入')
495
+ return
496
+ }
497
+ let body
498
+ try {
499
+ body = await readJson(request, 90 * 1024 * 1024)
500
+ } catch (error) {
501
+ fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
502
+ return
503
+ }
504
+ const record = body !== null && typeof body === 'object' ? body : {}
505
+ const action = typeof record.action === 'string' ? record.action : ''
506
+ try {
507
+ if (action === 'remove') {
508
+ sendJson(response, 200, { ok: true, ...(await removeFont(config.dataDir)) })
509
+ return
510
+ }
511
+ if (action === 'download') {
512
+ sendJson(response, 200, { ok: true, ...(await downloadFont({ dataDir: config.dataDir })) })
513
+ return
514
+ }
515
+ if (action === 'install') {
516
+ const bytes = typeof record.data === 'string' ? Buffer.from(record.data, 'base64') : Buffer.alloc(0)
517
+ sendJson(response, 200, { ok: true, ...(await installFont({ dataDir: config.dataDir, bytes })) })
518
+ return
519
+ }
520
+ fail(response, 400, 'unknown-action', `未知的字体操作:${action}`)
521
+ } catch (error) {
522
+ const reason = error !== null && error !== undefined ? error.code : ''
523
+ fail(
524
+ response,
525
+ reason === 'too-large' ? 413 : reason === 'download-failed' || reason === 'no-fetch' ? 502 : 400,
526
+ reason === 'too-large' ? 'too-large' : reason === 'download-failed' ? 'download-failed' : 'font-failed',
527
+ String(error && error.message ? error.message : error)
528
+ )
529
+ }
530
+ return
531
+ }
532
+
533
+ if (path === `${PREFIX}/font/file`) {
534
+ const bytes = await readFont(config.dataDir)
535
+ if (bytes === null) {
536
+ fail(response, 404, 'missing-font', '还没有安装手写字体')
537
+ return
538
+ }
539
+ sendBytes(response, 200, bytes, 'font/ttf', 'inline; filename="Xiaolai-Regular.ttf"')
540
+ return
541
+ }
542
+
307
543
  if (path === `${PREFIX}/qa-persona`) {
308
544
  if (request.method !== 'GET') {
309
545
  fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
@@ -472,6 +708,36 @@ async function activeLibrary() {
472
708
  return
473
709
  }
474
710
 
711
+ if (path === `${PREFIX}/print-page`) {
712
+ if (request.method !== 'POST') {
713
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
714
+ return
715
+ }
716
+ const body = await mutationBody(request, response)
717
+ if (body === undefined) return
718
+ const record = body !== null && typeof body === 'object' ? body : {}
719
+ const match = resolveChapter(await catalog(), record.book, String(record.code ?? '').toLowerCase())
720
+ if (match.ok !== true) {
721
+ fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
722
+ return
723
+ }
724
+ const name = typeof record.name === 'string' ? record.name : ''
725
+ // Only a text product can become a print page; a PDF prints itself.
726
+ if (!/\.(md|markdown|txt)$/i.test(name)) {
727
+ fail(response, 400, 'not-printable', '只有 Markdown 产物可以生成打印页')
728
+ return
729
+ }
730
+ const library = await activeLibrary()
731
+ const artifact = await readArtifact(library, match.book, match.chapter, name)
732
+ if (artifact.ok !== true) {
733
+ fail(response, artifact.reason === 'not-found' ? 404 : 400, 'print-read-failed', '读不到这个产物')
734
+ return
735
+ }
736
+ const html = printPageHtml(`${match.book.id} / ${match.chapter.code} / ${name}`, markdownToHtml(artifact.text))
737
+ sendJson(response, 200, { ok: true, title: name, html })
738
+ return
739
+ }
740
+
475
741
  if (path === `${PREFIX}/deepseek-key`) {
476
742
  if (request.method === 'GET') {
477
743
  sendJson(response, 200, { ok: true, configured: (await deepseekKey()) !== '' })
@@ -524,6 +790,128 @@ async function activeLibrary() {
524
790
  return
525
791
  }
526
792
 
793
+ if (path === `${PREFIX}/chapter-text`) {
794
+ try {
795
+ const book = url.searchParams.get('book') ?? ''
796
+ const code = (url.searchParams.get('code') ?? '').toLowerCase()
797
+ const library = await activeLibrary()
798
+ const source = await chapterPdf(library, book, code)
799
+ if (source === null) {
800
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
801
+ return
802
+ }
803
+ const result = await prepareChapterText({
804
+ script: join(config.toolsDir, 'pdf_text.py'),
805
+ source,
806
+ libraryDir: library.libraryDir,
807
+ book,
808
+ code,
809
+ refresh: url.searchParams.get('refresh') === '1',
810
+ run: (script, args) => toolOutput(script, args),
811
+ })
812
+ sendJson(response, 200, { ok: true, ...result })
813
+ } catch (error) {
814
+ const noText = error !== null && error !== undefined && error.code === 'no-text'
815
+ fail(
816
+ response,
817
+ noText ? 422 : 500,
818
+ noText ? 'no-text' : 'text-failed',
819
+ String(error && error.message ? error.message : error)
820
+ )
821
+ }
822
+ return
823
+ }
824
+
825
+ if (path === `${PREFIX}/base-session`) {
826
+ if (request.method !== 'POST') {
827
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
828
+ return
829
+ }
830
+ try {
831
+ const body = await readJson(request)
832
+ const book = typeof body.book === 'string' ? body.book : ''
833
+ const code = typeof body.code === 'string' ? body.code.toLowerCase() : ''
834
+ const mode = typeof body.mode === 'string' ? body.mode : ''
835
+ const library = await activeLibrary()
836
+ const source = await chapterPdf(library, book, code)
837
+ if (source === null) {
838
+ fail(response, 404, 'missing-file', '找不到这一章的 PDF 文件')
839
+ return
840
+ }
841
+ const info = await stat(source)
842
+ const text = await prepareChapterText({
843
+ script: join(config.toolsDir, 'pdf_text.py'),
844
+ source,
845
+ libraryDir: library.libraryDir,
846
+ book,
847
+ code,
848
+ pdf: { size: info.size, mtimeMs: Math.round(info.mtimeMs) },
849
+ run: (script, args) => toolOutput(script, args),
850
+ })
851
+ const services = typeof options.sessionServices === 'function' ? options.sessionServices() : null
852
+ if (services === null || services === undefined || services.agents === undefined || services.query === undefined) {
853
+ fail(response, 503, 'session-unavailable', '会话服务尚未就绪')
854
+ return
855
+ }
856
+ // Archiving is what keeps the base session out of the sidebar; without
857
+ // it we would create a visible conversation the user never asked for.
858
+ if (services.workspace === undefined || typeof services.workspace.archiveSession !== 'function') {
859
+ fail(response, 503, 'archive-unavailable', '会话归档服务尚未就绪')
860
+ return
861
+ }
862
+ const base = await ensureBaseSession({
863
+ agents: services.agents,
864
+ workspace: services.workspace,
865
+ sessionQuery: services.query,
866
+ libraryDir: library.libraryDir,
867
+ book,
868
+ code,
869
+ cwd: library.libraryDir,
870
+ pdf: { size: info.size, mtimeMs: Math.round(info.mtimeMs) },
871
+ textPath: text.path,
872
+ createMessage: value => ({
873
+ role: 'user',
874
+ id: `pdfdesk-${randomUUID()}`,
875
+ content: [{ type: 'text', text: value }],
876
+ source: { kind: 'user' },
877
+ }),
878
+ newId: () => `session-${randomUUID()}`,
879
+ atSeqOf: boundarySeq,
880
+ })
881
+ let branch = null
882
+ if (mode !== '') {
883
+ branch = await ensureBranchSession({
884
+ agents: services.agents,
885
+ sessionQuery: services.query,
886
+ libraryDir: library.libraryDir,
887
+ book,
888
+ code,
889
+ cwd: library.libraryDir,
890
+ manifest: base.manifest,
891
+ mode,
892
+ newId: () => `session-${randomUUID()}`,
893
+ })
894
+ }
895
+ sendJson(response, 200, {
896
+ ok: true,
897
+ base: { id: base.sessionId, created: base.created },
898
+ branch: branch === null ? null : { id: branch.sessionId, created: branch.created },
899
+ })
900
+ } catch (error) {
901
+ const reason = error !== null && error !== undefined ? error.code : ''
902
+ if (reason === 'no-text') {
903
+ fail(response, 422, 'no-text', '这一章没有可提取的文本(可能是扫描件)')
904
+ } else if (reason === 'bad-mode' || reason === 'no-base') {
905
+ fail(response, 400, String(reason), String(error && error.message ? error.message : error))
906
+ } else if (reason === 'no-boundary') {
907
+ fail(response, 409, 'no-boundary', '基础会话没有完成一个完整回合')
908
+ } else {
909
+ fail(response, 500, 'base-session-failed', String(error && error.message ? error.message : error))
910
+ }
911
+ }
912
+ return
913
+ }
914
+
527
915
  if (path === `${PREFIX}/translate-chapter`) {
528
916
  if (request.method !== 'POST') {
529
917
  fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
@@ -601,6 +989,207 @@ async function activeLibrary() {
601
989
  return
602
990
  }
603
991
 
992
+ if (path === `${PREFIX}/shared-prefix`) {
993
+ if (request.method !== 'POST') {
994
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
995
+ return
996
+ }
997
+ try {
998
+ const body = await readJson(request)
999
+ if (body === null || typeof body !== 'object' || body.action !== 'clear') {
1000
+ fail(response, 400, 'unknown-action', '未知的共享前缀操作')
1001
+ return
1002
+ }
1003
+ const library = await activeLibrary()
1004
+ const result = await clearSharedPrefixCache(library.libraryDir)
1005
+ sendJson(response, 200, { ok: true, ...result })
1006
+ } catch (error) {
1007
+ fail(response, 500, 'shared-prefix-clear-failed', String(error && error.message ? error.message : error))
1008
+ }
1009
+ return
1010
+ }
1011
+
1012
+ if (path === `${PREFIX}/attachments/file`) {
1013
+ const match = await chapterFromQuery(url)
1014
+ if (match.ok !== true) {
1015
+ fail(response, match.status, match.code, match.message)
1016
+ return
1017
+ }
1018
+ const name = safeAttachmentName(url.searchParams.get('name') ?? '')
1019
+ if (name === 'manifest.json') {
1020
+ fail(response, 404, 'missing-file', '找不到这个附件')
1021
+ return
1022
+ }
1023
+ const library = await activeLibrary()
1024
+ const dir = attachmentsDir(library.libraryDir, match.book.id, match.chapter.code)
1025
+ try {
1026
+ const body = await readFile(join(dir, name))
1027
+ const extension = extname(name).slice(1).toLowerCase()
1028
+ const type = extension === 'pdf'
1029
+ ? 'application/pdf'
1030
+ : extension === 'png' ? 'image/png'
1031
+ : extension === 'jpg' || extension === 'jpeg' ? 'image/jpeg'
1032
+ : extension === 'webp' ? 'image/webp'
1033
+ : extension === 'gif' ? 'image/gif'
1034
+ : extension === 'bmp' ? 'image/bmp'
1035
+ : 'application/octet-stream'
1036
+ sendBytes(response, 200, body, type, `inline; filename*=UTF-8''${encodeURIComponent(name)}`)
1037
+ } catch {
1038
+ fail(response, 404, 'missing-file', '找不到这个附件')
1039
+ }
1040
+ return
1041
+ }
1042
+
1043
+ if (path === `${PREFIX}/attachments`) {
1044
+ if (request.method === 'GET') {
1045
+ const match = await chapterFromQuery(url)
1046
+ if (match.ok !== true) {
1047
+ fail(response, match.status, match.code, match.message)
1048
+ return
1049
+ }
1050
+ const library = await activeLibrary()
1051
+ sendJson(response, 200, { ok: true, ...(await listAttachments(library.libraryDir, match.book.id, match.chapter.code)) })
1052
+ return
1053
+ }
1054
+ if (request.method !== 'POST') {
1055
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET 或 POST')
1056
+ return
1057
+ }
1058
+ // An upload is a base64 file body: the default 16 KB JSON limit would
1059
+ // reject every real attachment before it reached the size check.
1060
+ if (!isSameOrigin(request)) {
1061
+ fail(response, 403, 'cross-origin', '拒绝跨站写入')
1062
+ return
1063
+ }
1064
+ let body
1065
+ try {
1066
+ body = await readJson(request, 80 * 1024 * 1024)
1067
+ } catch (error) {
1068
+ fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
1069
+ return
1070
+ }
1071
+ if (body === undefined) return
1072
+ const record = body !== null && typeof body === 'object' ? body : {}
1073
+ const match = resolveChapter(await catalog(), record.book, String(record.code ?? '').toLowerCase())
1074
+ if (match.ok !== true) {
1075
+ fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
1076
+ return
1077
+ }
1078
+ try {
1079
+ const library = await activeLibrary()
1080
+ let sourcePath = typeof record.path === 'string' ? record.path : ''
1081
+ let cleanup = null
1082
+ if (sourcePath === '' && typeof record.data === 'string' && record.data !== '') {
1083
+ // Browser upload: decode into a temp file, then reuse the copy-in
1084
+ // path so naming, limits and the manifest behave identically.
1085
+ const bytes = Buffer.from(record.data, 'base64')
1086
+ if (bytes.length > MAX_ATTACHMENT_BYTES) {
1087
+ fail(response, 413, 'too-large', '附件超过 50 MB')
1088
+ return
1089
+ }
1090
+ cleanup = join(tmpdir(), `pdfdesk-upload-${randomUUID()}${extname(String(record.name ?? '')).toLowerCase()}`)
1091
+ await writeFile(cleanup, bytes)
1092
+ sourcePath = cleanup
1093
+ }
1094
+ try {
1095
+ let storedPath = sourcePath
1096
+ let pdfPath = null
1097
+ const originalName = typeof record.name === 'string' && record.name !== '' ? record.name : sourcePath
1098
+ if (isPptPath(originalName)) {
1099
+ pdfPath = join(tmpdir(), `pdfdesk-ppt-${randomUUID()}.pdf`)
1100
+ await convertPptToPdf({ source: sourcePath, outPath: pdfPath })
1101
+ storedPath = pdfPath
1102
+ }
1103
+ try {
1104
+ const item = await addAttachment({
1105
+ libraryDir: library.libraryDir,
1106
+ book: match.book.id,
1107
+ code: match.chapter.code,
1108
+ sourcePath: storedPath,
1109
+ name: pdfPath === null ? (typeof record.name === 'string' ? record.name : undefined) : pdfNameForPpt(originalName),
1110
+ })
1111
+ sendJson(response, 200, { ok: true, item })
1112
+ } finally {
1113
+ if (pdfPath !== null) await unlink(pdfPath).catch(() => {})
1114
+ }
1115
+ } finally {
1116
+ if (cleanup !== null) await unlink(cleanup).catch(() => {})
1117
+ }
1118
+ } catch (error) {
1119
+ const reason = error !== null && error !== undefined ? error.code : ''
1120
+ if (reason === 'no-converter') {
1121
+ fail(response, 503, 'no-converter', String(error.message ?? '没有可用的 PPT 转换器'))
1122
+ return
1123
+ }
1124
+ fail(
1125
+ response,
1126
+ reason === 'too-large' ? 413 : reason === 'bad-type' || reason === 'not-file' ? 400 : 500,
1127
+ reason === 'too-large' ? 'too-large' : reason === 'bad-type' ? 'bad-type' : 'attachment-add-failed',
1128
+ String(error && error.message ? error.message : error)
1129
+ )
1130
+ }
1131
+ return
1132
+ }
1133
+
1134
+ if (path === `${PREFIX}/attachments/remove`) {
1135
+ if (request.method !== 'POST') {
1136
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
1137
+ return
1138
+ }
1139
+ const body = await mutationBody(request, response)
1140
+ if (body === undefined) return
1141
+ const record = body !== null && typeof body === 'object' ? body : {}
1142
+ const match = resolveChapter(await catalog(), record.book, String(record.code ?? '').toLowerCase())
1143
+ if (match.ok !== true) {
1144
+ fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
1145
+ return
1146
+ }
1147
+ try {
1148
+ const library = await activeLibrary()
1149
+ const result = await removeAttachment({
1150
+ libraryDir: library.libraryDir,
1151
+ book: match.book.id,
1152
+ code: match.chapter.code,
1153
+ name: typeof record.name === 'string' ? record.name : '',
1154
+ })
1155
+ sendJson(response, 200, { ok: true, ...result })
1156
+ } catch (error) {
1157
+ fail(response, 500, 'attachment-remove-failed', String(error && error.message ? error.message : error))
1158
+ }
1159
+ return
1160
+ }
1161
+
1162
+ if (path === `${PREFIX}/questions`) {
1163
+ const library = await activeLibrary()
1164
+ if (request.method === 'GET') {
1165
+ const match = await chapterFromQuery(url)
1166
+ if (match.ok !== true) {
1167
+ fail(response, match.status, match.code, match.message)
1168
+ return
1169
+ }
1170
+ sendJson(response, 200, { ok: true, ...(await readQuestions(library.libraryDir, match.book.id, match.chapter.code)) })
1171
+ return
1172
+ }
1173
+ if (request.method !== 'PUT') {
1174
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET 或 PUT')
1175
+ return
1176
+ }
1177
+ const body = await mutationBody(request, response)
1178
+ if (body === undefined) return
1179
+ const record = body !== null && typeof body === 'object' ? body : {}
1180
+ const match = resolveChapter(await catalog(), record.book, String(record.code ?? '').toLowerCase())
1181
+ if (match.ok !== true) {
1182
+ fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
1183
+ return
1184
+ }
1185
+ try {
1186
+ sendJson(response, 200, { ok: true, ...(await writeQuestions(library.libraryDir, match.book.id, match.chapter.code, record)) })
1187
+ } catch (error) {
1188
+ fail(response, 400, 'questions-failed', String(error && error.message ? error.message : error))
1189
+ }
1190
+ return
1191
+ }
1192
+
604
1193
  if (path === `${PREFIX}/annotations`) {
605
1194
  try {
606
1195
  const library = await activeLibrary()
@@ -1479,7 +2068,7 @@ async function activeLibrary() {
1479
2068
  }
1480
2069
 
1481
2070
  if (path === `${PREFIX}/pdf`) {
1482
- if (request.method !== 'GET') {
2071
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
1483
2072
  fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1484
2073
  return
1485
2074
  }
@@ -1489,42 +2078,35 @@ async function activeLibrary() {
1489
2078
  return
1490
2079
  }
1491
2080
  const name = url.searchParams.get('name') ?? ''
2081
+ const library = await activeLibrary()
1492
2082
  const source = name === ''
1493
- ? chapterPdfPath(await activeLibrary(), match.book, match.chapter)
1494
- : artifactPdfPath(await activeLibrary(), match.book, match.chapter, name)
2083
+ ? chapterPdfPath(library, match.book, match.chapter)
2084
+ : artifactPdfPath(library, match.book, match.chapter, name)
1495
2085
  if (!source.ok) {
1496
2086
  fail(response, 400, source.reason, '这个文件不能作为 PDF 打开')
1497
2087
  return
1498
2088
  }
2089
+ // A translation or overlay layer lives beside the chapter PDF; the
2090
+ // reader serves it through the same ranged, cacheable route.
1499
2091
  const variant = url.searchParams.get('variant') ?? ''
2092
+ let target = source.path
1500
2093
  if (variant === 'translated' || variant === 'overlay') {
1501
2094
  const suffix = variant === 'overlay' ? '_overlay' : '_translated'
1502
- const target = join(dirname(source.path), `${basename(source.path, '.pdf')}${suffix}.pdf`)
1503
- let bytes = null
1504
- try {
1505
- bytes = await readPdf(target)
1506
- } catch {
1507
- bytes = null
1508
- }
1509
- if (bytes === null || !bytes.ok) {
1510
- fail(response, 404, 'missing-file', '还没有这一页/章的译文')
1511
- return
1512
- }
1513
- sendBytes(response, 200, bytes.bytes, 'application/pdf')
1514
- return
2095
+ target = join(dirname(source.path), `${basename(source.path, '.pdf')}${suffix}.pdf`)
1515
2096
  }
1516
- const file = await readPdf(source.path)
1517
- if (!file.ok) {
1518
- const status = file.reason === 'too-large' ? 413 : 404
1519
- fail(response, status, file.reason, file.reason === 'too-large' ? '这个 PDF 太大了' : '找不到这个 PDF')
2097
+ const sent = await sendPdfFile(request, response, target)
2098
+ if (sent.ok) return
2099
+ if (variant !== '') {
2100
+ fail(response, 404, 'missing-file', '还没有这一页/章的译文')
1520
2101
  return
1521
2102
  }
1522
- sendBytes(response, 200, file.bytes, 'application/pdf')
2103
+ const status = sent.reason === 'too-large' ? 413 : 404
2104
+ fail(response, status, sent.reason, sent.reason === 'too-large' ? '这个 PDF 太大了' : '找不到这个 PDF')
1523
2105
  return
1524
2106
  }
1525
2107
 
1526
2108
  if (path.startsWith(`${PREFIX}/vendor/`)) {
1527
- if (request.method !== 'GET') {
2109
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
1528
2110
  fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
1529
2111
  return
1530
2112
  }
@@ -1534,12 +2116,66 @@ async function activeLibrary() {
1534
2116
  fail(response, 404, 'not-found', '没有这个阅读器文件')
1535
2117
  return
1536
2118
  }
2119
+ const file = join(config.vendorDir, ...name.split('/'))
2120
+ let info
2121
+ try {
2122
+ info = await stat(file)
2123
+ } catch {
2124
+ fail(response, 404, 'missing-vendor', '阅读器文件缺失,请重新安装插件')
2125
+ return
2126
+ }
2127
+ // pdf.js fetches its worker for every document it opens. Without a
2128
+ // validator that was a fresh 1.26 MB download per open; with one the
2129
+ // browser revalidates or reuses it, and a plugin upgrade still lands
2130
+ // because the file's size/mtime changed.
2131
+ const etag = fileEtag(info)
2132
+ if (matchesEtag(request.headers['if-none-match'], etag)) {
2133
+ response.writeHead(304, { etag, 'cache-control': 'public, max-age=300' })
2134
+ response.end()
2135
+ return
2136
+ }
2137
+ let body
1537
2138
  try {
1538
- const body = await readFile(join(config.vendorDir, ...name.split('/')))
1539
- sendBytes(response, 200, body, contentType)
2139
+ body = await readFile(file)
1540
2140
  } catch {
1541
2141
  fail(response, 404, 'missing-vendor', '阅读器文件缺失,请重新安装插件')
2142
+ return
2143
+ }
2144
+ response.writeHead(200, {
2145
+ 'content-type': contentType,
2146
+ 'cache-control': 'public, max-age=300',
2147
+ etag,
2148
+ 'content-length': body.length,
2149
+ })
2150
+ if (request.method === 'HEAD') response.end()
2151
+ else response.end(body)
2152
+ return
2153
+ }
2154
+
2155
+ if (path === `${PREFIX}/artifact-ref`) {
2156
+ if (request.method !== 'GET') {
2157
+ fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
2158
+ return
2159
+ }
2160
+ const match = await chapterFromQuery(url)
2161
+ if (!match.ok) {
2162
+ fail(response, match.status, match.code, match.message)
2163
+ return
2164
+ }
2165
+ const name = url.searchParams.get('name') ?? ''
2166
+ if (name === '' || name.includes('/') || name.includes('\\') || name.includes('..')) {
2167
+ fail(response, 400, 'bad-name', '文件名不合法')
2168
+ return
2169
+ }
2170
+ const library = await activeLibrary()
2171
+ const file = join(chapterArtifactDir(library, match.book.id, match.chapter.code), name)
2172
+ const info = await stat(file).catch(() => null)
2173
+ if (info === null || info.isFile() !== true) {
2174
+ fail(response, 404, 'not-found', '这个文件不存在')
2175
+ return
1542
2176
  }
2177
+ const rel = relative(library.libraryDir, file)
2178
+ sendJson(response, 200, { ok: true, rel: rel.replace(/\\/g, '/') })
1543
2179
  return
1544
2180
  }
1545
2181