Repository Public
1/**2 * Publications: the only path from the studio's working copy to the public site.3 *4 * A publication is an immutable snapshot (kept in `blobs`) with a date from which it is live. History is5 * linear and append-only — publishing, rolling back, withdrawing and archiving each add an entry; nothing6 * is rewritten. For one target (a session, or "course" for the public plan) the entry in force is the7 * newest one that is due and was not cancelled:8 *9 * publish / rollback the snapshot is public10 * withdraw the session falls back to « À venir » (public plan only)11 * archive the session shows a withdrawal notice and leaves the index12 *13 * A snapshot holds only what was marked public at that moment. `publicManifest()` assembles the live14 * snapshots into a `Manifest`, which `buildView(manifest, "production")` then filters as before: the15 * working copy, drafts and scheduled entries that are not due never reach that function.16 */17import { statSync } from "node:fs";18import { join } from "node:path";19import { env } from "../lib/env";20import { Manifest, type Capsule, type Session } from "../modules/content-schema/schema";21import { audit, getJson, putJson } from "./audit";22import { all, get, now, run, tx } from "./db";23import { ApiError } from "./http";24import {25 bumpContentRev, contentRev, fingerprint, getCourseRow, getSessionRow, isBootstrapped, listSessions, sessionForManifest,26 type CourseData, type SessionRow,27} from "./content";2829export type PublicationKind = "publish" | "rollback" | "withdraw" | "archive";30export interface PublicationEntry {31 id: number; target: string; version: number; kind: PublicationKind; payloadSha: string | null; liveFrom: string;32 cancelledAt: string | null; note: string | null; createdAt: string; createdBy: string;33}34interface Raw { id: number; target: string; version: number; kind: PublicationKind; payload_sha: string | null; live_from: string; cancelled_at: string | null; note: string | null; created_at: string; created_by: string }35const toEntry = (r: Raw): PublicationEntry => ({ id: r.id, target: r.target, version: r.version, kind: r.kind, payloadSha: r.payload_sha, liveFrom: r.live_from, cancelledAt: r.cancelled_at, note: r.note, createdAt: r.created_at, createdBy: r.created_by });3637export const COURSE_TARGET = "course";38/** The public plan of one session: what « À venir » shows. */39export type PlanSession = Pick<Session, "id" | "number" | "slug" | "aliases" | "part" | "level" | "title" | "short" | "outcomes" | "dependsOn" | "tags" | "source">;40export interface PlanSnapshot extends CourseData { sessions: PlanSession[] }4142export const history = (target: string) => all<Raw>("SELECT * FROM publications WHERE target = ? ORDER BY version DESC", target).map(toEntry);43/** The entry in force at `at`: newest version that is due and not cancelled. */44export function liveEntry(target: string, at = now()): PublicationEntry | null {45 const r = get<Raw>("SELECT * FROM publications WHERE target = ? AND cancelled_at IS NULL AND live_from <= ? ORDER BY version DESC LIMIT 1", target, at);46 return r ? toEntry(r) : null;47}48/** Entries that are scheduled and would take over when due (newer than the one in force). */49export function scheduledEntries(target: string, at = now()): PublicationEntry[] {50 const live = liveEntry(target, at);51 return all<Raw>("SELECT * FROM publications WHERE target = ? AND cancelled_at IS NULL AND live_from > ? AND version > ? ORDER BY live_from", target, at, live?.version ?? 0).map(toEntry);52}53const nextVersion = (target: string) => (get<{ v: number | null }>("SELECT max(version) AS v FROM publications WHERE target = ?", target)?.v ?? 0) + 1;5455function insertEntry(target: string, kind: PublicationKind, payloadSha: string | null, liveFrom: string, note: string | null, actor: string): PublicationEntry {56 const version = nextVersion(target);57 run("INSERT INTO publications (target, version, kind, payload_sha, live_from, note, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", target, version, kind, payloadSha, liveFrom, note, now(), actor);58 bumpContentRev();59 return history(target)[0]!;60}6162function parseLiveFrom(value: unknown): { at: string; scheduled: boolean } {63 if (value === undefined || value === null || value === "") return { at: now(), scheduled: false };64 const t = typeof value === "string" ? Date.parse(value) : NaN;65 if (!Number.isFinite(t)) throw new ApiError(400, "invalid", "Date de publication invalide.");66 if (t <= Date.now() + 30_000) return { at: now(), scheduled: false };67 if (t > Date.now() + 366 * 86_400_000) throw new ApiError(400, "invalid", "La date de publication ne peut pas dépasser un an.");68 return { at: new Date(t).toISOString(), scheduled: true };69}70const cleanNote = (note: unknown) => (typeof note === "string" && note.trim() ? note.trim().slice(0, 300) : null);7172/* ---- What a publication of a session would contain ---- */7374const planOf = (s: Session): PlanSession => ({ id: s.id, number: s.number, slug: s.slug, aliases: s.aliases, part: s.part, level: s.level, title: s.title, short: s.short, outcomes: s.outcomes, dependsOn: s.dependsOn, tags: s.tags, source: s.source });75const mediaExists = (key: string | undefined) => { if (!key) return false; try { return statSync(join(env.dataDir, "media", key)).isFile(); } catch { return false; } };7677export interface PublishPlan {78 snapshot: Session;79 /** What becomes public, in plain words, for the confirmation dialog. */80 public: string[];81 /** What stays in the studio (private or preview-only items). */82 withheld: string[];83 /** Reasons why publishing is refused. */84 blockers: string[];85 warnings: string[];86}87const SECTION_LABEL: Record<string, string> = { quiz: "Quiz", glossary: "Glossaire", figures: "Figures", lab: "Laboratoire", script: "Scénario de narration", bibliography: "Références", slides: "Diapositives" };8889/** Builds the snapshot a publication would freeze, and checks the rules a published session must meet. */90export function planPublication(row: SessionRow): PublishPlan {91 const working = sessionForManifest(row, "published");92 const pub: string[] = [], withheld: string[] = [], blockers: string[] = [], warnings: string[] = [];93 const sections: Session["sections"] = {};94 for (const [key, ref] of Object.entries(working.sections)) {95 const label = `${SECTION_LABEL[key] ?? key}${ref!.count ? ` (${ref!.count})` : ""}`;96 if (ref!.visibility === "public") { sections[key as keyof Session["sections"]] = ref!; pub.push(label); } else withheld.push(`${label} — ${ref!.visibility === "preview" ? "aperçu seulement" : "privé"}`);97 }98 const capsules: Capsule[] = [];99 for (const c of working.capsules) {100 if (c.visibility !== "public") { withheld.push(`Capsule « ${c.title} » — ${c.visibility === "preview" ? "aperçu seulement" : "privée"}`); continue; }101 // A published instructional video ships with French captions and a transcript; the player and the search rely on both.102 if (!c.media.captions.some((t) => t.lang.toLowerCase().startsWith("fr"))) blockers.push(`Capsule « ${c.title} » : sous-titres français manquants.`);103 if (!c.media.transcript) blockers.push(`Capsule « ${c.title} » : transcription manquante.`);104 for (const key of [c.media.hls, c.media.mp4, c.media.poster, c.media.transcript, c.media.chapters, ...c.media.captions.map((t) => t.path)]) if (key && !mediaExists(key)) blockers.push(`Capsule « ${c.title} » : fichier absent du stockage (${key.split("/").pop()}).`);105 if (!c.media.chapters) warnings.push(`Capsule « ${c.title} » : aucun chapitre.`);106 capsules.push(c); pub.push(`Capsule « ${c.title} »`);107 }108 const license = getCourseRow().data.course.license;109 const resources = working.resources.filter((r) => {110 if (r.visibility !== "public") { withheld.push(`Ressource « ${r.title} » — ${r.visibility === "preview" ? "aperçu seulement" : "privée"}`); return false; }111 try { if (statSync(join(env.dataDir, "resources", r.path)).size !== r.bytes) blockers.push(`Ressource « ${r.title} » : la taille du fichier ne correspond plus.`); } catch { blockers.push(`Ressource « ${r.title} » : fichier absent du stockage.`); }112 if (r.download && !(r.license ?? license)) warnings.push(`Ressource « ${r.title} » : aucune licence consignée, le téléchargement restera fermé.`);113 pub.push(`Ressource « ${r.title} »${r.releaseAfter ? ` (à partir du ${r.releaseAfter.slice(0, 10)})` : ""}`);114 return true;115 });116 for (const c of listCapsulesNotReady(row.id)) withheld.push(`Capsule « ${c} » — sans vidéo prête`);117 if (!pub.length) blockers.push("Rien n'est marqué « public » dans cette séance : il n'y aurait rien à montrer.");118 if (!working.outcomes.length) warnings.push("Aucun résultat d'apprentissage.");119 return { snapshot: { ...working, sections, capsules, resources }, public: pub, withheld, blockers, warnings };120}121const listCapsulesNotReady = (sessionId: string) => all<{ data: string }>("SELECT data FROM capsules WHERE session_id = ? AND status != 'ready'", sessionId).map((r) => (JSON.parse(r.data) as { title: string }).title);122123/* ---- The public manifest ---- */124125function planSnapshotNow(): PlanSnapshot {126 const course = getCourseRow().data;127 return { ...course, sessions: listSessions().map((s) => planOf(sessionForManifest(s, "planned"))) };128}129130function assemble(plan: PlanSnapshot, entryFor: (id: string) => { kind: PublicationKind; payload: Session | null } | null): unknown {131 const ids = new Set(plan.sessions.map((s) => s.id));132 const closed = (p: PlanSession, publication: Session["publication"]): Session => ({ ...p, publication, effortMinutes: null, sections: {}, capsules: [], resources: [], revisions: [] });133 const sessions = plan.sessions.map((p) => {134 const e = entryFor(p.id);135 if (e && (e.kind === "publish" || e.kind === "rollback") && e.payload) return { ...e.payload, publication: "published" as const };136 return closed(p, e?.kind === "archive" ? "archived" : "planned");137 });138 // A session published before the plan that lists it: it still exists for the public, with its own plan fields.139 for (const s of listSessions()) {140 if (ids.has(s.id)) continue;141 const e = entryFor(s.id);142 if (e && (e.kind === "publish" || e.kind === "rollback") && e.payload) sessions.push({ ...e.payload, publication: "published" });143 }144 // Prerequisites and aliases are those of the snapshots; drop references the public cannot resolve.145 const known = new Set(sessions.map((s) => s.id)), slugs = new Set(sessions.map((s) => s.slug));146 const seen = new Set<string>();147 return {148 schemaVersion: 1, course: plan.course, author: plan.author, parts: plan.parts, diagrams: plan.diagrams, exposeTags: plan.exposeTags, redirects: plan.redirects, import: plan.import,149 sessions: sessions.map((s) => ({ ...s, dependsOn: s.dependsOn.filter((d) => known.has(d) && d !== s.id), aliases: s.aliases.filter((a) => !slugs.has(a) && !seen.has(a) && Boolean(seen.add(a))) })),150 };151}152153function manifestAt(at: string, override?: { target: string; kind: PublicationKind; payload: unknown }): Manifest {154 const planEntry = override?.target === COURSE_TARGET ? null : liveEntry(COURSE_TARGET, at);155 const plan = override?.target === COURSE_TARGET ? override.payload as PlanSnapshot : getJson<PlanSnapshot>(planEntry?.payloadSha);156 if (!plan) throw new ApiError(409, "no_plan", "Aucun plan de cours n'est publié.");157 return Manifest.parse(assemble(plan, (id) => {158 if (override?.target === id) return { kind: override.kind, payload: override.payload as Session | null };159 const e = liveEntry(id, at);160 return e ? { kind: e.kind, payload: getJson<Session>(e.payloadSha) } : null;161 }));162}163164type G = typeof globalThis & { __atlasPublic?: { key: string; manifest: Manifest; from: number; until: number } };165166/**167 * What the public site is built from, or null while the studio holds no published plan (the committed168 * snapshot is used then). Cached per content revision, and only until the next scheduled change is due.169 */170export function publicManifest(at = new Date()): Manifest | null {171 if (!isBootstrapped() || !get("SELECT 1 FROM publications WHERE target = ? LIMIT 1", COURSE_TARGET)) return null;172 const g = globalThis as G, key = `${env.dataDir}:${contentRev()}`, t = at.getTime();173 if (g.__atlasPublic?.key === key && t >= g.__atlasPublic.from && t < g.__atlasPublic.until) return g.__atlasPublic.manifest;174 const manifest = manifestAt(at.toISOString());175 const next = get<{ t: string | null }>("SELECT min(live_from) AS t FROM publications WHERE cancelled_at IS NULL AND live_from > ?", at.toISOString())?.t;176 // Never trusted for more than a minute: delayed releases (`releaseAfter`) are evaluated by buildView at request time.177 g.__atlasPublic = { key, manifest, from: t, until: Math.min(t + 60_000, next ? Date.parse(next) : Infinity) };178 return manifest;179}180181/** Refuses a publication that would make the public manifest invalid (duplicate address, unknown part…). */182function assertPublishable(target: string, kind: PublicationKind, payload: unknown, at: string) {183 try { manifestAt(at, { target, kind, payload }); }184 catch (e) {185 if (e instanceof ApiError) throw e;186 const issue = (e as { issues?: { message: string; path: (string | number)[] }[] }).issues?.[0];187 throw new ApiError(409, "invalid_manifest", `Publication refusée : le site public deviendrait incohérent (${issue ? `${issue.message}${issue.path.length ? ` — ${issue.path.join(".")}` : ""}` : "manifeste invalide"}).`);188 }189}190191/* ---- Actions ---- */192193export interface SessionStatus {194 state: SessionRow["state"];195 /** published · archived · none */196 public: "published" | "archived" | "none";197 live: PublicationEntry | null;198 scheduled: PublicationEntry[];199 /** True when the working copy would publish something different from what is live. */200 dirty: boolean;201}202export function sessionStatus(row: SessionRow): SessionStatus {203 const live = liveEntry(row.id), isPublic = live && (live.kind === "publish" || live.kind === "rollback");204 const dirty = isPublic ? fingerprint(planPublication(row).snapshot) !== fingerprint(getJson<Session>(live.payloadSha)) : false;205 return { state: row.state, public: isPublic ? "published" : live?.kind === "archive" ? "archived" : "none", live, scheduled: scheduledEntries(row.id), dirty };206}207208export function publishSession(id: string, input: { liveFrom?: unknown; note?: unknown; confirm?: unknown }, actor: string): PublicationEntry {209 if (input.confirm !== id) throw new ApiError(400, "confirmation_required", "La publication doit être confirmée explicitement.");210 return tx(() => {211 const row = getSessionRow(id);212 if (row.state !== "preview") throw new ApiError(409, "not_ready", "Passez d'abord la séance à l'état « Aperçu » et relisez-la dans l'aperçu privé.");213 const plan = planPublication(row);214 if (plan.blockers.length) throw new ApiError(409, "blocked", `Publication impossible : ${plan.blockers.join(" ")}`, { blockers: plan.blockers });215 const when = parseLiveFrom(input.liveFrom), before = liveEntry(id);216 assertPublishable(id, "publish", plan.snapshot, when.at);217 const entry = insertEntry(id, "publish", putJson(plan.snapshot), when.at, cleanNote(input.note), actor);218 audit(when.scheduled ? "publication.scheduled" : "publication.published", { actor, target: `session:${id}`, beforeRef: before?.payloadSha ?? null, afterRef: entry.payloadSha, detail: { version: entry.version, liveFrom: entry.liveFrom, public: plan.public } });219 return entry;220 });221}222223/** Puts an earlier snapshot back online, as a new entry of the history. */224export function rollbackSession(id: string, input: { toVersion?: unknown; confirm?: unknown; note?: unknown }, actor: string): PublicationEntry {225 if (input.confirm !== id) throw new ApiError(400, "confirmation_required", "Le retour en arrière doit être confirmé explicitement.");226 return tx(() => {227 const target = id === COURSE_TARGET ? COURSE_TARGET : getSessionRow(id).id;228 const source = history(target).find((e) => e.version === input.toVersion);229 if (!source || !source.payloadSha || (source.kind !== "publish" && source.kind !== "rollback") || source.cancelledAt) throw new ApiError(404, "not_found", "Cette version ne peut pas être remise en ligne.");230 const before = liveEntry(target), payload = getJson<unknown>(source.payloadSha);231 assertPublishable(target, "rollback", payload, now());232 const entry = insertEntry(target, "rollback", source.payloadSha, now(), cleanNote(input.note) ?? `Retour à la version ${source.version}`, actor);233 audit("publication.rolled_back", { actor, target: target === COURSE_TARGET ? "course" : `session:${id}`, beforeRef: before?.payloadSha ?? null, afterRef: entry.payloadSha, detail: { version: entry.version, restored: source.version } });234 return entry;235 });236}237238/** Takes a session offline (back to « À venir ») or archives it (withdrawal notice). */239export function retireSession(id: string, kind: "withdraw" | "archive", input: { confirm?: unknown; note?: unknown }, actor: string): PublicationEntry {240 if (input.confirm !== id) throw new ApiError(400, "confirmation_required", "Cette action doit être confirmée explicitement.");241 return tx(() => {242 getSessionRow(id);243 const before = liveEntry(id);244 if (kind === "withdraw" && (!before || before.kind === "withdraw")) throw new ApiError(409, "not_published", "Cette séance n'est pas en ligne.");245 assertPublishable(id, kind, null, now());246 const entry = insertEntry(id, kind, null, now(), cleanNote(input.note), actor);247 audit(kind === "archive" ? "publication.archived" : "publication.withdrawn", { actor, target: `session:${id}`, beforeRef: before?.payloadSha ?? null, detail: { version: entry.version } });248 return entry;249 });250}251252export function cancelScheduled(target: string, entryId: unknown, actor: string): void {253 tx(() => {254 const e = get<Raw>("SELECT * FROM publications WHERE id = ? AND target = ?", typeof entryId === "number" ? entryId : -1, target);255 if (!e || e.cancelled_at || e.live_from <= now()) throw new ApiError(409, "not_scheduled", "Cette publication n'est pas (ou plus) en attente.");256 run("UPDATE publications SET cancelled_at = ?, cancelled_by = ? WHERE id = ?", now(), actor, e.id);257 bumpContentRev();258 audit("publication.schedule_cancelled", { actor, target: target === COURSE_TARGET ? "course" : `session:${target}`, detail: { version: e.version, liveFrom: e.live_from } });259 });260}261262/** Publishes the course plan: identity, parts, the list of sessions with their public plan, diagrams, redirects. */263export function publishPlan(input: { liveFrom?: unknown; note?: unknown; confirm?: unknown }, actor: string): PublicationEntry {264 if (input.confirm !== COURSE_TARGET) throw new ApiError(400, "confirmation_required", "La publication du plan doit être confirmée explicitement.");265 return tx(() => {266 const snapshot = planSnapshotNow(), when = parseLiveFrom(input.liveFrom), before = liveEntry(COURSE_TARGET);267 assertPublishable(COURSE_TARGET, "publish", snapshot, when.at);268 const entry = insertEntry(COURSE_TARGET, "publish", putJson(snapshot), when.at, cleanNote(input.note), actor);269 audit(when.scheduled ? "plan.scheduled" : "plan.published", { actor, target: "course", beforeRef: before?.payloadSha ?? null, afterRef: entry.payloadSha, detail: { version: entry.version, liveFrom: entry.liveFrom, sessions: snapshot.sessions.length } });270 return entry;271 });272}273274/** True when the working plan (course settings, list and plan of sessions) differs from the published one. */275export function planDirty(): boolean {276 const live = liveEntry(COURSE_TARGET);277 return !live || fingerprint(planSnapshotNow()) !== fingerprint(getJson<PlanSnapshot>(live.payloadSha));278}279280/** Differences between the working plan and the published one, session by session, for the confirmation dialog. */281export function planChanges(): string[] {282 const live = getJson<PlanSnapshot>(liveEntry(COURSE_TARGET)?.payloadSha), cur = planSnapshotNow(), out: string[] = [];283 if (!live) return ["Première publication du plan."];284 const { sessions: a, ...restA } = live, { sessions: b, ...restB } = cur;285 for (const key of Object.keys(restB) as (keyof typeof restB)[]) if (key !== "import" && fingerprint(restA[key]) !== fingerprint(restB[key])) out.push({ course: "Identité du cours ou licence", author: "Auteur", parts: "Parties", diagrams: "Visibilité des schémas", exposeTags: "Affichage des thèmes", redirects: "Redirections" }[key as string] ?? String(key));286 const byId = new Map(a.map((s) => [s.id, s]));287 for (const s of b) {288 const old = byId.get(s.id);289 if (!old) out.push(`${s.id} — nouvelle séance : ${s.title}`);290 else { const { source: _a, ...x } = old, { source: _b, ...y } = s; void _a; void _b; if (fingerprint(x) !== fingerprint(y)) out.push(`${s.id} — plan modifié : ${s.title}`); }291 byId.delete(s.id);292 }293 for (const s of byId.values()) out.push(`${s.id} — retirée du plan : ${s.title}`);294 return out;295}296