SPB Git

Repository Public

content.ts 33.7 KB 471 lines typescript

1/**2 * The editorial model: the working copy of the course kept in the studio database, layered over what was3 * imported from the course repository.4 *5 *   course            one row: course identity, author, parts, licence, diagram visibility, redirects6 *   course_sessions   one row per session: plan fields (title, outcomes, prerequisites…), workflow state7 *   sections          quiz, glossary, figures, lab, script, bibliography — bodies live in `blobs`, by hash8 *   capsules          video capsules and their media references9 *   resources         downloadable files, with a version history10 *11 * Every row also remembers `base`: the value last imported from the repository, which is what makes a12 * three-way comparison possible at the next import (see sync.ts). Nothing in this file is public: what13 * visitors see is decided by publish.ts, through immutable publications.14 */15import { z } from "zod";16import {17  Bibliography, Capsule, Chapters, Glossary, LEVELS, Manifest, Quiz, RESOURCE_KINDS, SECTION_KEYS, Visibility,18  type Part, type Resource, type SectionKey, type Session,19} from "../modules/content-schema/schema";20import { audit, getBlobText, putBlob } from "./audit";21import { canonicalJson } from "./crypto";22import { all, get, getMeta, now, run, setMeta, tx } from "./db";23import { ApiError } from "./http";2425export const SESSION_STATES = ["planned", "draft", "preview"] as const;26export type SessionState = (typeof SESSION_STATES)[number];2728/** Fields that come from the course repository and that an import may update. */29export const IMPORT_FIELDS = ["title", "short", "part", "level", "outcomes", "dependsOn", "tags", "effortMinutes"] as const;30export type ImportField = (typeof IMPORT_FIELDS)[number];31export type SessionBase = Pick<Session, ImportField>;32export type SessionData = SessionBase & Pick<Session, "number" | "slug" | "aliases" | "source" | "revisions">;3334export interface CourseData {35  course: Manifest["course"]; author: Manifest["author"]; parts: Part[];36  diagrams: Manifest["diagrams"]; exposeTags: boolean; redirects: Manifest["redirects"]; import: Manifest["import"];37}38export type CourseBase = Pick<CourseData, "author" | "parts"> & { course: Omit<Manifest["course"], "license"> };3940export interface SessionRow { id: string; state: SessionState; data: SessionData; base: SessionBase | null; inSource: boolean; rev: number; updatedAt: string; updatedBy: string }41export interface SectionRow { sessionId: string; key: SectionKey; sha256: string; visibility: Visibility; count: number | null; baseSha: string | null; updatedAt: string; updatedBy: string }42export type CapsuleStatus = "empty" | "queued" | "processing" | "ready" | "failed";43/** Working data of a capsule. `media` paths are relative to ATLAS_DATA_DIR/media and never reused once written. */44export interface CapsuleData {45  title: string; optional: boolean; visibility: Visibility; download: boolean; durationSeconds: number | null;46  media: Capsule["media"]; thumbs: string[];47  source: { width: number; height: number; fps: number; videoCodec: string; audioCodec: string | null; bytes: number; filename: string } | null;48  renditions: { height: number; width: number; bandwidth: number }[];49}50export interface CapsuleRow { sessionId: string; id: string; position: number; status: CapsuleStatus; masterSha: string | null; data: CapsuleData; updatedAt: string }51export interface ResourceData { kind: Resource["kind"]; title: string; description?: string; visibility: Visibility; download: boolean; license: string | null; releaseAfter?: string }52export interface ResourceVersion { version: number; path: string; bytes: number; sha256: string; mime: string; filename: string; note: string | null; createdAt: string; createdBy: string }53export interface ResourceRow { sessionId: string; id: string; data: ResourceData; currentVersion: number; versions: ResourceVersion[] }5455const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/, SESSION_ID = /^S\d{2,3}$/;56const parse = <T>(text: string | null | undefined) => (text ? JSON.parse(text) as T : null);57const bad = (message: string, code = "invalid") => new ApiError(400, code, message);58const missing = (what: string) => new ApiError(404, "not_found", `${what} introuvable.`);59/** Optimistic concurrency: an edit names the revision it was made from; a stale or replayed one is refused. */60function assertRev(current: number, given: unknown) {61  if (typeof given !== "number" || given !== current) throw new ApiError(409, "stale", "Cet élément a été modifié entre-temps. Rechargez la page avant de réessayer.", { rev: current });62}6364/** Any change to what is — or could become — public bumps this counter; readers cache against it. */65export const contentRev = () => Number(getMeta("content_rev") ?? 0);66export const bumpContentRev = () => setMeta("content_rev", String(contentRev() + 1));67export const isBootstrapped = () => getMeta("bootstrapped") !== null;6869/* ---- Course ---- */7071export function getCourseRow(): { data: CourseData; base: CourseBase; rev: number } {72  const r = get<{ data: string; base: string; rev: number }>("SELECT data, base, rev FROM course WHERE id = 1");73  if (!r) throw new ApiError(409, "not_bootstrapped", "Le studio n'a pas encore de cours. Importez le dépôt du cours.");74  return { data: JSON.parse(r.data) as CourseData, base: JSON.parse(r.base) as CourseBase, rev: r.rev };75}76export function writeCourse(data: CourseData, base: CourseBase, actor: string) {77  run(`INSERT INTO course (id, data, base, rev, updated_at, updated_by) VALUES (1, ?, ?, 1, ?, ?)78       ON CONFLICT (id) DO UPDATE SET data = excluded.data, base = excluded.base, rev = rev + 1, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,79    JSON.stringify(data), JSON.stringify(base), now(), actor);80}8182const CoursePatch = z.object({83  license: z.string().trim().max(120).nullable(),84  exposeTags: z.boolean(),85  parts: z.array(z.object({ id: z.string().trim().min(1).max(8).regex(/^[A-Za-z0-9]+$/), short: z.string().trim().min(1).max(60), title: z.string().trim().min(1).max(160) })).min(1).max(20),86  diagrams: z.record(z.string().regex(/^[a-z0-9-]+$/), Visibility),87  redirects: z.array(z.object({ from: z.string().regex(/^\/[A-Za-z0-9/_-]*$/).max(200), to: z.string().regex(/^\/[A-Za-z0-9/_#?=&-]*$/).max(200) })).max(200),88}).partial().strict();8990export function updateCourse(patch: unknown, rev: unknown, actor: string): CourseData {91  const p = CoursePatch.safeParse(patch);92  if (!p.success) throw bad(`Champ invalide : ${p.error.issues[0]?.path.join(".")} — ${p.error.issues[0]?.message}`);93  return tx(() => {94    const cur = getCourseRow();95    assertRev(cur.rev, rev);96    const next: CourseData = { ...cur.data, ...(p.data.exposeTags !== undefined ? { exposeTags: p.data.exposeTags } : {}), ...(p.data.diagrams ? { diagrams: p.data.diagrams } : {}), ...(p.data.redirects ? { redirects: p.data.redirects } : {}) };97    if (p.data.license !== undefined) next.course = { ...cur.data.course, license: p.data.license || null };98    if (p.data.parts) {99      const ids = new Set(p.data.parts.map((x) => x.id));100      if (ids.size !== p.data.parts.length) throw bad("Deux parties portent le même identifiant.");101      const orphan = listSessions().find((s) => !ids.has(s.data.part));102      if (orphan) throw bad(`La partie ${orphan.data.part} est utilisée par la séance ${orphan.id} : déplacez la séance avant de retirer la partie.`);103      next.parts = p.data.parts;104    }105    for (const r of next.redirects) if (r.from === r.to || /^\/(admin|api|media|_next)/.test(r.from)) throw bad(`Redirection refusée : ${r.from}`);106    writeCourse(next, cur.base, actor);107    audit("course.updated", { actor, target: "course", before: cur.data, after: next });108    return next;109  });110}111112/* ---- Sessions ---- */113114interface RawSession { id: string; state: SessionState; data: string; base: string | null; in_source: number; rev: number; updated_at: string; updated_by: string }115const toSession = (r: RawSession): SessionRow => ({ id: r.id, state: r.state, data: JSON.parse(r.data) as SessionData, base: parse<SessionBase>(r.base), inSource: r.in_source === 1, rev: r.rev, updatedAt: r.updated_at, updatedBy: r.updated_by });116export const listSessions = (): SessionRow[] => all<RawSession>("SELECT * FROM course_sessions").map(toSession).sort((a, b) => a.data.number - b.data.number || a.id.localeCompare(b.id));117export function getSessionRow(id: string): SessionRow {118  const r = get<RawSession>("SELECT * FROM course_sessions WHERE id = ?", id);119  if (!r) throw missing(`Séance ${id}`);120  return toSession(r);121}122export function writeSession(id: string, o: { state: SessionState; data: SessionData; base: SessionBase | null; inSource?: boolean }, actor: string) {123  run(`INSERT INTO course_sessions (id, state, data, base, in_source, rev, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, 1, ?, ?)124       ON CONFLICT (id) DO UPDATE SET state = excluded.state, data = excluded.data, base = excluded.base, in_source = excluded.in_source, rev = rev + 1, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,125    id, o.state, JSON.stringify(o.data), o.base ? JSON.stringify(o.base) : null, o.inSource === false ? 0 : 1, now(), actor);126}127128const Text = (max: number) => z.string().trim().min(1).max(max);129const SessionPatch = z.object({130  title: Text(200), short: Text(80), part: Text(8), level: z.enum(LEVELS),131  outcomes: z.array(Text(400)).max(20), dependsOn: z.array(z.string().regex(SESSION_ID)).max(30), tags: z.array(Text(60)).max(30),132  effortMinutes: z.record(z.string().regex(/^[a-z_]+$/), z.tuple([z.number().int().min(0).max(1000), z.number().int().min(0).max(1000)])).nullable(),133  slug: z.string().regex(SLUG).max(120),134  revisions: z.array(z.object({ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), note: Text(300) })).max(100),135}).partial().strict();136137/** Every slug and alias in use, to keep addresses unique across the course. */138function takenSlugs(exceptId: string): Set<string> {139  return new Set(listSessions().filter((s) => s.id !== exceptId).flatMap((s) => [s.data.slug, ...s.data.aliases]));140}141function assertPlanValid(id: string, d: SessionData) {142  const course = getCourseRow().data, ids = new Set(listSessions().map((s) => s.id).concat(id));143  if (!course.parts.some((p) => p.id === d.part)) throw bad(`Partie inconnue : ${d.part}.`);144  for (const dep of d.dependsOn) {145    if (dep === id) throw bad("Une séance ne peut pas être son propre préalable.");146    if (!ids.has(dep)) throw bad(`Préalable inconnu : ${dep}.`);147  }148  if (new Set(d.dependsOn).size !== d.dependsOn.length) throw bad("Un préalable est cité deux fois.");149}150151export function updateSession(id: string, patch: unknown, rev: unknown, actor: string): SessionRow {152  const p = SessionPatch.safeParse(patch);153  if (!p.success) throw bad(`Champ invalide : ${p.error.issues[0]?.path.join(".")} — ${p.error.issues[0]?.message}`);154  return tx(() => {155    const cur = getSessionRow(id);156    assertRev(cur.rev, rev);157    const next: SessionData = { ...cur.data, ...p.data };158    if (p.data.slug && p.data.slug !== cur.data.slug) {159      if (takenSlugs(id).has(p.data.slug)) throw new ApiError(409, "slug_taken", `L'adresse « ${p.data.slug} » est déjà utilisée par une autre séance.`);160      // The former address keeps working for ever: it becomes an alias, served as a permanent redirect.161      next.aliases = [...new Set([...cur.data.aliases.filter((a) => a !== p.data.slug), cur.data.slug])];162    }163    assertPlanValid(id, next);164    writeSession(id, { state: cur.state, data: next, base: cur.base, inSource: cur.inSource }, actor);165    audit("session.updated", { actor, target: `session:${id}`, before: cur.data, after: next, detail: { fields: Object.keys(p.data) } });166    return getSessionRow(id);167  });168}169170export function createSession(input: unknown, actor: string): SessionRow {171  const p = z.object({ title: Text(200), short: Text(80), part: Text(8), level: z.enum(LEVELS) }).strict().safeParse(input);172  if (!p.success) throw bad("Titre, titre court, partie et niveau sont requis.");173  return tx(() => {174    const sessions = listSessions();175    const n = Math.max(0, ...sessions.map((s) => Number(s.id.slice(1)))) + 1, number = Math.max(0, ...sessions.map((s) => s.data.number)) + 1;176    const id = `S${String(n).padStart(2, "0")}`, taken = takenSlugs(id);177    const stem = `${String(number).padStart(2, "0")}-${slugOf(p.data.short)}`.replace(/-+$/, "");178    let slug = stem;179    for (let i = 2; taken.has(slug); i++) slug = `${stem}-${i}`;180    const data: SessionData = { ...p.data, number, slug, aliases: [], outcomes: [], dependsOn: [], tags: [], effortMinutes: null, source: { status: "unknown", lastReviewed: null, videoRecorded: false, hash: "0".repeat(64) }, revisions: [] };181    assertPlanValid(id, data);182    writeSession(id, { state: "draft", data, base: null, inSource: false }, actor);183    audit("session.created", { actor, target: `session:${id}`, after: data });184    return getSessionRow(id);185  });186}187const slugOf = (text: string) => text.replace(/œ/g, "oe").normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "seance";188189/** draft ⇄ preview. « preview » means: ready to be read in the private preview, and eligible for publication. */190export function setSessionState(id: string, state: unknown, actor: string): SessionRow {191  if (state !== "draft" && state !== "preview") throw bad("État inconnu.");192  return tx(() => {193    const cur = getSessionRow(id);194    if (cur.state !== state) {195      run("UPDATE course_sessions SET state = ?, rev = rev + 1, updated_at = ?, updated_by = ? WHERE id = ?", state, now(), actor, id);196      audit("session.state", { actor, target: `session:${id}`, before: { state: cur.state }, after: { state } });197    }198    return getSessionRow(id);199  });200}201202/** Moves a session one place up or down in the course order by exchanging its number with its neighbour's. */203export function moveSession(id: string, direction: unknown, actor: string): void {204  if (direction !== "up" && direction !== "down") throw bad("Direction inconnue.");205  tx(() => {206    const sessions = listSessions(), i = sessions.findIndex((s) => s.id === id), other = sessions[i + (direction === "up" ? -1 : 1)];207    if (i < 0) throw missing(`Séance ${id}`);208    if (!other) return;209    const a = sessions[i]!, na = a.data.number, nb = other.data.number;210    writeSession(a.id, { state: a.state, data: { ...a.data, number: nb }, base: a.base, inSource: a.inSource }, actor);211    writeSession(other.id, { state: other.state, data: { ...other.data, number: na }, base: other.base, inSource: other.inSource }, actor);212    audit("session.moved", { actor, target: `session:${id}`, before: { number: na }, after: { number: nb }, detail: { exchangedWith: other.id } });213  });214}215216/* ---- Sections ---- */217218interface RawSection { session_id: string; key: SectionKey; sha256: string; visibility: Visibility; count: number | null; base_sha256: string | null; updated_at: string; updated_by: string }219const toSection = (r: RawSection): SectionRow => ({ sessionId: r.session_id, key: r.key, sha256: r.sha256, visibility: r.visibility, count: r.count, baseSha: r.base_sha256, updatedAt: r.updated_at, updatedBy: r.updated_by });220export const listSections = (sessionId: string) => all<RawSection>("SELECT * FROM sections WHERE session_id = ? ORDER BY key", sessionId).map(toSection);221export const getSection = (sessionId: string, key: SectionKey) => { const r = get<RawSection>("SELECT * FROM sections WHERE session_id = ? AND key = ?", sessionId, key); return r ? toSection(r) : null; };222export function writeSection(sessionId: string, key: SectionKey, o: { sha256: string; visibility: Visibility; count: number | null; baseSha: string | null }, actor: string) {223  run(`INSERT INTO sections (session_id, key, sha256, visibility, count, base_sha256, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)224       ON CONFLICT (session_id, key) DO UPDATE SET sha256 = excluded.sha256, visibility = excluded.visibility, count = excluded.count, base_sha256 = excluded.base_sha256, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,225    sessionId, key, o.sha256, o.visibility, o.count, o.baseSha, now(), actor);226}227228const MAX_SECTION = 1_500_000;229/** Validates the body of a section against its schema and returns the canonical text to store, with its item count. */230export function normaliseSection(key: SectionKey, body: unknown, sessionId: string): { text: string; count: number | null } {231  if (key === "lab" || key === "script") {232    if (typeof body !== "string" || !body.trim()) throw bad("Le texte est vide.");233    if (body.length > MAX_SECTION || body.includes("\0")) throw bad("Texte trop volumineux ou invalide.");234    return { text: body.replace(/\r\n?/g, "\n"), count: null };235  }236  if (key === "figures") throw bad("Les figures proviennent du dépôt du cours : seules leur visibilité et leur importation se règlent ici.");237  if (key === "slides") throw bad("Les diapositives s'importent comme un paquet produit à partir des PDF du cours : seule leur visibilité se règle ici.");238  const value = typeof body === "string" ? (() => { try { return JSON.parse(body) as unknown; } catch { throw bad("JSON invalide."); } })() : body;239  const fail = (e: z.ZodError) => bad(`Contenu invalide : ${e.issues.slice(0, 3).map((i) => `${i.path.join(".") || "racine"} — ${i.message}`).join(" ; ")}`);240  if (key === "quiz") {241    const r = Quiz.safeParse(value);242    if (!r.success) throw fail(r.error);243    const ids = new Set<string>();244    for (const q of r.data.questions) {245      if (ids.has(q.id)) throw bad(`Deux questions portent l'identifiant ${q.id}.`);246      ids.add(q.id);247      if (q.type === "single" && !q.options.some((o) => o.id === q.answer)) throw bad(`Question ${q.id} : la bonne réponse ne figure pas parmi les choix.`);248      if (q.type === "multiple" && !q.answers.every((a) => q.options.some((o) => o.id === a))) throw bad(`Question ${q.id} : une bonne réponse ne figure pas parmi les choix.`);249    }250    return { text: `${JSON.stringify(r.data, null, 2)}\n`, count: r.data.questions.length };251  }252  if (key === "glossary") {253    const r = Glossary.safeParse(value);254    if (!r.success) throw fail(r.error);255    if (new Set(r.data.terms.map((t) => t.id)).size !== r.data.terms.length) throw bad("Deux termes portent le même identifiant.");256    const terms = r.data.terms.map((t) => ({ ...t, session: sessionId }));257    return { text: `${JSON.stringify({ terms }, null, 2)}\n`, count: terms.length };258  }259  const r = Bibliography.safeParse(value);260  if (!r.success) throw fail(r.error);261  for (const e of r.data.entries) if (e.url && !/^https?:\/\//.test(e.url)) throw bad(`Référence ${e.key} : seules les adresses http(s) sont acceptées.`);262  return { text: `${JSON.stringify(r.data, null, 2)}\n`, count: r.data.entries.length };263}264265export function putSection(sessionId: string, key: unknown, input: { body?: unknown; visibility?: unknown; expectSha?: unknown }, actor: string): SectionRow {266  if (!SECTION_KEYS.includes(key as SectionKey)) throw bad("Section inconnue.");267  const k = key as SectionKey;268  const vis = input.visibility === undefined ? undefined : Visibility.safeParse(input.visibility);269  if (vis && !vis.success) throw bad("Visibilité inconnue.");270  return tx(() => {271    const session = getSessionRow(sessionId), cur = getSection(sessionId, k);272    if (input.expectSha !== undefined && (cur?.sha256 ?? null) !== input.expectSha) throw new ApiError(409, "stale", "Cette section a été modifiée entre-temps. Rechargez la page avant de réessayer.");273    let sha = cur?.sha256, count = cur?.count ?? null;274    if (input.body !== undefined) { const n = normaliseSection(k, input.body, sessionId); sha = putBlob(n.text); count = n.count; }275    if (!sha) throw bad("Cette section n'existe pas encore : fournissez son contenu.");276    const visibility = vis?.data ?? cur?.visibility ?? "private";277    writeSection(sessionId, k, { sha256: sha, visibility, count, baseSha: cur?.baseSha ?? null }, actor);278    if (session.state === "planned") run("UPDATE course_sessions SET state = 'draft', rev = rev + 1 WHERE id = ?", sessionId);279    audit(cur ? "section.updated" : "section.created", { actor, target: `session:${sessionId}/${k}`, beforeRef: cur?.sha256 ?? null, afterRef: sha, detail: { visibility: { before: cur?.visibility ?? null, after: visibility }, count } });280    return getSection(sessionId, k)!;281  });282}283284export function deleteSection(sessionId: string, key: unknown, actor: string): void {285  if (!SECTION_KEYS.includes(key as SectionKey)) throw bad("Section inconnue.");286  tx(() => {287    const cur = getSection(sessionId, key as SectionKey);288    if (!cur) throw missing("Section");289    run("DELETE FROM sections WHERE session_id = ? AND key = ?", sessionId, key as string);290    audit("section.deleted", { actor, target: `session:${sessionId}/${key as string}`, beforeRef: cur.sha256 });291  });292}293export const sectionBody = (s: Pick<SectionRow, "sha256">) => getBlobText(s.sha256) ?? "";294295/* ---- Capsules ---- */296297interface RawCapsule { session_id: string; id: string; position: number; data: string; status: CapsuleStatus; master_sha: string | null; updated_at: string }298const toCapsule = (r: RawCapsule): CapsuleRow => ({ sessionId: r.session_id, id: r.id, position: r.position, status: r.status, masterSha: r.master_sha, data: JSON.parse(r.data) as CapsuleData, updatedAt: r.updated_at });299export const listCapsules = (sessionId: string) => all<RawCapsule>("SELECT * FROM capsules WHERE session_id = ? ORDER BY position, id", sessionId).map(toCapsule);300export function getCapsule(sessionId: string, id: string): CapsuleRow {301  const r = get<RawCapsule>("SELECT * FROM capsules WHERE session_id = ? AND id = ?", sessionId, id);302  if (!r) throw missing("Capsule");303  return toCapsule(r);304}305export function writeCapsule(c: Pick<CapsuleRow, "sessionId" | "id" | "position" | "status" | "masterSha" | "data">, actor: string) {306  run(`INSERT INTO capsules (session_id, id, position, data, status, master_sha, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)307       ON CONFLICT (session_id, id) DO UPDATE SET position = excluded.position, data = excluded.data, status = excluded.status, master_sha = excluded.master_sha, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,308    c.sessionId, c.id, c.position, JSON.stringify(c.data), c.status, c.masterSha, now(), actor);309}310311export function createCapsule(sessionId: string, input: unknown, actor: string): CapsuleRow {312  const p = z.object({ title: Text(160), id: z.string().regex(SLUG).max(60).optional(), optional: z.boolean().optional() }).strict().safeParse(input);313  if (!p.success) throw bad("Le titre de la capsule est requis (identifiant : minuscules, chiffres et traits d'union).");314  return tx(() => {315    getSessionRow(sessionId);316    const existing = listCapsules(sessionId), stem = p.data.id ?? slugOf(p.data.title).slice(0, 50);317    let id = stem;318    if (p.data.id && existing.some((c) => c.id === id)) throw new ApiError(409, "exists", "Une capsule porte déjà cet identifiant dans la séance.");319    for (let i = 2; existing.some((c) => c.id === id); i++) id = `${stem}-${i}`;320    const data: CapsuleData = { title: p.data.title, optional: p.data.optional ?? false, visibility: "private", download: false, durationSeconds: null, media: { captions: [] }, thumbs: [], source: null, renditions: [] };321    writeCapsule({ sessionId, id, position: Math.max(-1, ...existing.map((c) => c.position)) + 1, status: "empty", masterSha: null, data }, actor);322    audit("capsule.created", { actor, target: `session:${sessionId}/capsule:${id}`, after: data });323    return getCapsule(sessionId, id);324  });325}326327export function updateCapsule(sessionId: string, id: string, patch: unknown, actor: string): CapsuleRow {328  const p = z.object({ title: Text(160), optional: z.boolean(), visibility: Visibility, download: z.boolean() }).partial().strict().safeParse(patch);329  if (!p.success) throw bad("Champ de capsule invalide.");330  return tx(() => {331    const cur = getCapsule(sessionId, id), data = { ...cur.data, ...p.data };332    writeCapsule({ ...cur, data }, actor);333    audit("capsule.updated", { actor, target: `session:${sessionId}/capsule:${id}`, before: cur.data, after: data });334    return getCapsule(sessionId, id);335  });336}337338export function reorderCapsules(sessionId: string, order: unknown, actor: string): void {339  tx(() => {340    const cur = listCapsules(sessionId);341    if (!Array.isArray(order) || order.length !== cur.length || !cur.every((c) => order.includes(c.id))) throw bad("L'ordre doit citer chaque capsule de la séance exactement une fois.");342    (order as string[]).forEach((id, i) => run("UPDATE capsules SET position = ? WHERE session_id = ? AND id = ?", i, sessionId, id));343    audit("capsule.reordered", { actor, target: `session:${sessionId}`, before: cur.map((c) => c.id), after: order });344  });345}346347/** Removes the capsule from the working copy. Its files stay on disk: a publication made earlier may still name them. */348export function deleteCapsule(sessionId: string, id: string, actor: string): void {349  tx(() => {350    const cur = getCapsule(sessionId, id);351    if (cur.status === "queued" || cur.status === "processing") throw new ApiError(409, "busy", "Un traitement est en cours pour cette capsule. Annulez-le d'abord.");352    run("DELETE FROM capsules WHERE session_id = ? AND id = ?", sessionId, id);353    audit("capsule.deleted", { actor, target: `session:${sessionId}/capsule:${id}`, before: cur.data });354  });355}356357/** Writes chapter metadata next to the capsule's media, under a name derived from its content. */358export const ChaptersInput = Chapters.max(200).refine((c) => c.every((x, i) => i === 0 || x.start > c[i - 1]!.start), "les chapitres doivent être en ordre croissant");359360/* ---- Resources ---- */361362interface RawResource { session_id: string; id: string; data: string; current_version: number }363const versionsOf = (sessionId: string, id: string) => all<{ version: number; path: string; bytes: number; sha256: string; mime: string; filename: string; note: string | null; created_at: string; created_by: string }>(364  "SELECT * FROM resource_versions WHERE session_id = ? AND resource_id = ? ORDER BY version DESC", sessionId, id)365  .map((v): ResourceVersion => ({ version: v.version, path: v.path, bytes: v.bytes, sha256: v.sha256, mime: v.mime, filename: v.filename, note: v.note, createdAt: v.created_at, createdBy: v.created_by }));366const toResource = (r: RawResource): ResourceRow => ({ sessionId: r.session_id, id: r.id, data: JSON.parse(r.data) as ResourceData, currentVersion: r.current_version, versions: versionsOf(r.session_id, r.id) });367export const listResources = (sessionId: string) => all<RawResource>("SELECT * FROM resources WHERE session_id = ? ORDER BY id", sessionId).map(toResource);368export function getResource(sessionId: string, id: string): ResourceRow {369  const r = get<RawResource>("SELECT * FROM resources WHERE session_id = ? AND id = ?", sessionId, id);370  if (!r) throw missing("Ressource");371  return toResource(r);372}373374const ResourceMeta = z.object({375  kind: z.enum(RESOURCE_KINDS), title: Text(160), description: z.string().trim().max(600).optional(),376  visibility: Visibility, download: z.boolean(), license: z.string().trim().max(120).nullable(), releaseAfter: z.iso.datetime().optional().nullable(),377}).strict();378379/** Adds a file as a new resource, or as a new version of an existing one (same public address, new bytes). */380export function addResourceVersion(sessionId: string, input: { id?: string; meta?: unknown; file: { path: string; bytes: number; sha256: string; mime: string; filename: string }; note?: string }, actor: string): ResourceRow {381  return tx(() => {382    getSessionRow(sessionId);383    const existing = input.id ? get<RawResource>("SELECT * FROM resources WHERE session_id = ? AND id = ?", sessionId, input.id) : undefined;384    if (existing) {385      const version = existing.current_version + 1, top = Math.max(version, ...versionsOf(sessionId, existing.id).map((v) => v.version + 1));386      run("INSERT INTO resource_versions (session_id, resource_id, version, path, bytes, sha256, mime, filename, note, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",387        sessionId, existing.id, top, input.file.path, input.file.bytes, input.file.sha256, input.file.mime, input.file.filename, input.note?.slice(0, 300) ?? null, now(), actor);388      run("UPDATE resources SET current_version = ?, updated_at = ?, updated_by = ? WHERE session_id = ? AND id = ?", top, now(), actor, sessionId, existing.id);389      audit("resource.replaced", { actor, target: `session:${sessionId}/resource:${existing.id}`, detail: { version: top, sha256: input.file.sha256, bytes: input.file.bytes, filename: input.file.filename } });390      return getResource(sessionId, existing.id);391    }392    const meta = ResourceMeta.safeParse(input.meta);393    if (!meta.success) throw bad("Type et titre de la ressource requis.");394    const taken = new Set(listResources(sessionId).map((r) => r.id)), stem = input.id && /^[A-Za-z0-9._-]+$/.test(input.id) ? input.id : slugOf(meta.data.title).slice(0, 50);395    let id = stem;396    for (let i = 2; taken.has(id); i++) id = `${stem}-${i}`;397    const data: ResourceData = { ...meta.data, releaseAfter: meta.data.releaseAfter ?? undefined };398    run("INSERT INTO resources (session_id, id, data, current_version, updated_at, updated_by) VALUES (?, ?, ?, 1, ?, ?)", sessionId, id, JSON.stringify(data), now(), actor);399    run("INSERT INTO resource_versions (session_id, resource_id, version, path, bytes, sha256, mime, filename, note, created_at, created_by) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)",400      sessionId, id, input.file.path, input.file.bytes, input.file.sha256, input.file.mime, input.file.filename, input.note?.slice(0, 300) ?? null, now(), actor);401    audit("resource.created", { actor, target: `session:${sessionId}/resource:${id}`, after: { ...data, sha256: input.file.sha256, bytes: input.file.bytes, filename: input.file.filename } });402    return getResource(sessionId, id);403  });404}405406export function updateResource(sessionId: string, id: string, patch: unknown, actor: string): ResourceRow {407  const p = ResourceMeta.partial().safeParse(patch);408  if (!p.success) throw bad("Champ de ressource invalide.");409  return tx(() => {410    const cur = getResource(sessionId, id), data: ResourceData = { ...cur.data, ...p.data, releaseAfter: p.data.releaseAfter === null ? undefined : p.data.releaseAfter ?? cur.data.releaseAfter };411    run("UPDATE resources SET data = ?, updated_at = ?, updated_by = ? WHERE session_id = ? AND id = ?", JSON.stringify(data), now(), actor, sessionId, id);412    audit("resource.updated", { actor, target: `session:${sessionId}/resource:${id}`, before: cur.data, after: data });413    return getResource(sessionId, id);414  });415}416417/** Makes an earlier version current again. Nothing is deleted; the public address does not change. */418export function restoreResourceVersion(sessionId: string, id: string, version: unknown, actor: string): ResourceRow {419  return tx(() => {420    const cur = getResource(sessionId, id);421    if (!cur.versions.some((v) => v.version === version)) throw missing("Version");422    run("UPDATE resources SET current_version = ?, updated_at = ?, updated_by = ? WHERE session_id = ? AND id = ?", version as number, now(), actor, sessionId, id);423    audit("resource.version_restored", { actor, target: `session:${sessionId}/resource:${id}`, before: { version: cur.currentVersion }, after: { version } });424    return getResource(sessionId, id);425  });426}427428export function deleteResource(sessionId: string, id: string, actor: string): void {429  tx(() => {430    const cur = getResource(sessionId, id);431    run("DELETE FROM resources WHERE session_id = ? AND id = ?", sessionId, id);432    audit("resource.deleted", { actor, target: `session:${sessionId}/resource:${id}`, before: { ...cur.data, versions: cur.versions.length } });433  });434}435436/* ---- Working copy in manifest form ---- */437438/** A capsule as the manifest describes it; null while it has no playable media. */439export function capsuleForManifest(c: CapsuleRow): Capsule | null {440  if (c.status !== "ready" || !c.data.durationSeconds || !c.data.media.hls) return null;441  return { id: c.id, title: c.data.title, order: c.position, optional: c.data.optional, durationSeconds: c.data.durationSeconds, synthetic: false, visibility: c.data.visibility, download: c.data.download, media: c.data.media };442}443export function resourceForManifest(r: ResourceRow): Resource | null {444  const v = r.versions.find((x) => x.version === r.currentVersion);445  if (!v) return null;446  return { id: r.id, kind: r.data.kind, title: r.data.title, ...(r.data.description ? { description: r.data.description } : {}), visibility: r.data.visibility, download: r.data.download, license: r.data.license, path: v.path, bytes: v.bytes, sha256: v.sha256, mime: v.mime, ...(r.data.releaseAfter ? { releaseAfter: r.data.releaseAfter } : {}) };447}448449/** The working copy of one session, in the manifest's `Session` shape, with the given publication state. */450export function sessionForManifest(row: SessionRow, publication: Session["publication"]): Session {451  const sections: Session["sections"] = {};452  for (const s of listSections(row.id)) sections[s.key] = { path: `sessions/${row.id}/${s.key}`, sha256: s.sha256, visibility: s.visibility, ...(s.count !== null ? { count: s.count } : {}) };453  return {454    id: row.id, ...row.data, aliases: row.data.aliases.filter((a) => a !== row.data.slug), publication, sections,455    capsules: listCapsules(row.id).map(capsuleForManifest).filter((c): c is Capsule => c !== null),456    resources: listResources(row.id).map(resourceForManifest).filter((r): r is Resource => r !== null),457  };458}459460/**461 * The whole working copy as a manifest, for the private preview of signed-in editors. A session in the462 * `preview` state is shown as it would be once published; drafts stay closed, exactly as `buildView` rules.463 */464export function workingManifest(): Manifest {465  const course = getCourseRow().data;466  return Manifest.parse({ schemaVersion: 1, ...course, sessions: listSessions().map((s) => sessionForManifest(s, s.state)) });467}468469/** A stable fingerprint of a value, used to tell whether the working copy differs from what is live. */470export const fingerprint = (value: unknown) => canonicalJson(value);471
Files main
Menu

Theme