dsh-pdf-workbench 1.5.0 → 1.5.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/README.md +120 -171
- package/assets/screenshot-hero.jpg +0 -0
- package/assets/screenshot-settings-data.jpg +0 -0
- package/assets/screenshot-settings-env.jpg +0 -0
- package/assets/screenshot-settings-mode.jpg +0 -0
- package/assets/screenshot-settings-reading.jpg +0 -0
- package/assets/screenshot-shelf.jpg +0 -0
- package/client.js +1656 -171
- package/docs/changes/README.md +30 -0
- package/docs/changes/next.md +6 -0
- package/docs/changes/v1.5.2.md +432 -0
- package/docs/ci.md +7 -0
- package/docs/requirements/2026-11-27-/345/244/247/346/226/207/344/273/266/346/213/206/345/210/206/346/200/247/350/203/275.md +156 -0
- package/docs/roles/ci.md +7 -6
- package/docs/roles/programmer.md +6 -3
- package/docs/todo.md +188 -20
- package/package.json +1 -1
- package/screenshots.json +6 -4
- package/src/host/index-source.js +13 -2
- package/src/host/routes.js +456 -17
- package/tools/crop_question.py +82 -0
- package/tools/pdf_thumbs.py +78 -0
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +20 -2
package/src/host/index-source.js
CHANGED
|
@@ -21,6 +21,9 @@ const RANGE_FILE = /^(?<short>[^_]+?)_(?:(?:第[^_]*?章)_)?(?<rest>.*?)(?:_p|_)
|
|
|
21
21
|
/** Canonical chapter code, lowercase and exactly `c` + two or three digits. */
|
|
22
22
|
const CODE_SHAPE = /^c\d{2,3}$/
|
|
23
23
|
|
|
24
|
+
/** The placeholder the range splitter writes when it has no chapter title. */
|
|
25
|
+
const UNRENAMED_TITLE = /^(?:未命名|untitled)$/i
|
|
26
|
+
|
|
24
27
|
/**
|
|
25
28
|
* Canonicalize one chapter code.
|
|
26
29
|
* @param {unknown} raw - code from a file name or the authored index.
|
|
@@ -214,8 +217,9 @@ function bookRow(book) {
|
|
|
214
217
|
unparsed: typeof book.unparsed === 'number' ? book.unparsed : 0,
|
|
215
218
|
duplicates,
|
|
216
219
|
// A book made entirely of files whose names the splitter did not produce:
|
|
217
|
-
// readable, but hidden until the reader asks for unrecognized books.
|
|
218
|
-
|
|
220
|
+
// readable, but hidden until the reader asks for unrecognized books. A book
|
|
221
|
+
// the splitter produced but nobody named yet is in the same bucket.
|
|
222
|
+
loose: book.loose === true || (chapters.length > 0 && chapters.every(chapter => chapter.loose === true)),
|
|
219
223
|
chapters,
|
|
220
224
|
}
|
|
221
225
|
}
|
|
@@ -410,6 +414,12 @@ async function scanFragments(fragmentDir) {
|
|
|
410
414
|
}
|
|
411
415
|
for (const chapter of chapters) delete chapter.from
|
|
412
416
|
chapters.sort((left, right) => left.code.localeCompare(right.code))
|
|
417
|
+
// A plain page-range split (`split_pdf.py --ranges`) titles every chapter
|
|
418
|
+
// with the placeholder "未命名": the book has not been named per the split
|
|
419
|
+
// rule yet, so it belongs with the un-named books (out of the shelf until
|
|
420
|
+
// the reader asks for them) instead of flooding it after a split.
|
|
421
|
+
const unrenamed = chapters.length > 0
|
|
422
|
+
&& chapters.every(chapter => UNRENAMED_TITLE.test(String(chapter.title).trim()))
|
|
413
423
|
const { title, author } = splitBookTitle(entry.name)
|
|
414
424
|
books.push(bookRow({
|
|
415
425
|
id: short === '' ? entry.name : short,
|
|
@@ -417,6 +427,7 @@ async function scanFragments(fragmentDir) {
|
|
|
417
427
|
author,
|
|
418
428
|
dir: entry.name,
|
|
419
429
|
unparsed,
|
|
430
|
+
loose: unrenamed,
|
|
420
431
|
chapters,
|
|
421
432
|
}))
|
|
422
433
|
}
|
package/src/host/routes.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* GET /pdfdesk/artifact one produced file's text, for the preview
|
|
7
7
|
* GET /pdfdesk/pdf one chapter's PDF, or a produced PDF, for the reader
|
|
8
8
|
* GET /pdfdesk/pdf-ref that PDF as a workspace-relative path
|
|
9
|
+
* GET /pdfdesk/pdf-thumb one cached page thumbnail for the split panel
|
|
10
|
+
* POST /pdfdesk/pdf-layout page geometry + render one thumbnail range
|
|
9
11
|
* GET /pdfdesk/cover a user-provided book cover image
|
|
10
12
|
* GET /pdfdesk/context how full one session's context is
|
|
11
13
|
* GET /pdfdesk/questions one chapter's page-mark questions
|
|
@@ -27,7 +29,7 @@
|
|
|
27
29
|
* @module dsh-pdf-workbench/routes
|
|
28
30
|
*/
|
|
29
31
|
import { execFile } from 'node:child_process'
|
|
30
|
-
import { randomUUID } from 'node:crypto'
|
|
32
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
31
33
|
import { tmpdir } from 'node:os'
|
|
32
34
|
import { existsSync } from 'node:fs'
|
|
33
35
|
import { copyFile, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'
|
|
@@ -188,10 +190,29 @@ function imageBytesOf(value) {
|
|
|
188
190
|
}
|
|
189
191
|
}
|
|
190
192
|
|
|
193
|
+
/**
|
|
194
|
+
* Turn Python's "No module named 'fitz'" into the pip command a user can run.
|
|
195
|
+
* Every bundled tool runs through runTool/toolOutput, so one mapping covers the
|
|
196
|
+
* split, text, translate and export paths instead of showing a traceback that
|
|
197
|
+
* looks like a plugin crash.
|
|
198
|
+
* @param {unknown} stderr - the failed tool's stderr.
|
|
199
|
+
* @returns {string | null} a human hint, or null when this is not a missing package.
|
|
200
|
+
*/
|
|
201
|
+
export function dependencyHint(stderr) {
|
|
202
|
+
const text = String(stderr ?? '')
|
|
203
|
+
if (/No module named ['"]?fitz['"]?/.test(text) || /No module named ['"]?pymupdf['"]?/i.test(text)) {
|
|
204
|
+
return '缺少 Python 包 PyMuPDF:请运行 py -m pip install pymupdf(只阅读 PDF 不需要它)'
|
|
205
|
+
}
|
|
206
|
+
if (/No module named ['"]?PIL['"]?/.test(text) || /No module named ['"]?Pillow['"]?/i.test(text)) {
|
|
207
|
+
return '缺少 Python 包 Pillow:请运行 py -m pip install pillow'
|
|
208
|
+
}
|
|
209
|
+
return null
|
|
210
|
+
}
|
|
211
|
+
|
|
191
212
|
/**
|
|
192
213
|
* Build the prefix handler for the plugin's routes.
|
|
193
214
|
* @param {{ libraryDir: string, fragmentDir: string, artifactDir: string, coverDir: string, indexPath: string, statePath: string, resumeRatio?: number, toolsDir?: string }} config - resolved paths and behavior (the profile's library is the fallback).
|
|
194
|
-
* @param {{ resolveTarget?: () => Promise<{ workspaceId: string | null, cwd: string }>, listWorkspaces?: () => Promise<Array<{ id: string, title: string, path: string }>>, pending?: { list: Function, put: Function, remove: Function }, links?: { list: Function, add: Function, remove: Function }, contextPressure?: (sessionId: string) => Promise<object | null>, libraries?: { list: Function, active: Function, add: Function, setActive: Function, remove: Function }, translationMigration?: () => Promise<object>, revealFile?: (path: string) => void, installToolkit?: (libraryDir: string) => Promise<object>, aiTranslate?: (choice: object) => Promise<object> }} [options] - host capabilities the routes expose.
|
|
215
|
+
* @param {{ resolveTarget?: () => Promise<{ workspaceId: string | null, cwd: string }>, listWorkspaces?: () => Promise<Array<{ id: string, title: string, path: string }>>, pending?: { list: Function, put: Function, remove: Function }, links?: { list: Function, add: Function, remove: Function }, contextPressure?: (sessionId: string) => Promise<object | null>, libraries?: { list: Function, active: Function, add: Function, setActive: Function, remove: Function }, translationMigration?: () => Promise<object>, revealFile?: (path: string) => void, installToolkit?: (libraryDir: string) => Promise<object>, aiTranslate?: (choice: object) => Promise<object>, renderThumbs?: (job: { path: string, root: string, width: number, first: number, last: number }) => Promise<void> }} [options] - host capabilities the routes expose.
|
|
195
216
|
* @returns {(request: import('node:http').IncomingMessage, response: import('node:http').ServerResponse) => Promise<void>} the handler.
|
|
196
217
|
*/
|
|
197
218
|
export function createHandler(config, options = {}) {
|
|
@@ -217,17 +238,34 @@ export function createHandler(config, options = {}) {
|
|
|
217
238
|
* @param {string} code - chapter code.
|
|
218
239
|
* @returns {Promise<string|null>} absolute path, or null when missing.
|
|
219
240
|
*/
|
|
241
|
+
|
|
242
|
+
|
|
220
243
|
function runTool(script, args, env = {}) {
|
|
221
244
|
const pythons = [process.env.MATH_DESK_PYTHON, 'python', 'py'].filter(Boolean)
|
|
222
245
|
return new Promise((resolve, reject) => {
|
|
246
|
+
let lastFailure = null
|
|
223
247
|
const next = index => {
|
|
224
248
|
if (index >= pythons.length) {
|
|
225
|
-
|
|
249
|
+
// No interpreter at all is the only case where "没有可用的 Python" is
|
|
250
|
+
// true. If one ran and the tool failed, repeat that error: the old
|
|
251
|
+
// message hid real failures (bad ranges, a bad script path) as a
|
|
252
|
+
// missing Python.
|
|
253
|
+
reject(lastFailure ?? new Error('没有可用的 Python'))
|
|
226
254
|
return
|
|
227
255
|
}
|
|
228
|
-
execFile(pythons[index], [script, ...args], { timeout: 240000, windowsHide: true, env: { ...process.env, ...env } }, error => {
|
|
229
|
-
if (error === null)
|
|
230
|
-
|
|
256
|
+
execFile(pythons[index], [script, ...args], { timeout: 240000, windowsHide: true, env: { ...process.env, ...env } }, (error, stdout, stderr) => {
|
|
257
|
+
if (error === null) {
|
|
258
|
+
resolve()
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
// ENOENT means this interpreter is absent; keep trying the next one.
|
|
262
|
+
// Other failures are kept and reported after the last candidate.
|
|
263
|
+
if (error.code !== 'ENOENT') {
|
|
264
|
+
const missing = dependencyHint(stderr)
|
|
265
|
+
const detail = missing ?? (String(stderr ?? '').trim() || String(error.message ?? error))
|
|
266
|
+
lastFailure = Object.assign(new Error(detail.slice(0, 2000)), { code: error.code ?? 'tool-failed' })
|
|
267
|
+
}
|
|
268
|
+
next(index + 1)
|
|
231
269
|
})
|
|
232
270
|
}
|
|
233
271
|
next(0)
|
|
@@ -270,9 +308,19 @@ function toolOutput(script, args, env = {}) {
|
|
|
270
308
|
pythons[index],
|
|
271
309
|
[script, ...args],
|
|
272
310
|
{ timeout: 180000, windowsHide: true, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, ...env } },
|
|
273
|
-
(error, stdout) => {
|
|
274
|
-
if (error === null)
|
|
275
|
-
|
|
311
|
+
(error, stdout, stderr) => {
|
|
312
|
+
if (error === null) {
|
|
313
|
+
resolve(stdout)
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
// A missing Python package fails on every interpreter: report the pip
|
|
317
|
+
// command instead of retrying and then claiming no Python exists.
|
|
318
|
+
const missing = dependencyHint(stderr)
|
|
319
|
+
if (missing !== null) {
|
|
320
|
+
reject(Object.assign(new Error(missing), { code: 'missing-package' }))
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
next(index + 1)
|
|
276
324
|
}
|
|
277
325
|
)
|
|
278
326
|
}
|
|
@@ -280,6 +328,49 @@ function toolOutput(script, args, env = {}) {
|
|
|
280
328
|
})
|
|
281
329
|
}
|
|
282
330
|
|
|
331
|
+
/**
|
|
332
|
+
* Render one question mark's framed region to a PNG beside the question store.
|
|
333
|
+
* The picture is what a scanned page can give the model: text extraction is
|
|
334
|
+
* empty there, and “page 13” alone does not tell it what was framed.
|
|
335
|
+
* @param {object} config - resolved plugin paths.
|
|
336
|
+
* @param {object} library - the active library.
|
|
337
|
+
* @param {{ book: object, chapter: object }} match - the catalog rows.
|
|
338
|
+
* @param {object} question - `{ id, page, rect }`.
|
|
339
|
+
* @returns {Promise<string>} the absolute PNG path.
|
|
340
|
+
*/
|
|
341
|
+
async function renderQuestionCrop(config, library, match, question) {
|
|
342
|
+
const source = chapterPdfPath(library, match.book, match.chapter)
|
|
343
|
+
if (source.ok !== true || typeof source.path !== 'string') {
|
|
344
|
+
throw Object.assign(new Error('找不到这一章的 PDF'), { code: 'no-pdf' })
|
|
345
|
+
}
|
|
346
|
+
const id = question !== null && typeof question === 'object' && typeof question.id === 'string' ? question.id : ''
|
|
347
|
+
const page = Math.round(Number(question !== null && typeof question === 'object' ? question.page : 0))
|
|
348
|
+
if (!/^q-[A-Za-z0-9._-]{1,64}$/.test(id) || !Number.isFinite(page) || page < 1) {
|
|
349
|
+
throw Object.assign(new Error('疑问不合法'), { code: 'bad-question' })
|
|
350
|
+
}
|
|
351
|
+
const rect = question.rect !== null && typeof question.rect === 'object' ? question.rect : {}
|
|
352
|
+
const outDir = join(library.libraryDir, '.pdfdesk', 'questions', match.book.id, match.chapter.code, 'crops')
|
|
353
|
+
const out = join(outDir, `${id}.webp`)
|
|
354
|
+
await mkdir(outDir, { recursive: true })
|
|
355
|
+
// Drop a PNG left by the first build of this feature: the model now reads the
|
|
356
|
+
// lossless WebP, and the old file would only take space.
|
|
357
|
+
await unlink(join(outDir, `${id}.png`)).catch(() => {})
|
|
358
|
+
await runTool(join(config.toolsDir, 'crop_question.py'), [
|
|
359
|
+
source.path,
|
|
360
|
+
String(page),
|
|
361
|
+
String(Number(rect.x) || 0),
|
|
362
|
+
String(Number(rect.y) || 0),
|
|
363
|
+
String(Number(rect.w) || 0),
|
|
364
|
+
String(Number(rect.h) || 0),
|
|
365
|
+
out,
|
|
366
|
+
])
|
|
367
|
+
const info = await stat(out).catch(() => null)
|
|
368
|
+
if (info === null || !info.isFile() || info.size === 0) {
|
|
369
|
+
throw Object.assign(new Error('框选区域渲染失败'), { code: 'crop-failed' })
|
|
370
|
+
}
|
|
371
|
+
return out
|
|
372
|
+
}
|
|
373
|
+
|
|
283
374
|
async function chapterPdf(library, bookId, code) {
|
|
284
375
|
const current = await catalog()
|
|
285
376
|
const match = resolveChapter(current, bookId, code)
|
|
@@ -450,6 +541,162 @@ async function activeLibrary() {
|
|
|
450
541
|
return { ...match, status: match.code === 'unknown-chapter' ? 404 : 400 }
|
|
451
542
|
}
|
|
452
543
|
|
|
544
|
+
/* ---------------------------------------------------------- thumbnails -- */
|
|
545
|
+
|
|
546
|
+
/** Thumbnail widths the split panel may ask for, in CSS pixels. */
|
|
547
|
+
const THUMB_WIDTH_MIN = 80
|
|
548
|
+
const THUMB_WIDTH_MAX = 480
|
|
549
|
+
const THUMB_WIDTH_DEFAULT = 240
|
|
550
|
+
/** One Python run renders at most this many pages; the panel scrolls in batches. */
|
|
551
|
+
const THUMB_BATCH_MAX = 60
|
|
552
|
+
/** A cached thumbnail is immutable: its directory key contains the file mtime. */
|
|
553
|
+
const THUMB_CACHE_SECONDS = 31536000
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Per-PDF render jobs, so a fast scroll cannot start two Python renders for
|
|
557
|
+
* the same file at once. Later requests wait for the one already running.
|
|
558
|
+
* @type {Map<string, Promise<unknown>>}
|
|
559
|
+
*/
|
|
560
|
+
const thumbJobs = new Map()
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Clamp a requested thumbnail width to the supported range.
|
|
564
|
+
* @param {unknown} value - the query/body value.
|
|
565
|
+
* @returns {number} an integer CSS width.
|
|
566
|
+
*/
|
|
567
|
+
function thumbWidth(value) {
|
|
568
|
+
const width = Math.round(Number(value))
|
|
569
|
+
if (!Number.isFinite(width)) return THUMB_WIDTH_DEFAULT
|
|
570
|
+
return Math.min(THUMB_WIDTH_MAX, Math.max(THUMB_WIDTH_MIN, width))
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Cache root of one PDF identity.
|
|
575
|
+
* @param {string} key - identity hash.
|
|
576
|
+
* @returns {string} absolute directory.
|
|
577
|
+
*/
|
|
578
|
+
function thumbRoot(key) {
|
|
579
|
+
return join(config.dataDir, 'thumbs', key)
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* The geometry file of one PDF identity.
|
|
584
|
+
* @param {string} key - identity hash.
|
|
585
|
+
* @returns {string} absolute path.
|
|
586
|
+
*/
|
|
587
|
+
function thumbInfoFile(key) {
|
|
588
|
+
return join(thumbRoot(key), 'info.json')
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* One cached page image.
|
|
593
|
+
* @param {string} key - identity hash.
|
|
594
|
+
* @param {number} width - CSS width.
|
|
595
|
+
* @param {number} page - 1-based page number.
|
|
596
|
+
* @returns {string} absolute path.
|
|
597
|
+
*/
|
|
598
|
+
function thumbImageFile(key, width, page) {
|
|
599
|
+
return join(thumbRoot(key), String(width), `p${String(page).padStart(4, '0')}.jpg`)
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Read the cached page geometry, or null when nothing was rendered yet.
|
|
604
|
+
* @param {string} key - identity hash.
|
|
605
|
+
* @returns {Promise<{ pages: number, pageWidth: number, pageHeight: number } | null>} the geometry.
|
|
606
|
+
*/
|
|
607
|
+
async function readThumbInfo(key) {
|
|
608
|
+
try {
|
|
609
|
+
const parsed = JSON.parse(await readFile(thumbInfoFile(key), 'utf8'))
|
|
610
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
611
|
+
if (!Number.isInteger(parsed.pages) || parsed.pages <= 0) return null
|
|
612
|
+
if (!(Number(parsed.pageWidth) > 0) || !(Number(parsed.pageHeight) > 0)) return null
|
|
613
|
+
return { pages: parsed.pages, pageWidth: Number(parsed.pageWidth), pageHeight: Number(parsed.pageHeight) }
|
|
614
|
+
} catch {
|
|
615
|
+
return null
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* Resolve a chapter match to its PDF and a cache key that changes with the
|
|
621
|
+
* file's bytes (path + size + mtime), so a re-import never serves old pages.
|
|
622
|
+
* @param {{ ok: true, book: object, chapter: object }} match - resolved chapter.
|
|
623
|
+
* @returns {Promise<{ ok: true, path: string, key: string } | { ok: false, status: number, code: string, message: string }>} the source or the refusal.
|
|
624
|
+
*/
|
|
625
|
+
async function thumbSource(match) {
|
|
626
|
+
const library = await activeLibrary()
|
|
627
|
+
const source = chapterPdfPath(library, match.book, match.chapter)
|
|
628
|
+
if (!source.ok) {
|
|
629
|
+
return { ok: false, status: 400, code: source.reason, message: '这个文件不能作为 PDF 打开' }
|
|
630
|
+
}
|
|
631
|
+
let info
|
|
632
|
+
try {
|
|
633
|
+
info = await stat(source.path)
|
|
634
|
+
} catch {
|
|
635
|
+
info = null
|
|
636
|
+
}
|
|
637
|
+
if (info === null || !info.isFile()) {
|
|
638
|
+
return { ok: false, status: 404, code: 'not-found', message: '找不到这个 PDF' }
|
|
639
|
+
}
|
|
640
|
+
const key = createHash('sha1')
|
|
641
|
+
.update(`${source.path}|${info.size}|${Math.floor(info.mtimeMs)}`)
|
|
642
|
+
.digest('hex')
|
|
643
|
+
.slice(0, 16)
|
|
644
|
+
return { ok: true, path: source.path, key }
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Serialize render jobs per PDF, so overlapping scroll batches do not run
|
|
649
|
+
* several Python processes over the same file.
|
|
650
|
+
* @param {string} key - identity hash.
|
|
651
|
+
* @param {() => Promise<unknown>} task - the job.
|
|
652
|
+
* @returns {Promise<unknown>} the job's result.
|
|
653
|
+
*/
|
|
654
|
+
function runThumbJob(key, task) {
|
|
655
|
+
const previous = thumbJobs.get(key) ?? Promise.resolve()
|
|
656
|
+
const next = previous.catch(() => {}).then(task)
|
|
657
|
+
thumbJobs.set(key, next)
|
|
658
|
+
next.then(
|
|
659
|
+
() => { if (thumbJobs.get(key) === next) thumbJobs.delete(key) },
|
|
660
|
+
() => { if (thumbJobs.get(key) === next) thumbJobs.delete(key) },
|
|
661
|
+
)
|
|
662
|
+
return next
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Ensure the requested page range is in the thumbnail cache.
|
|
667
|
+
* @param {{ path: string, key: string }} source - the PDF.
|
|
668
|
+
* @param {number} width - CSS width.
|
|
669
|
+
* @param {number} first - first page (1-based).
|
|
670
|
+
* @param {number} last - last page (inclusive).
|
|
671
|
+
* @returns {Promise<{ info: object, rendered: number[] }>} geometry and rendered pages.
|
|
672
|
+
*/
|
|
673
|
+
async function ensureThumbRange(source, width, first, last) {
|
|
674
|
+
const info = await readThumbInfo(source.key)
|
|
675
|
+
const total = info === null ? 0 : info.pages
|
|
676
|
+
if (total > 0 && first > total) return { info, rendered: [] }
|
|
677
|
+
const end = total > 0 ? Math.min(last, total) : last
|
|
678
|
+
const start = Math.max(1, Math.min(first, end))
|
|
679
|
+
const pages = []
|
|
680
|
+
for (let page = start; page <= end; page += 1) pages.push(page)
|
|
681
|
+
const missing = pages.filter(page => !existsSync(thumbImageFile(source.key, width, page)))
|
|
682
|
+
if (info !== null && missing.length === 0) return { info, rendered: pages }
|
|
683
|
+
const job = { path: source.path, root: thumbRoot(source.key), width, first: start, last: end }
|
|
684
|
+
if (typeof options.renderThumbs === 'function') {
|
|
685
|
+
await options.renderThumbs(job)
|
|
686
|
+
} else {
|
|
687
|
+
await runTool(join(config.toolsDir, 'pdf_thumbs.py'), [
|
|
688
|
+
job.path,
|
|
689
|
+
job.root,
|
|
690
|
+
String(job.width),
|
|
691
|
+
String(job.first),
|
|
692
|
+
String(job.last),
|
|
693
|
+
])
|
|
694
|
+
}
|
|
695
|
+
const fresh = await readThumbInfo(source.key)
|
|
696
|
+
if (fresh === null) throw new Error('缩略图信息没有生成')
|
|
697
|
+
return { info: fresh, rendered: pages.filter(page => page <= fresh.pages) }
|
|
698
|
+
}
|
|
699
|
+
|
|
453
700
|
return async function handle(request, response) {
|
|
454
701
|
try {
|
|
455
702
|
// DSH's trust fence: Host/Origin validation and browser authentication.
|
|
@@ -979,7 +1226,10 @@ async function activeLibrary() {
|
|
|
979
1226
|
fail(response, 400, 'invalid-body', '缺少 book 或 ranges')
|
|
980
1227
|
return
|
|
981
1228
|
}
|
|
982
|
-
|
|
1229
|
+
// Resolve the book against the library the user is looking at: `config`
|
|
1230
|
+
// still points at the profile's default library, so a book in any other
|
|
1231
|
+
// active library was reported as missing.
|
|
1232
|
+
const current = await catalog(true)
|
|
983
1233
|
const row = Array.isArray(current.books) ? current.books.find(item => item.id === book) : undefined
|
|
984
1234
|
if (row === undefined) {
|
|
985
1235
|
fail(response, 404, 'unknown-book', '没有这本书')
|
|
@@ -1000,7 +1250,7 @@ async function activeLibrary() {
|
|
|
1000
1250
|
// 输出按书库规则写进 `分片/<书id>/`,命名交给 split_pdf.py(与书库同一套规则)。
|
|
1001
1251
|
const outDir = join(library.fragmentDir, book)
|
|
1002
1252
|
try {
|
|
1003
|
-
const output = await runTool('split_pdf.py', [source.path, outDir, '--id', book, '--ranges', ranges])
|
|
1253
|
+
const output = await runTool(join(config.toolsDir, 'split_pdf.py'), [source.path, outDir, '--id', book, '--ranges', ranges])
|
|
1004
1254
|
invalidateCatalog()
|
|
1005
1255
|
sendJson(response, 200, { ok: true, outDir, output })
|
|
1006
1256
|
} catch (error) {
|
|
@@ -1211,9 +1461,9 @@ async function activeLibrary() {
|
|
|
1211
1461
|
}
|
|
1212
1462
|
try {
|
|
1213
1463
|
const body = await readJson(request)
|
|
1214
|
-
const
|
|
1215
|
-
const chapter = resolveChapter(
|
|
1216
|
-
if (chapter
|
|
1464
|
+
const current = await catalog()
|
|
1465
|
+
const chapter = resolveChapter(current, body.book, body.code)
|
|
1466
|
+
if (chapter.ok !== true) {
|
|
1217
1467
|
fail(response, 404, 'no-chapter', '找不到这一章')
|
|
1218
1468
|
return
|
|
1219
1469
|
}
|
|
@@ -1821,6 +2071,67 @@ async function activeLibrary() {
|
|
|
1821
2071
|
return
|
|
1822
2072
|
}
|
|
1823
2073
|
|
|
2074
|
+
if (path === `${PREFIX}/question-crop` || path === `${PREFIX}/question-crops`) {
|
|
2075
|
+
if (request.method !== 'POST') {
|
|
2076
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
2077
|
+
return
|
|
2078
|
+
}
|
|
2079
|
+
if (!isSameOrigin(request)) {
|
|
2080
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
2081
|
+
return
|
|
2082
|
+
}
|
|
2083
|
+
let body
|
|
2084
|
+
try {
|
|
2085
|
+
body = await readJson(request, 2 * 1024 * 1024)
|
|
2086
|
+
} catch (error) {
|
|
2087
|
+
fail(response, 400, 'invalid-body', String(error && error.message ? error.message : error))
|
|
2088
|
+
return
|
|
2089
|
+
}
|
|
2090
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
2091
|
+
const match = resolveChapter(await catalog(), record.book, String(record.code ?? '').toLowerCase())
|
|
2092
|
+
if (match.ok !== true) {
|
|
2093
|
+
fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
|
|
2094
|
+
return
|
|
2095
|
+
}
|
|
2096
|
+
const library = await activeLibrary()
|
|
2097
|
+
if (path === `${PREFIX}/question-crop`) {
|
|
2098
|
+
try {
|
|
2099
|
+
sendJson(response, 200, { ok: true, path: await renderQuestionCrop(config, library, match, record) })
|
|
2100
|
+
} catch (error) {
|
|
2101
|
+
const reason = error !== null && error !== undefined ? error.code : ''
|
|
2102
|
+
fail(
|
|
2103
|
+
response,
|
|
2104
|
+
reason === 'no-pdf' || reason === 'bad-question' ? 400 : 502,
|
|
2105
|
+
reason === 'no-pdf' ? 'no-pdf' : reason === 'bad-question' ? 'bad-question' : 'crop-failed',
|
|
2106
|
+
String(error && error.message ? error.message : error),
|
|
2107
|
+
)
|
|
2108
|
+
}
|
|
2109
|
+
return
|
|
2110
|
+
}
|
|
2111
|
+
// Batch: session seed wants a picture for every existing mark, including
|
|
2112
|
+
// ones created before this feature. Cached crops are reused until the
|
|
2113
|
+
// PDF itself changes.
|
|
2114
|
+
const stored = await readQuestions(library.libraryDir, match.book.id, match.chapter.code)
|
|
2115
|
+
const questions = Array.isArray(stored.questions) ? stored.questions : []
|
|
2116
|
+
const source = chapterPdfPath(library, match.book, match.chapter)
|
|
2117
|
+
const pdfInfo = source.ok === true ? await stat(source.path).catch(() => null) : null
|
|
2118
|
+
const items = []
|
|
2119
|
+
for (const question of questions.slice(0, 40)) {
|
|
2120
|
+
const out = join(library.libraryDir, '.pdfdesk', 'questions', match.book.id, match.chapter.code, 'crops', `${question.id}.webp`)
|
|
2121
|
+
const existing = await stat(out).catch(() => null)
|
|
2122
|
+
if (existing === null || existing.isFile() !== true || (pdfInfo !== null && existing.mtimeMs < pdfInfo.mtimeMs)) {
|
|
2123
|
+
try {
|
|
2124
|
+
await renderQuestionCrop(config, library, match, question)
|
|
2125
|
+
} catch {
|
|
2126
|
+
continue
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
items.push({ id: question.id, path: out })
|
|
2130
|
+
}
|
|
2131
|
+
sendJson(response, 200, { ok: true, items, total: questions.length, truncated: questions.length > 40 })
|
|
2132
|
+
return
|
|
2133
|
+
}
|
|
2134
|
+
|
|
1824
2135
|
if (path === `${PREFIX}/annotations`) {
|
|
1825
2136
|
try {
|
|
1826
2137
|
const library = await activeLibrary()
|
|
@@ -2324,14 +2635,50 @@ async function activeLibrary() {
|
|
|
2324
2635
|
return
|
|
2325
2636
|
}
|
|
2326
2637
|
const body = await readJson(request)
|
|
2327
|
-
const
|
|
2638
|
+
const record = body !== null && typeof body === 'object' ? body : {}
|
|
2639
|
+
const book = typeof record.book === 'string' ? record.book : ''
|
|
2640
|
+
const file = typeof record.file === 'string' ? record.file.trim() : ''
|
|
2641
|
+
const wholeOnly = record.whole === true
|
|
2328
2642
|
if (book === '' || /[\\/:*?"<>|]/.test(book)) {
|
|
2329
2643
|
fail(response, 400, 'bad-book', '书名不合法')
|
|
2330
2644
|
return
|
|
2331
2645
|
}
|
|
2646
|
+
if (file !== '' && /[\\/:*?"<>|]/.test(file)) {
|
|
2647
|
+
fail(response, 400, 'bad-file', '整本文件名不合法')
|
|
2648
|
+
return
|
|
2649
|
+
}
|
|
2332
2650
|
const library = await activeLibrary()
|
|
2333
|
-
|
|
2334
|
-
|
|
2651
|
+
// "Remove the whole-book form" must never touch the split folder that
|
|
2652
|
+
// shares the book id: look only for the original whole PDF.
|
|
2653
|
+
if (wholeOnly) {
|
|
2654
|
+
const stem = (file === '' ? book : file).replace(/\.pdf$/i, '')
|
|
2655
|
+
let source = ''
|
|
2656
|
+
for (const dir of [join(library.libraryDir, '整本'), library.libraryDir, join(library.libraryDir, '分片')]) {
|
|
2657
|
+
const candidate = join(dir, `${stem}.pdf`)
|
|
2658
|
+
try {
|
|
2659
|
+
const info = await stat(candidate)
|
|
2660
|
+
if (info.isFile()) {
|
|
2661
|
+
source = candidate
|
|
2662
|
+
break
|
|
2663
|
+
}
|
|
2664
|
+
} catch {
|
|
2665
|
+
// try the next layout
|
|
2666
|
+
}
|
|
2667
|
+
}
|
|
2668
|
+
if (source === '') {
|
|
2669
|
+
fail(response, 404, 'missing', `找不到整本 PDF(${stem}.pdf)`)
|
|
2670
|
+
return
|
|
2671
|
+
}
|
|
2672
|
+
const trashDir = join(library.libraryDir, '回收站')
|
|
2673
|
+
await mkdir(trashDir, { recursive: true })
|
|
2674
|
+
const target = join(trashDir, `${Date.now()}-${basename(source)}`)
|
|
2675
|
+
await rename(source, target)
|
|
2676
|
+
invalidateCatalog()
|
|
2677
|
+
sendJson(response, 200, { ok: true, path: target })
|
|
2678
|
+
return
|
|
2679
|
+
}
|
|
2680
|
+
const current = await catalog()
|
|
2681
|
+
const row = current.books.find(item => item.id === book)
|
|
2335
2682
|
const fragmentRoot = join(library.libraryDir, '分片')
|
|
2336
2683
|
let source = ''
|
|
2337
2684
|
const candidates = []
|
|
@@ -2901,6 +3248,98 @@ async function activeLibrary() {
|
|
|
2901
3248
|
return
|
|
2902
3249
|
}
|
|
2903
3250
|
|
|
3251
|
+
if (path === `${PREFIX}/pdf-layout`) {
|
|
3252
|
+
if (request.method !== 'POST') {
|
|
3253
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 POST')
|
|
3254
|
+
return
|
|
3255
|
+
}
|
|
3256
|
+
if (!isSameOrigin(request)) {
|
|
3257
|
+
fail(response, 403, 'cross-origin', '拒绝跨站写入')
|
|
3258
|
+
return
|
|
3259
|
+
}
|
|
3260
|
+
let body
|
|
3261
|
+
try {
|
|
3262
|
+
body = await readJson(request)
|
|
3263
|
+
} catch (error) {
|
|
3264
|
+
fail(response, 400, 'bad-json', String(error && error.message ? error.message : error))
|
|
3265
|
+
return
|
|
3266
|
+
}
|
|
3267
|
+
const payload = body !== null && typeof body === 'object' ? body : {}
|
|
3268
|
+
const match = resolveChapter(
|
|
3269
|
+
await catalog(),
|
|
3270
|
+
String(payload.book ?? ''),
|
|
3271
|
+
String(payload.code ?? '').toLowerCase(),
|
|
3272
|
+
)
|
|
3273
|
+
if (!match.ok) {
|
|
3274
|
+
fail(response, match.code === 'unknown-chapter' ? 404 : 400, match.code, match.message)
|
|
3275
|
+
return
|
|
3276
|
+
}
|
|
3277
|
+
const source = await thumbSource(match)
|
|
3278
|
+
if (!source.ok) {
|
|
3279
|
+
fail(response, source.status, source.code, source.message)
|
|
3280
|
+
return
|
|
3281
|
+
}
|
|
3282
|
+
const width = thumbWidth(payload.w)
|
|
3283
|
+
const first = Math.max(1, Math.round(Number(payload.from) || 1))
|
|
3284
|
+
const requestedLast = Math.round(Number(payload.to) || (first + 11))
|
|
3285
|
+
const last = Math.max(first, Math.min(requestedLast, first + THUMB_BATCH_MAX - 1))
|
|
3286
|
+
try {
|
|
3287
|
+
const result = await runThumbJob(source.key, () => ensureThumbRange(source, width, first, last))
|
|
3288
|
+
sendJson(response, 200, {
|
|
3289
|
+
ok: true,
|
|
3290
|
+
pages: result.info.pages,
|
|
3291
|
+
pageWidth: result.info.pageWidth,
|
|
3292
|
+
pageHeight: result.info.pageHeight,
|
|
3293
|
+
aspect: result.info.pageHeight / result.info.pageWidth,
|
|
3294
|
+
width,
|
|
3295
|
+
v: source.key,
|
|
3296
|
+
rendered: result.rendered,
|
|
3297
|
+
})
|
|
3298
|
+
} catch (error) {
|
|
3299
|
+
fail(response, 503, 'thumbs-failed', String(error && error.message ? error.message : error))
|
|
3300
|
+
}
|
|
3301
|
+
return
|
|
3302
|
+
}
|
|
3303
|
+
|
|
3304
|
+
if (path === `${PREFIX}/pdf-thumb`) {
|
|
3305
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
3306
|
+
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|
|
3307
|
+
return
|
|
3308
|
+
}
|
|
3309
|
+
const match = await chapterFromQuery(url)
|
|
3310
|
+
if (!match.ok) {
|
|
3311
|
+
fail(response, match.status, match.code, match.message)
|
|
3312
|
+
return
|
|
3313
|
+
}
|
|
3314
|
+
const page = Math.round(Number(url.searchParams.get('page')))
|
|
3315
|
+
if (!Number.isInteger(page) || page < 1 || page > 20000) {
|
|
3316
|
+
fail(response, 400, 'bad-page', '页码不合法')
|
|
3317
|
+
return
|
|
3318
|
+
}
|
|
3319
|
+
const width = thumbWidth(url.searchParams.get('w'))
|
|
3320
|
+
const source = await thumbSource(match)
|
|
3321
|
+
if (!source.ok) {
|
|
3322
|
+
fail(response, source.status, source.code, source.message)
|
|
3323
|
+
return
|
|
3324
|
+
}
|
|
3325
|
+
const version = url.searchParams.get('v') ?? ''
|
|
3326
|
+
if (version !== '' && version !== source.key) {
|
|
3327
|
+
fail(response, 409, 'stale-thumb', 'PDF 已更新,请重新载入缩略图')
|
|
3328
|
+
return
|
|
3329
|
+
}
|
|
3330
|
+
let bytes
|
|
3331
|
+
try {
|
|
3332
|
+
bytes = await readFile(thumbImageFile(source.key, width, page))
|
|
3333
|
+
} catch {
|
|
3334
|
+
fail(response, 404, 'not-prepared', '缩略图还没生成')
|
|
3335
|
+
return
|
|
3336
|
+
}
|
|
3337
|
+
const etag = `"${source.key}-${width}-${page}"`
|
|
3338
|
+
if (sendNotModified(request, response, etag)) return
|
|
3339
|
+
sendBytes(response, 200, bytes, 'image/jpeg', undefined, { etag, maxAge: THUMB_CACHE_SECONDS })
|
|
3340
|
+
return
|
|
3341
|
+
}
|
|
3342
|
+
|
|
2904
3343
|
if (path === `${PREFIX}/pdf`) {
|
|
2905
3344
|
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
|
2906
3345
|
fail(response, 405, 'method-not-allowed', '这个接口只接受 GET')
|