// Plays on disk, one directory each under DATA_DIR/plays//: // meta.json { id, title, note, published, status, created, updated, images, pages, progress, model } // play.txt the markup // img/NNN.jpg the uploaded page photos, in upload order // Writes go to a temp file and are renamed into place so a crash never leaves half a file. import { mkdir, readFile, writeFile, rename, readdir, rm, cp, stat } from "node:fs/promises"; import { randomBytes } from "node:crypto"; import path from "node:path"; const ID_RE = /^[a-z0-9][a-z0-9-]{0,79}$/; export class NotFound extends Error {} export function slugify(title) { const base = title.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase() .replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50) || "hra"; return `${base}-${randomBytes(3).toString("hex")}`; } export function createStore(dataDir) { const root = path.join(dataDir, "plays"); const dir = (id) => { if (!ID_RE.test(id)) throw new NotFound(id); return path.join(root, id); }; async function atomicWrite(file, data) { const tmp = `${file}.${randomBytes(4).toString("hex")}.tmp`; await writeFile(tmp, data); await rename(tmp, file); } async function getMeta(id) { try { return JSON.parse(await readFile(path.join(dir(id), "meta.json"), "utf8")); } catch (err) { if (err.code === "ENOENT") throw new NotFound(id); throw err; } } // Serialise read-modify-write of one play's meta (the transcription job and // HTTP requests both update it). const locks = new Map(); function updateMeta(id, fn) { const run = (locks.get(id) || Promise.resolve()).then(async () => { const meta = await getMeta(id); const next = { ...meta, ...(await fn(meta)), updated: new Date().toISOString() }; await atomicWrite(path.join(dir(id), "meta.json"), JSON.stringify(next, null, 2)); return next; }); locks.set(id, run.catch(() => {})); return run; } return { root, async init() { await mkdir(root, { recursive: true }); }, async list() { const ids = (await readdir(root, { withFileTypes: true })).filter((d) => d.isDirectory() && ID_RE.test(d.name)); const metas = await Promise.all(ids.map((d) => getMeta(d.name).catch(() => null))); return metas.filter(Boolean).sort((a, b) => a.title.localeCompare(b.title, "cs")); }, getMeta, updateMeta, async create({ title, note = "", id = slugify(title), text = "", published = false, status = "draft" }) { const d = dir(id); await mkdir(path.join(d, "img"), { recursive: true }); const now = new Date().toISOString(); const meta = { id, title, note, published, status, created: now, updated: now, images: 0, pages: [], progress: null }; await atomicWrite(path.join(d, "play.txt"), text); await atomicWrite(path.join(d, "meta.json"), JSON.stringify(meta, null, 2)); return meta; }, async getText(id) { try { return await readFile(path.join(dir(id), "play.txt"), "utf8"); } catch (err) { if (err.code === "ENOENT") throw new NotFound(id); throw err; } }, async setText(id, text) { await getMeta(id); await atomicWrite(path.join(dir(id), "play.txt"), text); }, imagePath(id, n) { if (!Number.isInteger(n) || n < 1 || n > 999) throw new NotFound(`${id}/${n}`); return path.join(dir(id), "img", `${String(n).padStart(3, "0")}.jpg`); }, async putImage(id, n, buf) { const file = this.imagePath(id, n); await mkdir(path.dirname(file), { recursive: true }); // seeded plays come without img/ await atomicWrite(file, buf); }, async getImage(id, n) { try { return await readFile(this.imagePath(id, n)); } catch (err) { if (err.code === "ENOENT") throw new NotFound(`${id}/${n}`); throw err; } }, async clearImages(id) { const d = path.join(dir(id), "img"); await rm(d, { recursive: true, force: true }); await mkdir(d); }, async remove(id) { await getMeta(id); await rm(dir(id), { recursive: true, force: true }); }, // First start with an empty volume: copy in the plays bundled with the image. async seed(seedDir) { if ((await readdir(root)).length) return 0; let n = 0; for (const d of await readdir(seedDir).catch(() => [])) { if (!ID_RE.test(d) || !(await stat(path.join(seedDir, d))).isDirectory()) continue; await cp(path.join(seedDir, d), path.join(root, d), { recursive: true }); n++; } return n; }, }; }