dsh-pdf-workbench 1.3.3 → 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.
- package/LICENSE +21 -21
- package/README.md +225 -199
- package/assets/screenshot-attachments.jpg +0 -0
- package/assets/screenshot-canvas.jpg +0 -0
- package/assets/screenshot-questions.jpg +0 -0
- package/assets/screenshot-settings-data.jpg +0 -0
- package/assets/screenshot-settings-mode.jpg +0 -0
- package/assets/screenshot-settings-reading.jpg +0 -0
- package/client.js +5700 -849
- package/docs/DETAIL.md +1 -69
- package/docs/RELEASE.md +119 -119
- package/docs/SIDE-PREVIEW.md +5 -1
- package/docs/preview.svg +86 -0
- package/icon.svg +7 -6
- package/index.js +18 -2
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
- package/screenshots.json +13 -8
- package/src/client/host-ui-entry.js +11 -11
- package/src/client/react-jsx-runtime.cjs +21 -21
- package/src/client/viewer.js +80 -80
- package/src/host/artifacts.js +31 -3
- package/src/host/attachments.js +159 -0
- package/src/host/backup.js +457 -0
- package/src/host/base-session.js +146 -0
- package/src/host/book-import.js +98 -0
- package/src/host/chapter-sessions.js +154 -0
- package/src/host/chapter-text.js +91 -0
- package/src/host/fonts.js +190 -0
- package/src/host/pdf-stream.js +168 -0
- package/src/host/ppt.js +153 -0
- package/src/host/print.js +191 -0
- package/src/host/questions.js +186 -0
- package/src/host/routes.js +671 -25
- package/src/host/state.js +1 -1
- package/src/host/zip.js +186 -0
- package/tools/AGENTS.md +33 -33
- package/tools/README.md +138 -138
- package/tools/auto_chapters.py +122 -122
- package/tools/dsfile.mjs +198 -198
- package/tools/export_chapter.py +108 -108
- package/tools/export_page.py +91 -91
- package/tools/md2overlay.py +200 -200
- package/tools/md2tex.py +422 -422
- package/tools/pdf_blocks.py +110 -110
- package/tools/pdf_fontsize.py +20 -20
- package/tools/pdf_merge.py +15 -15
- package/tools/pdf_pagesizes.py +8 -8
- package/tools/pdf_raster.py +21 -21
- package/tools/pdf_text.py +34 -0
- package/tools/pdfkit.py +896 -896
- package/tools/realign_overlay.py +248 -248
- package/tools/rebuild_overlay.py +55 -55
- package/tools/rename_chapters.py +93 -93
- package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
- package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
- package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
- package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
- package/tools//350/247/204/350/214/203/api/346/217/220/347/244/272/350/257/215_/346/217/220/345/217/226.md +11 -11
- package/vendor/cmaps/LICENSE.txt +36 -36
- package/vendor/fonts/excalifont/OFL.txt +98 -98
- package/vendor/fonts/zhhand/OFL.txt +99 -99
- package/vendor/host-ui.cjs +1719 -1719
- package/vendor/host-ui.css +799 -799
- package/vendor/pdf.min.mjs +28 -28
- package/vendor/pdf.worker.min.mjs +28 -28
- package/vendor/pdfjs-LICENSE.txt +177 -177
- package/vendor/rough/LICENSE +21 -21
- package/vendor/rough/rough.mjs +1 -1
- package/vendor/wasm/LICENSE_JBIG2 +196 -196
- package/vendor/wasm/LICENSE_OPENJPEG +39 -39
- package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
- package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
- package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
- package/vendor/wasm/LICENSE_QCMS +21 -21
- package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
- package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +1 -1
- package/tools/node.cmd +0 -3
- package/tools/py.cmd +0 -3
- package/vendor/fonts/zhhand/Xiaolai-Regular.ttf +0 -0
package/src/client/viewer.js
CHANGED
|
@@ -1,80 +1,80 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* PdfViewer — the unified reader face of the rewrite.
|
|
3
|
-
*
|
|
4
|
-
* One component owns: zoom, scroll container, page painting per layer, and the
|
|
5
|
-
* mode layout (single / continuous / dual). Modes only choose which layers and
|
|
6
|
-
* columns are rendered; painting and geometry stay identical, which is what the
|
|
7
|
-
* old per-mode canvases kept getting wrong.
|
|
8
|
-
*
|
|
9
|
-
* This module is the extracted target: `client.js` will mount it once per
|
|
10
|
-
* reader and per side preview, then the legacy paint paths can be deleted.
|
|
11
|
-
*
|
|
12
|
-
* Layers:
|
|
13
|
-
* { kind: 'source', doc }
|
|
14
|
-
* { kind: 'translation', doc }
|
|
15
|
-
* { kind: 'masks', boxes } // reveal boxes over `translation`
|
|
16
|
-
* { kind: 'blocks', blocks } // debug block overlay
|
|
17
|
-
*
|
|
18
|
-
* Geometry rules (from docs/READER-REWRITE.md):
|
|
19
|
-
* - centered content uses `safe center`, so a zoomed page can still scroll to
|
|
20
|
-
* its left edge;
|
|
21
|
-
* - the overlay is ONE page-sized translation image clipped by a `clipPath` of
|
|
22
|
-
* rectangle subpaths per mask (v0.49.2). A per-mask canvas drifted because a
|
|
23
|
-
* zoomed page box is wider than the stage; `maskPageStyle` below is the old
|
|
24
|
-
* per-canvas formula, kept only for reference;
|
|
25
|
-
* - repainting is driven by (doc, page, scale, version), not by DOM mounting.
|
|
26
|
-
*/
|
|
27
|
-
|
|
28
|
-
/** CSS injected once by the viewer's owner. */
|
|
29
|
-
export const VIEWER_STYLE = `
|
|
30
|
-
.mdv-root { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; min-height: 0; }
|
|
31
|
-
.mdv-stage { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
|
32
|
-
.mdv-columns { display: flex; gap: 12px; width: 100%; height: 100%; }
|
|
33
|
-
.mdv-column { flex: 1 1 0; min-width: 0; overflow: auto; }
|
|
34
|
-
.mdv-page { position: relative; margin: 0 auto 18px; width: fit-content; }
|
|
35
|
-
.mdv-canvas { display: block; }
|
|
36
|
-
.mdv-layer { position: absolute; inset: 0; pointer-events: none; }
|
|
37
|
-
.mdv-mask { position: absolute; overflow: hidden; border: 1px dashed rgba(40, 140, 235, .9); box-sizing: border-box; }
|
|
38
|
-
.mdv-mask-page { position: absolute; max-width: none; }
|
|
39
|
-
.mdv-block { position: absolute; border: 1px dashed rgba(235, 70, 70, .85); box-sizing: border-box; }
|
|
40
|
-
.mdv-block[data-kind="heading"] { border-color: rgba(60, 130, 235, .95); }
|
|
41
|
-
.mdv-block[data-kind="formula"] { border-color: rgba(40, 160, 90, .95); }
|
|
42
|
-
`
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Paint one page into a canvas at a given scale.
|
|
46
|
-
* @param {object} options - doc, pageNumber, scale, canvas, signal.
|
|
47
|
-
* @returns {Promise<void>} resolves when the page finished painting.
|
|
48
|
-
*/
|
|
49
|
-
export async function paintPage(options) {
|
|
50
|
-
const { doc, pageNumber, scale, canvas, signal } = options
|
|
51
|
-
const page = await doc.getPage(pageNumber)
|
|
52
|
-
if (signal !== undefined && signal.aborted) return
|
|
53
|
-
const viewport = page.getViewport({ scale })
|
|
54
|
-
let dpr = Math.min(2, Math.max(1, typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1))
|
|
55
|
-
if (viewport.width * dpr > 8000 || viewport.height * dpr > 8000) dpr = 1
|
|
56
|
-
canvas.width = Math.max(1, Math.floor(viewport.width * dpr))
|
|
57
|
-
canvas.height = Math.max(1, Math.floor(viewport.height * dpr))
|
|
58
|
-
canvas.style.width = `${Math.floor(viewport.width)}px`
|
|
59
|
-
canvas.style.height = `${Math.floor(viewport.height)}px`
|
|
60
|
-
await page.render({
|
|
61
|
-
canvasContext: canvas.getContext('2d'),
|
|
62
|
-
viewport,
|
|
63
|
-
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
|
|
64
|
-
}).promise
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/**
|
|
68
|
-
* Compute the geometry a per-mask translated canvas used to need.
|
|
69
|
-
* @deprecated Superseded by the single-image `clipPath` overlay (v0.49.2).
|
|
70
|
-
* @param {{ x: number, y: number, w: number, h: number }} box - normalized box.
|
|
71
|
-
* @returns {{ left: string, top: string, width: string, height: string }} CSS percentages.
|
|
72
|
-
*/
|
|
73
|
-
export function maskPageStyle(box) {
|
|
74
|
-
return {
|
|
75
|
-
left: `${-(box.x / box.w) * 100}%`,
|
|
76
|
-
top: `${-(box.y / box.h) * 100}%`,
|
|
77
|
-
width: `${100 / box.w}%`,
|
|
78
|
-
height: `${100 / box.h}%`,
|
|
79
|
-
}
|
|
80
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* PdfViewer — the unified reader face of the rewrite.
|
|
3
|
+
*
|
|
4
|
+
* One component owns: zoom, scroll container, page painting per layer, and the
|
|
5
|
+
* mode layout (single / continuous / dual). Modes only choose which layers and
|
|
6
|
+
* columns are rendered; painting and geometry stay identical, which is what the
|
|
7
|
+
* old per-mode canvases kept getting wrong.
|
|
8
|
+
*
|
|
9
|
+
* This module is the extracted target: `client.js` will mount it once per
|
|
10
|
+
* reader and per side preview, then the legacy paint paths can be deleted.
|
|
11
|
+
*
|
|
12
|
+
* Layers:
|
|
13
|
+
* { kind: 'source', doc }
|
|
14
|
+
* { kind: 'translation', doc }
|
|
15
|
+
* { kind: 'masks', boxes } // reveal boxes over `translation`
|
|
16
|
+
* { kind: 'blocks', blocks } // debug block overlay
|
|
17
|
+
*
|
|
18
|
+
* Geometry rules (from docs/READER-REWRITE.md):
|
|
19
|
+
* - centered content uses `safe center`, so a zoomed page can still scroll to
|
|
20
|
+
* its left edge;
|
|
21
|
+
* - the overlay is ONE page-sized translation image clipped by a `clipPath` of
|
|
22
|
+
* rectangle subpaths per mask (v0.49.2). A per-mask canvas drifted because a
|
|
23
|
+
* zoomed page box is wider than the stage; `maskPageStyle` below is the old
|
|
24
|
+
* per-canvas formula, kept only for reference;
|
|
25
|
+
* - repainting is driven by (doc, page, scale, version), not by DOM mounting.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** CSS injected once by the viewer's owner. */
|
|
29
|
+
export const VIEWER_STYLE = `
|
|
30
|
+
.mdv-root { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; min-height: 0; }
|
|
31
|
+
.mdv-stage { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
|
32
|
+
.mdv-columns { display: flex; gap: 12px; width: 100%; height: 100%; }
|
|
33
|
+
.mdv-column { flex: 1 1 0; min-width: 0; overflow: auto; }
|
|
34
|
+
.mdv-page { position: relative; margin: 0 auto 18px; width: fit-content; }
|
|
35
|
+
.mdv-canvas { display: block; }
|
|
36
|
+
.mdv-layer { position: absolute; inset: 0; pointer-events: none; }
|
|
37
|
+
.mdv-mask { position: absolute; overflow: hidden; border: 1px dashed rgba(40, 140, 235, .9); box-sizing: border-box; }
|
|
38
|
+
.mdv-mask-page { position: absolute; max-width: none; }
|
|
39
|
+
.mdv-block { position: absolute; border: 1px dashed rgba(235, 70, 70, .85); box-sizing: border-box; }
|
|
40
|
+
.mdv-block[data-kind="heading"] { border-color: rgba(60, 130, 235, .95); }
|
|
41
|
+
.mdv-block[data-kind="formula"] { border-color: rgba(40, 160, 90, .95); }
|
|
42
|
+
`
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Paint one page into a canvas at a given scale.
|
|
46
|
+
* @param {object} options - doc, pageNumber, scale, canvas, signal.
|
|
47
|
+
* @returns {Promise<void>} resolves when the page finished painting.
|
|
48
|
+
*/
|
|
49
|
+
export async function paintPage(options) {
|
|
50
|
+
const { doc, pageNumber, scale, canvas, signal } = options
|
|
51
|
+
const page = await doc.getPage(pageNumber)
|
|
52
|
+
if (signal !== undefined && signal.aborted) return
|
|
53
|
+
const viewport = page.getViewport({ scale })
|
|
54
|
+
let dpr = Math.min(2, Math.max(1, typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1))
|
|
55
|
+
if (viewport.width * dpr > 8000 || viewport.height * dpr > 8000) dpr = 1
|
|
56
|
+
canvas.width = Math.max(1, Math.floor(viewport.width * dpr))
|
|
57
|
+
canvas.height = Math.max(1, Math.floor(viewport.height * dpr))
|
|
58
|
+
canvas.style.width = `${Math.floor(viewport.width)}px`
|
|
59
|
+
canvas.style.height = `${Math.floor(viewport.height)}px`
|
|
60
|
+
await page.render({
|
|
61
|
+
canvasContext: canvas.getContext('2d'),
|
|
62
|
+
viewport,
|
|
63
|
+
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
|
|
64
|
+
}).promise
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Compute the geometry a per-mask translated canvas used to need.
|
|
69
|
+
* @deprecated Superseded by the single-image `clipPath` overlay (v0.49.2).
|
|
70
|
+
* @param {{ x: number, y: number, w: number, h: number }} box - normalized box.
|
|
71
|
+
* @returns {{ left: string, top: string, width: string, height: string }} CSS percentages.
|
|
72
|
+
*/
|
|
73
|
+
export function maskPageStyle(box) {
|
|
74
|
+
return {
|
|
75
|
+
left: `${-(box.x / box.w) * 100}%`,
|
|
76
|
+
top: `${-(box.y / box.h) * 100}%`,
|
|
77
|
+
width: `${100 / box.w}%`,
|
|
78
|
+
height: `${100 / box.h}%`,
|
|
79
|
+
}
|
|
80
|
+
}
|
package/src/host/artifacts.js
CHANGED
|
@@ -43,19 +43,46 @@ const TEXT_EXTENSIONS = new Set([
|
|
|
43
43
|
/** Extensions shown as an image badge; the reader does not draw them yet. */
|
|
44
44
|
const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'avif'])
|
|
45
45
|
|
|
46
|
+
/** Word documents: listed, but previewed by DSH/Office rather than in this plugin. */
|
|
47
|
+
const OFFICE_EXTENSIONS = new Set(['doc', 'docx'])
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Products the workbench lists. This is a whitelist on purpose: a chapter
|
|
51
|
+
* directory also holds build intermediates (`tex`, `aox`/`aux`/`log`/`out`/
|
|
52
|
+
* `bbl`/`blg`/`synctex` …), spreadsheets, slides and scratch files. None of
|
|
53
|
+
* them are reading material here, and an extension nobody thought of must not
|
|
54
|
+
* leak into the list. The files stay on disk untouched; only the listing
|
|
55
|
+
* ignores them.
|
|
56
|
+
*/
|
|
57
|
+
const VISIBLE_EXTENSIONS = new Set([
|
|
58
|
+
'pdf', 'md', 'markdown', 'doc', 'docx',
|
|
59
|
+
'png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'avif',
|
|
60
|
+
])
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Whether one produced file belongs in the list.
|
|
64
|
+
* @param {string} name - file name.
|
|
65
|
+
* @returns {boolean} true when the row should be shown.
|
|
66
|
+
*/
|
|
67
|
+
function visibleName(name) {
|
|
68
|
+
const extension = extname(name).replace(/^\./, '').toLowerCase()
|
|
69
|
+
return VISIBLE_EXTENSIONS.has(extension)
|
|
70
|
+
}
|
|
71
|
+
|
|
46
72
|
/** Decoders tried in order for a preview; UTF-8 first, then the common Chinese Windows code page. */
|
|
47
73
|
const DECODERS = ['utf-8', 'gb18030']
|
|
48
74
|
|
|
49
75
|
/**
|
|
50
76
|
* The kind shown as a badge and used to decide whether the reader can draw it.
|
|
51
77
|
* @param {string} name - file name.
|
|
52
|
-
* @returns {'pdf' | 'text' | 'image' | 'other'} the kind.
|
|
78
|
+
* @returns {'pdf' | 'text' | 'image' | 'office' | 'other'} the kind.
|
|
53
79
|
*/
|
|
54
80
|
export function kindOf(name) {
|
|
55
81
|
const extension = extname(name).replace(/^\./, '').toLowerCase()
|
|
56
82
|
if (extension === 'pdf') return 'pdf'
|
|
57
83
|
if (TEXT_EXTENSIONS.has(extension)) return 'text'
|
|
58
84
|
if (IMAGE_EXTENSIONS.has(extension)) return 'image'
|
|
85
|
+
if (OFFICE_EXTENSIONS.has(extension)) return 'office'
|
|
59
86
|
return 'other'
|
|
60
87
|
}
|
|
61
88
|
|
|
@@ -202,8 +229,9 @@ async function readingNames(dir) {
|
|
|
202
229
|
return entries
|
|
203
230
|
.filter(entry => entry.isFile() || entry.isSymbolicLink())
|
|
204
231
|
.map(entry => entry.name)
|
|
205
|
-
// Office lock files and editor droppings are noise in a reading list
|
|
206
|
-
|
|
232
|
+
// Office lock files and editor droppings are noise in a reading list; TeX
|
|
233
|
+
// sources, spreadsheets and slides are not reading material for this plugin.
|
|
234
|
+
.filter(name => !name.startsWith('.') && !name.startsWith('~$') && visibleName(name))
|
|
207
235
|
.sort((left, right) => left.localeCompare(right, 'zh'))
|
|
208
236
|
}
|
|
209
237
|
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chapter attachments: user-supplied files kept beside the chapter, outside the
|
|
3
|
+
* PDF reader. A first version accepts PDFs and images; the manifest records what
|
|
4
|
+
* was copied so the browser can list it without rescanning metadata.
|
|
5
|
+
* @module dsh-pdf-workbench/attachments
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { copyFile, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from 'node:fs/promises'
|
|
9
|
+
import { basename, extname, join } from 'node:path'
|
|
10
|
+
|
|
11
|
+
/** Extensions the first version accepts, with the kind shown in the UI. */
|
|
12
|
+
export const ATTACHMENT_KINDS = {
|
|
13
|
+
pdf: 'pdf',
|
|
14
|
+
png: 'image',
|
|
15
|
+
jpg: 'image',
|
|
16
|
+
jpeg: 'image',
|
|
17
|
+
webp: 'image',
|
|
18
|
+
gif: 'image',
|
|
19
|
+
bmp: 'image',
|
|
20
|
+
avif: 'image',
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Per-file ceiling for a copied attachment. */
|
|
24
|
+
export const MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Where one chapter's attachments live.
|
|
28
|
+
* @param {string} libraryDir - the library root.
|
|
29
|
+
* @param {string} book - book id.
|
|
30
|
+
* @param {string} code - chapter code.
|
|
31
|
+
* @returns {string} the absolute directory.
|
|
32
|
+
*/
|
|
33
|
+
export function attachmentsDir(libraryDir, book, code) {
|
|
34
|
+
return join(libraryDir, '.pdfdesk', 'attachments', book, code)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The manifest beside the files.
|
|
39
|
+
* @param {string} libraryDir - the library root.
|
|
40
|
+
* @param {string} book - book id.
|
|
41
|
+
* @param {string} code - chapter code.
|
|
42
|
+
* @returns {string} the manifest path.
|
|
43
|
+
*/
|
|
44
|
+
export function attachmentManifestPath(libraryDir, book, code) {
|
|
45
|
+
return join(attachmentsDir(libraryDir, book, code), 'manifest.json')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Strip directories and characters Windows or the browser would misread.
|
|
50
|
+
* @param {string} value - proposed file name.
|
|
51
|
+
* @returns {string} a safe base name (never empty).
|
|
52
|
+
*/
|
|
53
|
+
export function safeAttachmentName(value) {
|
|
54
|
+
const base = basename(String(value ?? '')).replace(/[<>:"/\\|?*\u0000-\u001f]/g, '_').trim()
|
|
55
|
+
return base === '' || base === '.' || base === '..' ? 'attachment' : base.slice(0, 120)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Read the manifest, tolerating a missing or broken file.
|
|
60
|
+
* @param {string} dir - the chapter's attachment directory.
|
|
61
|
+
* @returns {Promise<{ version: number, items: object[] }>} parsed manifest.
|
|
62
|
+
*/
|
|
63
|
+
async function readManifest(dir) {
|
|
64
|
+
const raw = await readFile(join(dir, 'manifest.json'), 'utf8').catch(() => null)
|
|
65
|
+
if (raw === null) return { version: 1, items: [] }
|
|
66
|
+
try {
|
|
67
|
+
const parsed = JSON.parse(raw)
|
|
68
|
+
const items = Array.isArray(parsed.items) ? parsed.items.filter(item => item !== null && typeof item === 'object' && typeof item.name === 'string') : []
|
|
69
|
+
return { version: 1, items }
|
|
70
|
+
} catch {
|
|
71
|
+
return { version: 1, items: [] }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Write the manifest atomically.
|
|
77
|
+
* @param {string} dir - the chapter's attachment directory.
|
|
78
|
+
* @param {{ version: number, items: object[] }} manifest - the value.
|
|
79
|
+
* @returns {Promise<void>} completion.
|
|
80
|
+
*/
|
|
81
|
+
async function writeManifest(dir, manifest) {
|
|
82
|
+
const path = join(dir, 'manifest.json')
|
|
83
|
+
const temporary = `${path}.${process.pid}.tmp`
|
|
84
|
+
await writeFile(temporary, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
|
|
85
|
+
await copyFile(temporary, path)
|
|
86
|
+
await unlink(temporary).catch(() => {})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* List one chapter's attachments, including files the manifest does not know
|
|
91
|
+
* about yet (a copy interrupted before the manifest write).
|
|
92
|
+
* @param {string} libraryDir - the library root.
|
|
93
|
+
* @param {string} book - book id.
|
|
94
|
+
* @param {string} code - chapter code.
|
|
95
|
+
* @returns {Promise<{ dir: string, items: object[] }>} the manifest items.
|
|
96
|
+
*/
|
|
97
|
+
export async function listAttachments(libraryDir, book, code) {
|
|
98
|
+
const dir = attachmentsDir(libraryDir, book, code)
|
|
99
|
+
const manifest = await readManifest(dir)
|
|
100
|
+
const known = new Set(manifest.items.map(item => item.name))
|
|
101
|
+
const names = await readdir(dir).catch(() => [])
|
|
102
|
+
const extra = []
|
|
103
|
+
for (const name of names) {
|
|
104
|
+
if (name === 'manifest.json' || known.has(name)) continue
|
|
105
|
+
const info = await stat(join(dir, name)).catch(() => null)
|
|
106
|
+
if (info === null || !info.isFile()) continue
|
|
107
|
+
const extension = extname(name).slice(1).toLowerCase()
|
|
108
|
+
if (ATTACHMENT_KINDS[extension] === undefined) continue
|
|
109
|
+
extra.push({ name, kind: ATTACHMENT_KINDS[extension], bytes: info.size, addedAt: info.mtimeMs })
|
|
110
|
+
}
|
|
111
|
+
return { dir, items: [...manifest.items, ...extra] }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Copy one local file into the chapter's attachments.
|
|
116
|
+
* @param {{ libraryDir: string, book: string, code: string, sourcePath: string, name?: string }} options - the library, chapter and source.
|
|
117
|
+
* @returns {Promise<{ name: string, kind: string, bytes: number, addedAt: number }>} the stored item.
|
|
118
|
+
*/
|
|
119
|
+
export async function addAttachment(options) {
|
|
120
|
+
const extension = extname(String(options.sourcePath ?? '')).slice(1).toLowerCase()
|
|
121
|
+
const kind = ATTACHMENT_KINDS[extension]
|
|
122
|
+
if (kind === undefined) throw Object.assign(new Error('只支持 PDF 与图片附件'), { code: 'bad-type' })
|
|
123
|
+
const info = await stat(options.sourcePath)
|
|
124
|
+
if (!info.isFile()) throw Object.assign(new Error('附件必须是文件'), { code: 'not-file' })
|
|
125
|
+
if (info.size > MAX_ATTACHMENT_BYTES) throw Object.assign(new Error('附件超过 50 MB'), { code: 'too-large' })
|
|
126
|
+
const dir = attachmentsDir(options.libraryDir, options.book, options.code)
|
|
127
|
+
await mkdir(dir, { recursive: true })
|
|
128
|
+
const manifest = await readManifest(dir)
|
|
129
|
+
const wanted = safeAttachmentName(options.name ?? options.sourcePath)
|
|
130
|
+
const stem = wanted.slice(0, Math.max(1, wanted.length - extension.length - 1))
|
|
131
|
+
let name = wanted
|
|
132
|
+
let counter = 0
|
|
133
|
+
const taken = new Set([...manifest.items.map(item => item.name), 'manifest.json'])
|
|
134
|
+
while (taken.has(name)) {
|
|
135
|
+
counter += 1
|
|
136
|
+
name = `${stem}-${counter}.${extension}`
|
|
137
|
+
}
|
|
138
|
+
await copyFile(options.sourcePath, join(dir, name))
|
|
139
|
+
const item = { name, kind, bytes: info.size, addedAt: Date.now() }
|
|
140
|
+
manifest.items.push(item)
|
|
141
|
+
await writeManifest(dir, manifest)
|
|
142
|
+
return item
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Delete one attachment and drop it from the manifest.
|
|
147
|
+
* @param {{ libraryDir: string, book: string, code: string, name: string }} options - the library, chapter and file.
|
|
148
|
+
* @returns {Promise<{ removed: boolean }>} whether a file was deleted.
|
|
149
|
+
*/
|
|
150
|
+
export async function removeAttachment(options) {
|
|
151
|
+
const dir = attachmentsDir(options.libraryDir, options.book, options.code)
|
|
152
|
+
const name = safeAttachmentName(options.name)
|
|
153
|
+
const manifest = await readManifest(dir)
|
|
154
|
+
const index = manifest.items.findIndex(item => item.name === name)
|
|
155
|
+
if (index >= 0) manifest.items.splice(index, 1)
|
|
156
|
+
const result = await unlink(join(dir, name)).then(() => true).catch(() => false)
|
|
157
|
+
if (index >= 0 || result) await writeManifest(dir, manifest)
|
|
158
|
+
return { removed: result || index >= 0 }
|
|
159
|
+
}
|