Repository Public
1/**2 * Chunked, resumable uploads. Large bodies do not pass the gateway, so a file travels in pieces of a few MB:3 *4 * 1. init name, size, purpose and a fingerprint (SHA-256 over the SHA-256 of every chunk). The same5 * file asked again resumes the same upload; a file already stored is reported as a duplicate.6 * 2. chunks PUT one piece at a time, each with its SHA-256; a piece that does not hash to what was7 * announced is refused. Sending a piece twice is harmless.8 * 3. complete the pieces are assembled, the fingerprint is recomputed from what was really received, the9 * whole file is hashed (that SHA-256 is its identity from then on) and its content is checked10 * against its extension by magic bytes. Only then does it leave the staging directory.11 *12 * Nothing under uploads/ is ever served. Each purpose then has its own finaliser (finaliseUpload).13 */14import { createHash } from "node:crypto";15import { createReadStream, createWriteStream, existsSync } from "node:fs";16import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";17import { dirname, join } from "node:path";18import { pipeline } from "node:stream/promises";19import { env } from "../lib/env";20import { Transcript, isSafeRelPath } from "../modules/content-schema/schema";21import { parseVtt, toVtt } from "../modules/learning-engine/vtt";22import { extractArchive, ArchiveError } from "./archive";23import { audit } from "./audit";24import { langLabel, normaliseLang, toTranscript, validateCaptions, type CaptionReport } from "./captions";25import { ChaptersInput, addResourceVersion, getCapsule, getResource, getSessionRow, writeCapsule, type CapsuleRow, type ResourceRow } from "./content";26import { randomId, sha256 } from "./crypto";27import { all, get, now, run, tx } from "./db";28import { ApiError } from "./http";29import { enqueue } from "./jobs";30import { RESOURCE_TYPES, contentMismatch, extOf, extensionAccepted, acceptedExtensions, safeFilename, type Purpose } from "./magic";31import { importDeck } from "./slides";32import { paths, roomFor, storageUsage } from "./storage";33import { prepareImport, type ImportDiff, type ImportRecord } from "./sync";3435export const CHUNK_SIZE = 4 * 1024 * 1024;36const PURPOSES: Purpose[] = ["master", "resource", "captions", "transcript", "archive", "slides"];37const maxBytes = (p: Purpose) => (p === "master" ? env.maxMasterBytes : p === "resource" ? env.maxResourceBytes : p === "archive" ? env.maxArchiveBytes : p === "slides" ? 200_000_000 : 5_000_000);3839export interface Upload { id: string; purpose: Purpose; filename: string; size: number; chunkSize: number; totalChunks: number; fingerprint: string; context: Record<string, unknown>; status: "open" | "complete" | "failed" | "aborted"; sha256: string | null; error: string | null; result: unknown; createdAt: string; createdBy: string }40interface Raw { id: string; purpose: Purpose; filename: string; size: number; chunk_size: number; total_chunks: number; fingerprint: string; context: string; status: Upload["status"]; sha256: string | null; error: string | null; result: string | null; created_at: string; created_by: string }41const toUpload = (r: Raw): Upload => ({ id: r.id, purpose: r.purpose, filename: r.filename, size: r.size, chunkSize: r.chunk_size, totalChunks: r.total_chunks, fingerprint: r.fingerprint, context: JSON.parse(r.context) as Record<string, unknown>, status: r.status, sha256: r.sha256, error: r.error, result: r.result ? JSON.parse(r.result) as unknown : null, createdAt: r.created_at, createdBy: r.created_by });4243export function getUpload(id: string): Upload {44 const r = /^up_[a-f0-9]{16}$/.test(id) ? get<Raw>("SELECT * FROM uploads WHERE id = ?", id) : undefined;45 if (!r) throw new ApiError(404, "not_found", "Téléversement introuvable.");46 return toUpload(r);47}48export const receivedChunks = (id: string) => all<{ n: number }>("SELECT n FROM upload_chunks WHERE upload_id = ? ORDER BY n", id).map((r) => r.n);49const dirOf = (id: string) => join(paths.uploads, id);5051export interface InitResult { upload: Upload; received: number[]; resumed: boolean; duplicate: { sha256: string; filename: string; at: string } | null; warning: string | null }5253export async function initUpload(input: { purpose?: unknown; filename?: unknown; size?: unknown; fingerprint?: unknown; context?: unknown }, actor: string): Promise<InitResult> {54 const purpose = input.purpose as Purpose;55 if (!PURPOSES.includes(purpose)) throw new ApiError(400, "invalid", "Destination de téléversement inconnue.");56 if (typeof input.filename !== "string" || !input.filename.trim() || input.filename.length > 300) throw new ApiError(400, "invalid", "Nom de fichier manquant.");57 const filename = safeFilename(input.filename), size = input.size;58 if (typeof size !== "number" || !Number.isInteger(size) || size <= 0) throw new ApiError(400, "invalid", "Le fichier est vide.");59 if (size > maxBytes(purpose)) throw new ApiError(413, "too_large", `Fichier trop volumineux : ${(size / 1e6).toFixed(0)} Mo, pour une limite de ${(maxBytes(purpose) / 1e6).toFixed(0)} Mo.`);60 if (!extensionAccepted(purpose, filename)) throw new ApiError(415, "bad_type", `Type de fichier non accepté ici (.${extOf(filename) || "?"}). Acceptés : ${acceptedExtensions(purpose).map((e) => `.${e}`).join(", ")}.`);61 if (typeof input.fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(input.fingerprint)) throw new ApiError(400, "invalid", "Empreinte du fichier manquante.");62 const context = checkContext(purpose, input.context);6364 const usage = await storageUsage(), room = await roomFor(size, purpose === "master" ? 2 : 1);65 if (!room.ok) throw new ApiError(507, "no_space", room.reason!);6667 // The same bytes, already received in full for the same purpose: say so before anything travels.68 const twin = get<Raw>("SELECT * FROM uploads WHERE fingerprint = ? AND size = ? AND purpose = ? AND status = 'complete' AND sha256 IS NOT NULL ORDER BY completed_at DESC LIMIT 1", input.fingerprint, size, purpose);69 const duplicate = twin && (purpose !== "master" || masterPath(twin.sha256!)) ? { sha256: twin.sha256!, filename: twin.filename, at: twin.created_at } : null;7071 const open = get<Raw>("SELECT * FROM uploads WHERE fingerprint = ? AND size = ? AND purpose = ? AND status = 'open' AND created_by = ? ORDER BY created_at DESC LIMIT 1", input.fingerprint, size, purpose, actor);72 if (open && existsSync(dirOf(open.id))) {73 run("UPDATE uploads SET context = ?, filename = ? WHERE id = ?", JSON.stringify(context), filename, open.id);74 return { upload: getUpload(open.id), received: receivedChunks(open.id), resumed: true, duplicate, warning: usage.message };75 }76 const id = `up_${randomId(8)}`;77 await mkdir(dirOf(id), { recursive: true });78 run("INSERT INTO uploads (id, purpose, filename, size, chunk_size, total_chunks, fingerprint, context, status, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)",79 id, purpose, filename, size, CHUNK_SIZE, Math.ceil(size / CHUNK_SIZE), input.fingerprint, JSON.stringify(context), now(), actor);80 return { upload: getUpload(id), received: [], resumed: false, duplicate, warning: usage.message };81}8283/** What each purpose needs to know about its destination; checked at init so a bad request fails before any byte is sent. */84function checkContext(purpose: Purpose, raw: unknown): Record<string, unknown> {85 const c = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;86 if (purpose === "archive") return {};87 const sessionId = typeof c.sessionId === "string" ? c.sessionId : "";88 getSessionRow(sessionId);89 if (purpose === "slides") return { sessionId };90 if (purpose === "resource") {91 if (typeof c.resourceId === "string" && c.resourceId) { getResource(sessionId, c.resourceId); return { sessionId, resourceId: c.resourceId, note: typeof c.note === "string" ? c.note.slice(0, 300) : undefined }; }92 return { sessionId, meta: c.meta };93 }94 const capsuleId = typeof c.capsuleId === "string" ? c.capsuleId : "";95 getCapsule(sessionId, capsuleId);96 if (purpose === "master") return { sessionId, capsuleId };97 const lang = normaliseLang(typeof c.lang === "string" ? c.lang : "fr-CA");98 if (!lang) throw new ApiError(400, "bad_lang", "Code de langue invalide (exemples : fr-CA, en).");99 return { sessionId, capsuleId, lang, alsoTranscript: c.alsoTranscript === true };100}101102export async function putChunk(id: string, n: number, body: Buffer, declaredSha: string | null): Promise<{ received: number; total: number }> {103 const up = getUpload(id);104 if (up.status !== "open") throw new ApiError(409, "closed", "Ce téléversement est terminé ou abandonné.");105 if (!Number.isInteger(n) || n < 0 || n >= up.totalChunks) throw new ApiError(400, "bad_chunk", "Numéro de morceau hors limites.");106 const expected = n === up.totalChunks - 1 ? up.size - up.chunkSize * (up.totalChunks - 1) : up.chunkSize;107 if (body.length !== expected) throw new ApiError(400, "bad_chunk", `Taille de morceau inattendue (${body.length} octets au lieu de ${expected}).`);108 const hash = sha256(body);109 if (!declaredSha || declaredSha !== hash) throw new ApiError(422, "checksum", "Le morceau reçu ne correspond pas à son empreinte SHA-256 : il a été altéré en chemin. Renvoyez-le.");110 const file = join(dirOf(id), String(n).padStart(6, "0")), tmp = `${file}.${randomId(4)}.tmp`;111 await writeFile(tmp, body);112 await rename(tmp, file);113 run("INSERT INTO upload_chunks (upload_id, n, sha256, bytes) VALUES (?, ?, ?, ?) ON CONFLICT (upload_id, n) DO UPDATE SET sha256 = excluded.sha256, bytes = excluded.bytes", id, n, hash, body.length);114 return { received: receivedChunks(id).length, total: up.totalChunks };115}116117export async function abortUpload(id: string, actor: string): Promise<void> {118 const up = getUpload(id);119 if (up.status === "open") { run("UPDATE uploads SET status = 'aborted', completed_at = ? WHERE id = ?", now(), id); audit("upload.aborted", { actor, target: `upload:${id}`, detail: { filename: up.filename } }); }120 await rm(dirOf(id), { recursive: true, force: true });121}122123/** Removes uploads left open for more than two days, and their chunks. Run by the worker. */124export async function sweepUploads(olderThanMs = 48 * 3_600_000): Promise<number> {125 const stale = all<{ id: string }>("SELECT id FROM uploads WHERE status = 'open' AND created_at < ?", new Date(Date.now() - olderThanMs).toISOString());126 for (const { id } of stale) { run("UPDATE uploads SET status = 'aborted', completed_at = ?, error = 'abandonné : aucun envoi depuis deux jours' WHERE id = ?", now(), id); await rm(dirOf(id), { recursive: true, force: true }); }127 return stale.length;128}129130const masterPath = (hash: string) => { const m = get<{ ext: string }>("SELECT ext FROM masters WHERE sha256 = ?", hash); const p = m ? join(/* turbopackIgnore: true */ paths.masters, `${hash}.${m.ext}`) : null; return p && existsSync(p) ? p : null; };131export const masterFile = masterPath;132133export type FinalResult =134 | { kind: "master"; sha256: string; capsule: CapsuleRow; jobId: number; duplicate: boolean }135 | { kind: "resource"; sha256: string; resource: ResourceRow }136 | { kind: "captions"; sha256: string; capsule: CapsuleRow; report: CaptionReport }137 | { kind: "transcript"; sha256: string; capsule: CapsuleRow; segments: number }138 | { kind: "slides"; sha256: string; session: string; slides: number; changed: boolean; warnings: string[] }139 | { kind: "archive"; sha256: string; record: ImportRecord; diff: ImportDiff; extracted: { files: number; bytes: number; skipped: Record<string, number> } };140141const completing = new Set<string>();142143/** Assembles, verifies and files an upload. Any refusal deletes what was received. */144export async function completeUpload(id: string, actor: string): Promise<FinalResult> {145 if (completing.has(id)) throw new ApiError(409, "busy", "Ce téléversement est déjà en cours de finalisation.");146 completing.add(id);147 try { return await completeOnce(id, actor); } finally { completing.delete(id); }148}149150async function completeOnce(id: string, actor: string): Promise<FinalResult> {151 const up = getUpload(id);152 if (up.status === "complete" && up.result) return up.result as FinalResult;153 if (up.status !== "open") throw new ApiError(409, "closed", "Ce téléversement est terminé ou abandonné.");154 const chunks = all<{ n: number; sha256: string; bytes: number }>("SELECT n, sha256, bytes FROM upload_chunks WHERE upload_id = ? ORDER BY n", id);155 if (chunks.length !== up.totalChunks) throw new ApiError(409, "incomplete", `Il manque ${up.totalChunks - chunks.length} morceau(x) sur ${up.totalChunks}.`, { received: chunks.map((c) => c.n) });156 const refuse = async (status: number, code: string, message: string): Promise<never> => {157 run("UPDATE uploads SET status = 'failed', error = ?, completed_at = ? WHERE id = ?", message, now(), id);158 await rm(dirOf(id), { recursive: true, force: true });159 audit("upload.refused", { actor, target: `upload:${id}`, detail: { filename: up.filename, purpose: up.purpose, reason: code } });160 throw new ApiError(status, code, message);161 };162 if (sha256(chunks.map((c) => c.sha256).join("")) !== up.fingerprint) await refuse(422, "checksum", "Les morceaux reçus ne correspondent pas à l'empreinte annoncée du fichier. Recommencez le téléversement.");163164 const assembled = join(dirOf(id), "assembled"), whole = createHash("sha256"), out = createWriteStream(assembled);165 let size = 0;166 for (const c of chunks) {167 const piece = createHash("sha256");168 await pipeline(createReadStream(join(dirOf(id), String(c.n).padStart(6, "0"))), async function* (source) { for await (const d of source) { whole.update(d as Buffer); piece.update(d as Buffer); size += (d as Buffer).length; yield d as Buffer; } }, out, { end: false });169 // Re-checked from disk: a chunk file damaged after it was received is caught here.170 if (piece.digest("hex") !== c.sha256) { out.destroy(); await refuse(422, "checksum", "Un morceau s'est altéré sur le disque du serveur. Recommencez le téléversement."); }171 }172 await new Promise<void>((res, rej) => out.end((e?: Error | null) => (e ? rej(e) : res())));173 const hash = whole.digest("hex");174 if (size !== up.size) await refuse(422, "checksum", "La taille du fichier assemblé ne correspond pas à la taille annoncée.");175176 const fh = await open(assembled, "r"), head = Buffer.alloc(Math.min(4096, size));177 try { await fh.read(head, 0, head.length, 0); } finally { await fh.close(); }178 const mismatch = contentMismatch(up.purpose, up.filename, head);179 if (mismatch) await refuse(415, "bad_content", mismatch);180181 let result: FinalResult;182 try { result = await finalise(up, assembled, hash, actor); }183 catch (e) {184 if (e instanceof ApiError) await refuse(e.status, e.code, e.message);185 if (e instanceof ArchiveError) await refuse(422, "bad_archive", e.message);186 throw e;187 }188 run("UPDATE uploads SET status = 'complete', sha256 = ?, result = ?, completed_at = ? WHERE id = ?", hash, JSON.stringify(result), now(), id);189 await rm(dirOf(id), { recursive: true, force: true });190 audit("upload.completed", { actor, target: `upload:${id}`, detail: { filename: up.filename, purpose: up.purpose, bytes: up.size, sha256: hash } });191 return result;192}193194async function finalise(up: Upload, file: string, hash: string, actor: string): Promise<FinalResult> {195 const c = up.context, sessionId = c.sessionId as string, capsuleId = c.capsuleId as string;196 switch (up.purpose) {197 case "master": {198 const ext = extOf(up.filename), existing = masterPath(hash), target = join(/* turbopackIgnore: true */ paths.masters, `${hash}.${ext}`);199 if (!existing) {200 await mkdir(paths.masters, { recursive: true });201 await rename(file, target); // the master is kept as received, under its own hash: it is never modified afterwards202 run("INSERT INTO masters (sha256, filename, ext, bytes, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (sha256) DO UPDATE SET ext = excluded.ext", hash, up.filename, ext, up.size, now(), actor);203 }204 return { kind: "master", sha256: hash, duplicate: Boolean(existing), ...attachMaster(sessionId, capsuleId, hash, actor) };205 }206 case "resource": {207 const ext = extOf(up.filename), rel = `${sessionId}/${hash.slice(0, 16)}/${up.filename}`;208 if (!isSafeRelPath(rel)) throw new ApiError(400, "invalid", "Nom de fichier non accepté.");209 if (typeof c.resourceId === "string") { const cur = getResource(sessionId, c.resourceId); if (cur.versions.find((v) => v.version === cur.currentVersion)?.sha256 === hash) throw new ApiError(409, "duplicate", "Ce fichier est identique à la version actuelle de la ressource : rien n'a été remplacé."); }210 const target = join(paths.resources, rel);211 await mkdir(dirname(target), { recursive: true });212 if (existsSync(target)) await rm(file, { force: true }); else await rename(file, target);213 const resource = addResourceVersion(sessionId, { id: c.resourceId as string | undefined, meta: c.meta, note: c.note as string | undefined, file: { path: rel, bytes: up.size, sha256: hash, mime: RESOURCE_TYPES[ext]!.mime, filename: up.filename } }, actor);214 return { kind: "resource", sha256: hash, resource };215 }216 case "captions": {217 const text = await readFile(file, "utf8");218 const { capsule, report } = await attachCaptions(sessionId, capsuleId, text, c.lang as string, { alsoTranscript: c.alsoTranscript === true }, actor);219 return { kind: "captions", sha256: hash, capsule, report };220 }221 case "transcript": {222 const text = await readFile(file, "utf8");223 const { capsule, segments } = await attachTranscript(sessionId, capsuleId, text, extOf(up.filename) === "json" ? "json" : "vtt", c.lang as string, actor);224 return { kind: "transcript", sha256: hash, capsule, segments };225 }226 case "slides": {227 // A slide pack built elsewhere (poppler is not needed here): validated file by file, installed as a private section.228 const { deck, changed } = await importDeck(file, actor, sessionId);229 return { kind: "slides", sha256: hash, session: deck.session, slides: deck.count, changed, warnings: deck.warnings };230 }231 case "archive": {232 const repo = join(paths.work, `${up.id}-repo`);233 await rm(repo, { recursive: true, force: true });234 try {235 const report = await extractArchive(file, repo, { maxEntries: 20_000, maxFileBytes: 50_000_000, maxTotalBytes: Math.max(600_000_000, up.size * 4), maxRatio: 200 });236 // `git archive` puts files at the root; an archive made by hand usually wraps them in one folder.237 let root = repo;238 if (!existsSync(join(repo, "course.yaml"))) {239 const top = (await readdir(repo, { withFileTypes: true })).filter((e) => e.isDirectory());240 const inner = top.find((d) => existsSync(join(repo, d.name, "course.yaml")));241 if (!inner) throw new ApiError(422, "not_a_course", "Cette archive ne contient pas de course.yaml : ce n'est pas un instantané du dépôt du cours.");242 root = join(repo, inner.name);243 }244 const { record, diff } = await prepareImport(root, `Archive téléversée : ${up.filename}`, actor);245 return { kind: "archive", sha256: hash, record, diff, extracted: { files: report.files, bytes: report.bytes, skipped: report.skipped } };246 } finally { await rm(repo, { recursive: true, force: true }); }247 }248 }249}250251/* ---- Finalisers shared with the API (a duplicate master is attached without a new upload) ---- */252253/** Points a capsule at a stored master and queues its encode. */254export function attachMaster(sessionId: string, capsuleId: string, hash: string, actor: string): { capsule: CapsuleRow; jobId: number } {255 if (!masterPath(hash)) throw new ApiError(404, "not_found", "Ce fichier maître n'est plus dans le stockage.");256 return tx(() => {257 const cap = getCapsule(sessionId, capsuleId);258 if (cap.status === "queued" || cap.status === "processing") throw new ApiError(409, "busy", "Un traitement est déjà en cours pour cette capsule. Attendez sa fin ou annulez-le.");259 writeCapsule({ ...cap, masterSha: hash, status: "queued" }, actor);260 const jobId = enqueue("transcode", { sessionId, capsuleId, masterSha: hash }, actor);261 audit("capsule.master_attached", { actor, target: `session:${sessionId}/capsule:${capsuleId}`, detail: { sha256: hash, jobId } });262 return { capsule: getCapsule(sessionId, capsuleId), jobId };263 });264}265266/** Writes a small sidecar file next to the capsule's media, under a name derived from its content (never overwritten). */267async function writeSidecar(sessionId: string, capsuleId: string, stem: string, ext: string, body: string): Promise<string> {268 const rel = `${sessionId}/${capsuleId}/${stem}.${sha256(body).slice(0, 10)}.${ext}`;269 if (!isSafeRelPath(rel)) throw new ApiError(400, "invalid", "Chemin de média invalide.");270 const target = join(/* turbopackIgnore: true */ paths.media, rel);271 await mkdir(dirname(target), { recursive: true });272 if (!existsSync(target)) { const tmp = `${target}.${randomId(4)}.tmp`; await writeFile(tmp, body); await rename(tmp, target); }273 return rel;274}275276/** Validates a WebVTT file and attaches it as the caption track of its language. Errors refuse it; warnings come back. */277export async function attachCaptions(sessionId: string, capsuleId: string, source: string, langInput: string, o: { alsoTranscript?: boolean; dryRun?: boolean }, actor: string): Promise<{ capsule: CapsuleRow; report: CaptionReport }> {278 const lang = normaliseLang(langInput);279 if (!lang) throw new ApiError(400, "bad_lang", "Code de langue invalide (exemples : fr-CA, en).");280 const cap = getCapsule(sessionId, capsuleId), report = validateCaptions(source, { videoDuration: cap.data.durationSeconds });281 if (o.dryRun) return { capsule: cap, report };282 if (!report.ok) throw new ApiError(422, "bad_captions", `Sous-titres refusés : ${report.errors.slice(0, 3).join(" ; ")}${report.errors.length > 3 ? ` (et ${report.errors.length - 3} autres)` : ""}.`, { report: { ...report, preview: [] } });283 // Stored normalised (UTF-8, LF, cue text without markup): what was validated is exactly what is served.284 const rel = await writeSidecar(sessionId, capsuleId, `captions.${lang}`, "vtt", toVtt(parseVtt(source).cues));285 let transcript: string | undefined;286 if (o.alsoTranscript || !cap.data.media.transcript) transcript = await writeSidecar(sessionId, capsuleId, "transcript", "json", `${JSON.stringify(toTranscript(source, "vtt", lang).transcript, null, 2)}\n`);287 const capsule = tx(() => {288 const cur = getCapsule(sessionId, capsuleId);289 const captions = [...cur.data.media.captions.filter((t) => t.lang !== lang), { lang, label: langLabel(lang), path: rel }].sort((a, b) => Number(b.lang.startsWith("fr")) - Number(a.lang.startsWith("fr")) || a.lang.localeCompare(b.lang));290 const data = { ...cur.data, media: { ...cur.data.media, captions, ...(transcript ? { transcript } : {}) } };291 writeCapsule({ ...cur, data }, actor);292 audit("capsule.captions_attached", { actor, target: `session:${sessionId}/capsule:${capsuleId}`, before: cur.data.media, after: data.media, detail: { lang, cues: report.cues, warnings: report.warnings.length, transcript: Boolean(transcript) } });293 return getCapsule(sessionId, capsuleId);294 });295 return { capsule, report };296}297298export function removeCaptions(sessionId: string, capsuleId: string, lang: string, actor: string): CapsuleRow {299 return tx(() => {300 const cur = getCapsule(sessionId, capsuleId), data = { ...cur.data, media: { ...cur.data.media, captions: cur.data.media.captions.filter((t) => t.lang !== lang) } };301 writeCapsule({ ...cur, data }, actor);302 audit("capsule.captions_removed", { actor, target: `session:${sessionId}/capsule:${capsuleId}`, before: cur.data.media, after: data.media, detail: { lang } });303 return getCapsule(sessionId, capsuleId);304 });305}306307/** Imports a transcript (WebVTT or JSON) into the searchable format read by the player and the search index. */308export async function attachTranscript(sessionId: string, capsuleId: string, source: string, format: "vtt" | "json", langInput: string, actor: string): Promise<{ capsule: CapsuleRow; segments: number }> {309 const lang = normaliseLang(langInput) ?? "fr-CA", { transcript, errors } = toTranscript(source, format, lang);310 if (errors.length) throw new ApiError(422, "bad_transcript", `Transcription refusée : ${errors.slice(0, 3).join(" ; ")}.`);311 const parsed = Transcript.safeParse(transcript);312 if (!parsed.success) throw new ApiError(422, "bad_transcript", "Transcription refusée : segments invalides.");313 const rel = await writeSidecar(sessionId, capsuleId, "transcript", "json", `${JSON.stringify(parsed.data, null, 2)}\n`);314 const capsule = tx(() => {315 const cur = getCapsule(sessionId, capsuleId), data = { ...cur.data, media: { ...cur.data.media, transcript: rel } };316 writeCapsule({ ...cur, data }, actor);317 audit("capsule.transcript_attached", { actor, target: `session:${sessionId}/capsule:${capsuleId}`, before: cur.data.media, after: data.media, detail: { segments: parsed.data.segments.length, format } });318 return getCapsule(sessionId, capsuleId);319 });320 return { capsule, segments: parsed.data.segments.length };321}322323/** Saves the chapter list of a capsule (an empty list removes it). */324export async function saveChapters(sessionId: string, capsuleId: string, input: unknown, actor: string): Promise<CapsuleRow> {325 const cap = getCapsule(sessionId, capsuleId);326 let rel: string | undefined;327 if (Array.isArray(input) && input.length) {328 const p = ChaptersInput.safeParse(input);329 if (!p.success) throw new ApiError(400, "invalid", `Chapitres invalides : ${p.error.issues[0]?.message}.`);330 if (p.data[0]!.start !== 0) throw new ApiError(400, "invalid", "Le premier chapitre doit commencer à 0:00.");331 if (cap.data.durationSeconds && p.data.some((c) => c.start >= cap.data.durationSeconds!)) throw new ApiError(400, "invalid", "Un chapitre commence après la fin de la vidéo.");332 rel = await writeSidecar(sessionId, capsuleId, "chapters", "json", `${JSON.stringify(p.data, null, 2)}\n`);333 }334 return tx(() => {335 const cur = getCapsule(sessionId, capsuleId), media = { ...cur.data.media };336 if (rel) media.chapters = rel; else delete media.chapters;337 writeCapsule({ ...cur, data: { ...cur.data, media } }, actor);338 audit("capsule.chapters_saved", { actor, target: `session:${sessionId}/capsule:${capsuleId}`, before: cur.data.media, after: media });339 return getCapsule(sessionId, capsuleId);340 });341}342343/** Text of a sidecar file of a capsule (captions, transcript, chapters), for the studio's editors. */344export async function readSidecar(rel: string | undefined): Promise<string | null> {345 if (!rel || !isSafeRelPath(rel)) return null;346 const s = await stat(join(paths.media, rel)).catch(() => null);347 return s?.isFile() && s.size < 6_000_000 ? readFile(join(paths.media, rel), "utf8") : null;348}349