Repository Public
1/**2 * Slide decks: from the course repository's web PDFs to what the online viewer shows.3 *4 * build (needs poppler: pdfinfo, pdftotext, pdftocairo — at import time only, on a machine that has it)5 * SXX-web.pdf + SXX-web-light.pdf → one SVG per slide and per theme, WebP thumbnails, deck.json6 * pack the result as a directory or a .tar.gz, to be carried to a machine without poppler7 * import validates a pack (schema, every checksum, every SVG inspected) and registers it as the session's8 * « slides » section — private, like everything that enters the studio.9 *10 * The repository is data: the .tex files are only searched for frame titles, labels and structure macros;11 * nothing is compiled or executed, external programs get fixed arguments and no shell. Speaker notes12 * (`speaker-notes.md`, `\note{…}`, the `-notes.pdf` export) are never opened or kept: the deck format has13 * no field that could hold them, and slide text comes from the public web export only.14 */15import { execFile } from "node:child_process";16import { createHash } from "node:crypto";17import { existsSync } from "node:fs";18import { cp, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";19import { tmpdir } from "node:os";20import { dirname, join, resolve, sep } from "node:path";21import { promisify } from "node:util";22import { gzipSync } from "node:zlib";23import { parse as parseYaml } from "yaml";24import { env } from "../lib/env";25import { checkSvg } from "../modules/content-schema/adapter";26import { Deck, isSafeRelPath, type Session, type SlideTheme } from "../modules/content-schema/schema";27import { TAR_END, extractArchive, tarEntry } from "./archive";28import { audit, getJson, putBlob } from "./audit";29import { getSection, getSessionRow, putSection, setSessionState, writeSection } from "./content";30import { tx } from "./db";31import { ApiError } from "./http";32import { liveEntry, planPublication, publishSession, retireSession, type PublicationEntry } from "./publish";3334const run = promisify(execFile);35const sha256 = (b: Buffer | string) => createHash("sha256").update(b).digest("hex");36const pad3 = (n: number) => String(n).padStart(3, "0");37export const slidesRoot = () => join(env.dataDir, "slides");3839/* ---- Structure of a deck, from its sources (pure) ---- */4041export type SourceEvent = { kind: "title" } | { kind: "section"; title: string } | { kind: "content"; id: string | null; title: string } | { kind: "references" } | { kind: "closing" };4243/** Removes TeX comments (an unescaped % to the end of the line). */44const uncomment = (tex: string) => tex.split("\n").map((l) => l.replace(/(^|[^\\])%.*$/, "$1")).join("\n");45/** The balanced {…} group starting at `at` (which must be an opening brace), without its braces. */46function group(tex: string, at: number): string | null {47 if (tex[at] !== "{") return null;48 let depth = 0;49 for (let i = at; i < tex.length; i++) { if (tex[i] === "\\") { i++; continue; } if (tex[i] === "{") depth++; else if (tex[i] === "}" && --depth === 0) return tex.slice(at + 1, i); }50 return null;51}52const plain = (tex: string) => tex.replace(/\\[a-zA-Z]+\*?(\[[^\]]*\])?/g, "").replace(/[{}~]/g, " ").replace(/\s+/g, " ").trim();5354/**55 * Reads the order of the pages a deck produces from `main.tex` and the files it inputs: the title slide,56 * section dividers, content frames with their label, the references and the closing slide. Only these57 * structure markers are read; the body of the frames — and the `\note{…}` they contain — is skipped.58 */59export function parseDeckSource(main: string, read: (relPath: string) => string | null): SourceEvent[] {60 const events: SourceEvent[] = [];61 const scan = (source: string, depth: number) => {62 const tex = uncomment(source), re = /\\(?:(AtlasTitleSlide|AtlasSection|AtlasReferences|AtlasClosingSlide|input)\b|begin\{frame\})/g;63 for (let m = re.exec(tex); m; m = re.exec(tex)) {64 const after = m.index + m[0].length;65 if (m[1] === "AtlasTitleSlide") events.push({ kind: "title" });66 else if (m[1] === "AtlasReferences") events.push({ kind: "references" });67 else if (m[1] === "AtlasClosingSlide") events.push({ kind: "closing" });68 else if (m[1] === "AtlasSection") events.push({ kind: "section", title: plain(group(tex, after) ?? "") });69 else if (m[1] === "input") { const rel = group(tex, after)?.trim(); if (rel && depth < 3 && /^[A-Za-z0-9._/-]+$/.test(rel) && !rel.includes("..")) { const body = read(rel.endsWith(".tex") ? rel : `${rel}.tex`); if (body !== null) scan(body, depth + 1); } }70 else {71 let at = after;72 const opt = /^\s*\[[^\]]*\]/.exec(tex.slice(at)); if (opt) at += opt[0].length;73 const title = plain(group(tex, at) ?? "");74 const end = tex.indexOf("\\end{frame}", at), label = /\\label\{(S\d{2,3}-D\d{2,3})\}/.exec(tex.slice(at, end < 0 ? at + 400 : end));75 events.push({ kind: "content", id: label?.[1] ?? null, title });76 if (end > 0) re.lastIndex = end; // nothing inside a frame is a structure marker — and its notes are not read77 }78 }79 };80 scan(main, 0);81 return events;82}8384export interface PageText { kicker: string; title: string; text: string }8586/** Splits the text of one PDF page into the header strip, the title and the body, without the footer strip. */87export function cleanPageText(raw: string, sessionId: string): PageText {88 let lines = raw.replace(/\f/g, "").split("\n").map((l) => l.replace(/\s+/g, " ").trim());89 const footer = (l: string) => /^ATLAS IA$/.test(l) || new RegExp(`^${sessionId} • \\d+ / \\d+$`).test(l) || / · UQO$/.test(l) || /^\d+ \/ \d+$/.test(l);90 while (lines.length && (lines[lines.length - 1] === "" || footer(lines[lines.length - 1]!))) lines.pop();91 // The header strip (« S01 • Partie I : … », « S01 • SECTION 2 ») and a divider's lone number come first, in either order.92 let kicker = "";93 for (let i = 0; i < Math.min(lines.length, 5); i++) {94 const l = lines[i]!;95 if (l === "" ) continue;96 if (l.startsWith(`${sessionId} •`)) { kicker = l; lines.splice(i, 1); i--; }97 else if (l === "ATLAS IA" || /^\d{1,2}$/.test(l)) { lines.splice(i, 1); i--; }98 else break;99 }100 lines = lines.join("\n").replace(/\n{3,}/g, "\n\n").split("\n");101 while (lines.length && lines[0] === "") lines.shift();102 return { kicker, title: (lines[0] ?? "").slice(0, 300) || "Diapositive", text: lines.join("\n").trim() };103}104105export interface MappedSlide { n: number; id: string | null; kind: Deck["slides"][number]["kind"]; title: string; section: string | null; text: string }106107/**108 * Gives every PDF page its kind, its slide identifier and its section. The source order is authoritative109 * when it accounts for every page (the references take whatever pages are left: at least one); otherwise110 * the kinds are read from the pages themselves and no identifier is assigned — reported as a warning,111 * never guessed.112 */113export function mapSlides(events: SourceEvent[], pages: PageText[]): { slides: MappedSlide[]; warnings: string[] } {114 const warnings: string[] = [], fixed = events.filter((e) => e.kind !== "references").length, refs = events.filter((e) => e.kind === "references").length;115 const extra = pages.length - fixed;116 let sequence: SourceEvent[] | null = null;117 if (refs === 1 && extra >= 1) sequence = events.flatMap((e): SourceEvent[] => (e.kind === "references" ? Array.from({ length: extra }, () => e) : [e]));118 else if (refs === 0 && extra === 0) sequence = events;119 // The pages must agree with the source where it can be checked: dividers say « SECTION », references say « Références ».120 if (sequence && !sequence.every((e, i) => (e.kind === "section") === /• SECTION/i.test(pages[i]!.kicker) && (e.kind !== "references" || /^Références/i.test(pages[i]!.title)))) sequence = null;121 if (!sequence) {122 warnings.push(`la structure des sources (${events.length} repères) ne correspond pas aux ${pages.length} pages du PDF : types déduits des pages, identifiants de diapositives omis`);123 sequence = pages.map((p, i): SourceEvent => (i === 0 ? { kind: "title" } : /• SECTION/i.test(p.kicker) ? { kind: "section", title: p.title } : /^Références/i.test(p.title) ? { kind: "references" } : i === pages.length - 1 && !/Partie|Synthèse/.test(p.kicker) ? { kind: "closing" } : { kind: "content", id: null, title: p.title }));124 }125 let section: string | null = null;126 const ids = new Set<string>();127 const slides = sequence.map((e, i): MappedSlide => {128 const p = pages[i]!;129 let id = e.kind === "content" ? e.id : null;130 if (id && ids.has(id)) { warnings.push(`identifiant ${id} utilisé deux fois : conservé pour la première diapositive seulement`); id = null; }131 if (id) ids.add(id);132 // Titles written in the sources are exact; the first line of the page is the fallback (a long title wraps in the PDF).133 const title = (e.kind === "content" || e.kind === "section") && e.title && !/[\\$]/.test(e.title) ? e.title : p.title;134 if (e.kind === "section") section = title;135 return { n: i + 1, id, kind: e.kind, title, section: e.kind === "title" || e.kind === "closing" ? null : section, text: p.text };136 });137 return { slides, warnings };138}139140/* ---- Build (poppler) ---- */141142export async function popplerStatus(): Promise<{ ok: boolean; message: string | null }> {143 for (const cmd of ["pdfinfo", "pdftotext", "pdftocairo"]) { try { await run(cmd, ["-v"], { timeout: 10_000 }); } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return { ok: false, message: `${cmd} (poppler) est introuvable : la conversion des diapositives se fait sur une machine qui l'a (brew install poppler), puis le résultat s'importe comme un paquet.` }; } }144 return { ok: true, message: null };145}146147const FigureManifest = (raw: unknown): { id: string; alt: string; slides: string[] }[] => {148 const figs = (raw as { figures?: unknown })?.figures;149 return Array.isArray(figs) ? figs.flatMap((f: { id?: unknown; alt?: unknown; slides?: unknown }) => (typeof f?.id === "string" && typeof f.alt === "string" && Array.isArray(f.slides) ? [{ id: f.id, alt: f.alt.trim(), slides: f.slides.filter((s): s is string => typeof s === "string") }] : [])) : [];150};151152/** Reads a file of the repository, confined to it (no "..", no link to the outside), size-limited. Null when absent. */153async function repoFile(root: string, rel: string, max: number): Promise<Buffer | null> {154 if (!isSafeRelPath(rel)) return null;155 try { const real = await realpath(resolve(root, rel)); if (!real.startsWith(root + sep)) return null; const s = await stat(real); return s.isFile() && s.size <= max ? await readFile(real) : null; } catch { return null; }156}157158export interface BuiltDeck { deck: Deck; dir: string; bytes: { svg: number; svgGzip: number; thumbs: number } }159160/**161 * Converts one session's two web PDFs into a pack directory `<out>/<session>/` (deck.json + assets).162 * Returns null, with the reason, when the session has no complete pair of web PDFs.163 */164export async function buildDeck(repoDir: string, sessionId: string, out: string): Promise<BuiltDeck | { skipped: string }> {165 if (!/^S\d{2,3}$/.test(sessionId)) throw new Error("identifiant de séance invalide");166 const root = await realpath(resolve(repoDir));167 const pdf = { dark: await repoFile(root, `dist/slides/${sessionId}-web.pdf`, 80e6), light: await repoFile(root, `dist/slides/${sessionId}-web-light.pdf`, 80e6) };168 if (!pdf.dark || !pdf.light) return { skipped: "exports web absents (dist/slides/SXX-web.pdf et SXX-web-light.pdf)" };169 if (pdf.dark.subarray(0, 5).toString() !== "%PDF-" || pdf.light.subarray(0, 5).toString() !== "%PDF-") return { skipped: "un export web n'est pas un PDF" };170 const sessionDir = (await readdir(join(root, "sessions")).catch(() => [])).find((d) => d.startsWith(`${sessionId}-`) && isSafeRelPath(d));171 if (!sessionDir) return { skipped: "dossier de la séance introuvable" };172173 const work = await mkdtemp(join(tmpdir(), "atlas-deck-"));174 try {175 const files = { dark: join(work, "dark.pdf"), light: join(work, "light.pdf") };176 await writeFile(files.dark, pdf.dark); await writeFile(files.light, pdf.light); // poppler only ever sees these copies177 const info = async (f: string) => { const o = (await run("pdfinfo", [f], { timeout: 30_000 })).stdout; const size = /Page size:\s+([\d.]+) x ([\d.]+)/.exec(o); return { pages: Number(/Pages:\s+(\d+)/.exec(o)?.[1] ?? 0), width: Number(size?.[1] ?? 0), height: Number(size?.[2] ?? 0) }; };178 const [d, l] = [await info(files.dark), await info(files.light)];179 if (!d.pages || d.pages !== l.pages) return { skipped: `les deux exports n'ont pas le même nombre de pages (${d.pages} et ${l.pages})` };180 if (d.pages > 400) return { skipped: "plus de 400 pages" };181182 const main = (await repoFile(root, `sessions/${sessionDir}/slides/main.tex`, 2e6))?.toString("utf8");183 const sources = new Map<string, string | null>();184 for (const rel of main ? [...uncomment(main).matchAll(/\\input\{([^}]+)\}/g)].map((m) => m[1]!.trim()) : []) { const name = rel.endsWith(".tex") ? rel : `${rel}.tex`; sources.set(name, (await repoFile(root, `sessions/${sessionDir}/slides/${name}`, 2e6))?.toString("utf8") ?? null); }185 const events = main ? parseDeckSource(main, (rel) => sources.get(rel) ?? null) : [];186 const pages: ReturnType<typeof cleanPageText>[] = [];187 for (let n = 1; n <= d.pages; n++) pages.push(cleanPageText((await run("pdftotext", ["-f", String(n), "-l", String(n), "-enc", "UTF-8", files.dark, "-"], { timeout: 30_000, maxBuffer: 4e6 })).stdout, sessionId));188 const { slides, warnings } = mapSlides(events, pages);189 if (!main) warnings.push("slides/main.tex absent : identifiants de diapositives omis");190 const manifest = (await repoFile(root, `sessions/${sessionDir}/figures/manifest.yaml`, 2e6))?.toString("utf8");191 let figures: ReturnType<typeof FigureManifest> = [];192 try { figures = manifest ? FigureManifest(parseYaml(manifest, { schema: "core", maxAliasCount: 50 })) : []; } catch { warnings.push("figures/manifest.yaml illisible : descriptions de figures omises"); }193194 const hash = sha256(`${sha256(pdf.dark)}:${sha256(pdf.light)}:${JSON.stringify(slides.map((s) => [s.id, s.kind]))}:${JSON.stringify(figures)}:v1`);195 const dir = `${sessionId}/${hash.slice(0, 12)}`, target = join(resolve(out), sessionId);196 await rm(target, { recursive: true, force: true });197 const bytes = { svg: 0, svgGzip: 0, thumbs: 0 };198 const entry = async (rel: string, data: Buffer) => { await mkdir(dirname(join(target, rel)), { recursive: true }); await writeFile(join(target, rel), data); return { path: rel, sha256: sha256(data), bytes: data.length }; };199 const { default: sharp } = await import("sharp");200 const made: Record<SlideTheme, { svg: Awaited<ReturnType<typeof entry>>[]; thumb: Awaited<ReturnType<typeof entry>>[] }> = { dark: { svg: [], thumb: [] }, light: { svg: [], thumb: [] } };201 for (const theme of ["dark", "light"] as const) {202 await run("pdftocairo", ["-png", "-scale-to-x", "480", "-scale-to-y", "-1", files[theme], join(work, `t-${theme}`)], { timeout: 300_000 });203 const pngs = (await readdir(work)).filter((f) => f.startsWith(`t-${theme}-`) && f.endsWith(".png")).sort();204 if (pngs.length !== d.pages) throw new Error(`vignettes : ${pngs.length} images pour ${d.pages} pages`);205 for (let n = 1; n <= d.pages; n++) {206 const svgFile = join(work, `p-${theme}-${n}.svg`);207 await run("pdftocairo", ["-svg", "-f", String(n), "-l", String(n), files[theme], svgFile], { timeout: 60_000 });208 const svg = await readFile(svgFile), check = checkSvg(svg.toString("utf8"));209 if (!check.ok) throw new Error(`diapositive ${n} (${theme}) refusée : ${check.reason}`);210 if (svg.length > 3e6) throw new Error(`diapositive ${n} (${theme}) : image vectorielle de plus de 3 Mo`);211 made[theme].svg.push(await entry(`${theme}/${pad3(n)}.svg`, svg));212 bytes.svg += svg.length; bytes.svgGzip += gzipSync(svg, { level: 9 }).length;213 const webp = await sharp(join(work, pngs[n - 1]!)).webp({ quality: 74, effort: 5 }).toBuffer();214 made[theme].thumb.push(await entry(`thumbs/${theme}/${pad3(n)}.webp`, webp));215 bytes.thumbs += webp.length;216 }217 }218 const deck = Deck.parse({219 session: sessionId, hash, dir, count: d.pages, width: d.width, height: d.height, warnings,220 slides: slides.map((s, i) => ({ ...s, figures: s.id ? figures.filter((f) => f.slides.includes(s.id!)).map((f) => ({ id: f.id, alt: f.alt })) : [], files: { dark: made.dark.svg[i]!, light: made.light.svg[i]!, thumbDark: made.dark.thumb[i]!, thumbLight: made.light.thumb[i]! } })),221 });222 await writeFile(join(target, "deck.json"), `${JSON.stringify(deck, null, 2)}\n`);223 return { deck, dir: target, bytes };224 } finally { await rm(work, { recursive: true, force: true }); }225}226227/** Packs a built deck directory as .tar.gz (deck.json + assets), to carry it to a machine without poppler. */228export async function packDeck(dir: string, file: string): Promise<number> {229 const deck = Deck.parse(JSON.parse(await readFile(join(dir, "deck.json"), "utf8")));230 const names = ["deck.json", ...deck.slides.flatMap((s) => Object.values(s.files).map((f) => f.path))];231 const tar = gzipSync(Buffer.concat([...(await Promise.all(names.map(async (n) => tarEntry(`${deck.session}/${n}`, await readFile(join(dir, n)), new Date(0))))), TAR_END]), { level: 6 });232 await writeFile(file, tar);233 return tar.length;234}235236/* ---- Import of a pack into the studio ---- */237238/**239 * Validates a pack — a directory holding deck.json, or a .tar.gz of one — and installs it:240 * assets under ATLAS_DATA_DIR/slides/<session>/<hash>/ (never rewritten: a new deck gets a new directory, so a241 * publication keeps the slides it was made with), and the « slides » section of the session set to the new242 * deck, with the visibility it had (private the first time). Nothing becomes public here.243 */244export async function importDeck(source: string, actor: string, expectSession?: string): Promise<{ deck: Deck; changed: boolean }> {245 let dir = resolve(/* turbopackIgnore: true */ source), scratch: string | null = null;246 try {247 if (!(await stat(/* turbopackIgnore: true */ dir)).isDirectory()) {248 scratch = await mkdtemp(join(tmpdir(), "atlas-deck-in-"));249 await extractArchive(dir, scratch, { maxEntries: 3000, maxFileBytes: 4e6, maxTotalBytes: 400e6, maxRatio: 100 });250 dir = scratch;251 }252 if (!existsSync(join(/* turbopackIgnore: true */ dir, "deck.json"))) { const inner = (await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true })).filter((e) => e.isDirectory() && existsSync(join(/* turbopackIgnore: true */ dir, e.name, "deck.json"))); if (inner.length !== 1) throw new ApiError(422, "bad_pack", "Ce paquet ne contient pas de deck.json (un paquet de diapositives par séance)."); dir = join(/* turbopackIgnore: true */ dir, inner[0]!.name); }253 const parsed = Deck.safeParse(JSON.parse(await readFile(join(/* turbopackIgnore: true */ dir, "deck.json"), "utf8").catch(() => "null")));254 if (!parsed.success) throw new ApiError(422, "bad_pack", `deck.json invalide : ${parsed.error.issues[0]?.path.join(".")} — ${parsed.error.issues[0]?.message}`);255 const deck = parsed.data;256 if (expectSession && deck.session !== expectSession) throw new ApiError(422, "bad_pack", `Ce paquet est celui de ${deck.session}, pas de ${expectSession}.`);257 if (deck.dir !== `${deck.session}/${deck.hash.slice(0, 12)}`) throw new ApiError(422, "bad_pack", "Dossier du paquet incohérent avec son empreinte.");258 getSessionRow(deck.session);259 const target = join(/* turbopackIgnore: true */ slidesRoot(), deck.dir), staging = `${target}.tmp-${process.pid}`;260 // Every file of the pack is checked, even when this deck is already installed: a pack is never taken on trust.261 const installed = existsSync(join(/* turbopackIgnore: true */ target, "deck.json")) ? await readFile(join(/* turbopackIgnore: true */ target, "deck.json"), "utf8") : null;262 if (installed !== null && JSON.stringify(JSON.parse(installed)) !== JSON.stringify(deck)) throw new ApiError(422, "bad_pack", "Un paquet différent porte déjà cette empreinte : paquet refusé.");263 {264 await rm(staging, { recursive: true, force: true });265 for (const s of deck.slides) for (const [key, f] of Object.entries(s.files)) {266 const want = key.startsWith("thumb") ? /^thumbs\/(dark|light)\/\d{3}\.webp$/ : /^(dark|light)\/\d{3}\.svg$/;267 if (!want.test(f.path)) throw new ApiError(422, "bad_pack", `Nom de fichier inattendu dans le paquet : ${f.path}`);268 const data = await readFile(join(/* turbopackIgnore: true */ dir, f.path)).catch(() => null);269 if (!data || data.length !== f.bytes || sha256(data) !== f.sha256) throw new ApiError(422, "bad_pack", `Fichier absent ou altéré dans le paquet : ${f.path}`);270 if (f.path.endsWith(".svg")) { const c = checkSvg(data.toString("utf8")); if (!c.ok) throw new ApiError(422, "bad_pack", `Image refusée (${c.reason}) : ${f.path}`); }271 else if (data.subarray(0, 4).toString() !== "RIFF" || data.subarray(8, 12).toString() !== "WEBP") throw new ApiError(422, "bad_pack", `Vignette qui n'est pas une image WebP : ${f.path}`);272 await mkdir(dirname(join(/* turbopackIgnore: true */ staging, f.path)), { recursive: true });273 await writeFile(join(/* turbopackIgnore: true */ staging, f.path), data);274 }275 if (installed === null) {276 await writeFile(join(/* turbopackIgnore: true */ staging, "deck.json"), `${JSON.stringify(deck, null, 2)}\n`);277 await mkdir(dirname(target), { recursive: true });278 await cp(staging, target, { recursive: true });279 }280 await rm(staging, { recursive: true, force: true });281 }282 const body = `${JSON.stringify(deck)}\n`;283 const changed = tx(() => {284 const cur = getSection(deck.session, "slides"), hash = putBlob(body);285 if (cur?.sha256 === hash) return false;286 writeSection(deck.session, "slides", { sha256: hash, visibility: cur?.visibility ?? "private", count: deck.count, baseSha: hash }, actor);287 audit(cur ? "slides.updated" : "slides.imported", { actor, target: `session:${deck.session}/slides`, beforeRef: cur?.sha256 ?? null, afterRef: hash, detail: { slides: deck.count, deck: deck.hash.slice(0, 12), warnings: deck.warnings } });288 return true;289 });290 return { deck, changed };291 } finally { if (scratch) await rm(scratch, { recursive: true, force: true }); }292}293294/**295 * Absolute path of an asset of a deck, if the deck lists it. SVG slides are stored and sent uncompressed:296 * compressing text responses is the gateway's job (they shrink about six times), as for the rest of the site.297 */298export function deckAsset(deck: Deck, file: string): { path: string; type: string } | null {299 const listed = deck.slides.some((s) => Object.values(s.files).some((f) => f.path === file));300 if (!listed || !isSafeRelPath(file)) return null;301 const base = join(/* turbopackIgnore: true */ slidesRoot(), deck.dir, file);302 return existsSync(/* turbopackIgnore: true */ base) ? { path: base, type: file.endsWith(".svg") ? "image/svg+xml" : "image/webp" } : null;303}304305/* ---- Publishing the slides of a session, and only them ---- */306307function publicItems(s: Session | null): Set<string> {308 return new Set(s ? [...Object.keys(s.sections).map((k) => `section:${k}`), ...s.capsules.map((c) => `capsule:${c.id}`), ...s.resources.map((r) => `resource:${r.id}`)] : []);309}310311/**312 * Puts the slides of a session online without publishing anything else: the « slides » section becomes313 * public and the session is published — refused if that publication would also make public something that314 * is not online today (a quiz, a lab, a capsule… marked public in the studio). Reversible with315 * `unpublishSlides`, or with the publication history of the session.316 */317export function publishSlides(sessionId: string, actor: string, note?: string): PublicationEntry {318 return tx(() => {319 const sec = getSection(sessionId, "slides");320 if (!sec) throw new ApiError(409, "no_slides", `${sessionId} n'a pas de diapositives importées.`);321 const live = liveEntry(sessionId), online = publicItems(live && (live.kind === "publish" || live.kind === "rollback") ? getJson<Session>(live.payloadSha) : null);322 if (sec.visibility !== "public") putSection(sessionId, "slides", { visibility: "public" }, actor);323 if (getSessionRow(sessionId).state !== "preview") setSessionState(sessionId, "preview", actor);324 const extra = [...publicItems(planPublication(getSessionRow(sessionId)).snapshot)].filter((k) => !online.has(k) && k !== "section:slides");325 if (extra.length) throw new ApiError(409, "would_publish_more", `${sessionId} : la publication des diapositives rendrait aussi publics ${extra.join(", ")}, marqués « public » dans le studio. Rien n'a été publié ; réglez leur visibilité ou publiez la séance depuis le studio.`);326 return publishSession(sessionId, { confirm: sessionId, note: note ?? "Diapositives mises en ligne" }, actor);327 });328}329330/** Takes the slides of a session offline. A session that offered nothing else goes back to « À venir ». */331export function unpublishSlides(sessionId: string, actor: string, note?: string): PublicationEntry | null {332 return tx(() => {333 const sec = getSection(sessionId, "slides"), live = liveEntry(sessionId);334 const snap = live && (live.kind === "publish" || live.kind === "rollback") ? getJson<Session>(live.payloadSha) : null;335 if (sec && sec.visibility === "public") putSection(sessionId, "slides", { visibility: "preview" }, actor);336 if (!snap?.sections.slides) return null; // not online: nothing to withdraw337 const online = publicItems(snap);338 if (online.size === 1) return retireSession(sessionId, "withdraw", { confirm: sessionId, note: note ?? "Diapositives retirées" }, actor);339 const extra = [...publicItems(planPublication(getSessionRow(sessionId)).snapshot)].filter((k) => !online.has(k));340 if (extra.length) throw new ApiError(409, "would_publish_more", `${sessionId} : republier sans les diapositives rendrait aussi publics ${extra.join(", ")}. Faites-le depuis le studio.`);341 return publishSession(sessionId, { confirm: sessionId, note: note ?? "Diapositives retirées" }, actor);342 });343}344