Files
dogfather-universe/server/pruef-nachschauen-blick.mjs

388 lines
26 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* =====================================================================
NACHSCHAUEN MIT DEM CHAT VON DAMALS (05.11.2026, Neuplan M7)
Server: Schalter nur für die Regie, Stelle je Beitrag, Aufheben beim
Beenden (ohne Entferntes), Schalter danach aus, Gegenprobe ohne Schalter,
Agentur 404. Seite: Puls, Rauten, Chat läuft mit (YouTube durch eine
Attrappe ersetzt – die echte Wiedergabe ist hier nicht messbar).
DREI AUSGÄNGE: 0 in Ordnung · 1 Befund · 3 konnte nicht nachsehen.
Bilder: NS_BILDER=<ordner> node server/pruef-nachschauen-blick.mjs
===================================================================== */
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { request } from "node:http";
import { createServer as httpsServer } from "node:https";
import { zertifikatBauen } from "./helfer-openssl.mjs";
import { notbremse } from "./helfer-notbremse.mjs";
import { eigenerPort } from "./helfer-port.mjs";
const HIER = dirname(fileURLToPath(import.meta.url));
const ordner = mkdtempSync(join(tmpdir(), "pruef-nachschauen-"));
process.env.WORKSPACE_DB = join(ordner, "workspace.db");
const PORT = await eigenerPort(import.meta);
const HTTPS_PORT = await eigenerPort(import.meta, "pruef-nachschauen-blick (HTTPS)", 1);
process.env.PORT = `${PORT}`;
process.env.SITE_ACCESS_SECRET = "lokaler-test";
/* Protokoll-Minuten alle 2 s statt 60 s – sonst wartete die Prüfung Minuten. */
process.env.REAKTION_MINUTE_MS = "2000";
process.env.SITE_PUBLIC_LAUNCH_AT = "2020-01-01T00:00:00+01:00";
const express = (await import("express")).default;
/* Der Sitzungskeks ist `secure`. Der Vorbau unten spricht https, der
Server dahinter nicht -- ohne diesen Griff setzt er den Keks und
der Browser verwirft ihn. */
const ec = express.response.cookie;
express.response.cookie = function (n, w, o) { return ec.call(this, n, w, { ...(o || {}), secure: false }); };
await import("./index.js");
notbremse(300_000, "pruef-nachschauen-blick");
await new Promise((r) => setTimeout(r, 1000));
const CREW = "crew.dogfather-universe.com";
/* ---------- Leute ------------------------------------------------------- */
const { DatabaseSync } = await import("node:sqlite");
const { scryptSync, randomBytes, createHmac } = await import("node:crypto");
const d = new DatabaseSync(process.env.WORKSPACE_DB);
const kenn = randomBytes(32).toString("hex");
d.prepare("INSERT INTO einstellungen (schluessel, wert, geaendert, von)"
+ " VALUES (?,?,?,NULL) ON CONFLICT(schluessel) DO NOTHING")
.run("code_kennung_schluessel", kenn, new Date().toISOString());
const ALT = new Date(Date.now() - 200 * 86400000).toISOString();
function anlegen(name, rolle, code) {
const salt = randomBytes(16).toString("hex");
const hash = scryptSync(code, salt, 64,
{ N: 32768, r: 8, p: 1, maxmem: 96 * 1024 * 1024 }).toString("hex");
d.prepare("INSERT INTO personen (name, rolle, code_hash, code_salt, code_n,"
+ " code_kennung, aktiv, erstellt) VALUES (?,?,?,?,?,?,1,?)")
.run(name, rolle, hash, salt, 32768,
createHmac("sha256", kenn).update(code).digest("hex"), ALT);
}
const CODES = {
admin: "CODE-M00-000001", hand: "CODE-M01-000001",
gast: "CODE-M02-000001", gast2: "CODE-M03-000001",
};
/* VANVAN IST DIE RECHTE HAND und wird mitgemessen, nicht nur
DogFather: Filipe hat "nur ich und vanvan" gesagt, und ob die
zweite Haelfte davon stimmt, sieht man nur, wenn sie dabei ist. */
anlegen("DogFather", "admin", CODES.admin);
anlegen("VanVan", "hand", CODES.hand);
anlegen("Nachtfalter", "gast", CODES.gast);
anlegen("Lenny", "gast", CODES.gast2);
d.close();
function roh(pfad, { method = "GET", keks = "", rumpf = null } = {}) {
return new Promise((fertig, schief) => {
const daten = rumpf === null ? null : Buffer.from(JSON.stringify(rumpf));
const a = request({
host: "127.0.0.1", port: PORT, path: pfad, method,
headers: {
Host: CREW, Origin: `https://${CREW}`,
...(keks ? { Cookie: keks } : {}),
...(daten ? { "Content-Type": "application/json", "Content-Length": daten.length } : {}),
},
}, (antwort) => {
const teile = [];
antwort.on("data", (s) => teile.push(s));
antwort.on("end", () => {
const text = Buffer.concat(teile).toString("utf8");
let j = null; try { j = JSON.parse(text); } catch { /* kein JSON */ }
fertig({ code: antwort.statusCode, text, j, kopf: antwort.headers });
});
});
a.on("error", schief);
if (daten) a.write(daten);
a.end();
});
}
async function anmelden(wer) {
const a = await roh("/workspace/api/anmelden", {
method: "POST",
rumpf: { rolle: wer === "gast2" ? "gast" : wer, code: CODES[wer], alter_ok: true },
});
return [].concat(a.kopf["set-cookie"] || []).map((z) => z.split(";")[0]).join("; ");
}
const k = {
admin: await anmelden("admin"),
hand: await anmelden("hand"),
gast: await anmelden("gast"),
gast2: await anmelden("gast2"),
};
/* ---------- Zaehlwerk --------------------------------------------------- */
let fehler = 0;
let geprueft = 0;
const ok = (b, t) => {
geprueft++;
console.log((b ? " ok " : " FEHL ") + t);
if (!b) fehler++;
};
function nichtNachsehbar(grund) {
console.log("\n -- NICHT NACHSEHBAR");
console.log(` ${grund}`);
console.log(" Das ist KEIN Befund am Code -- es heisst nur, dass");
console.log(" gerade niemand nachsehen konnte.\n");
try { rmSync(ordner, { recursive: true, force: true }); } catch { /* egal */ }
process.exit(3);
}
/* ---------- Die Buehne fuellen ------------------------------------------ */
/* ZWEI STUECKE IN DER WARTESCHLANGE, EINES MIT TERMIN UND EINES OHNE.
Genau das ist die Aussage der linken Reihe ("was keinen hat, steht
unten"), und mit nur einem Eintrag liesse sie sich nicht messen. */
for (const adresse of ["https://youtu.be/9bZkp7q19f0",
"https://www.youtube.com/watch?v=kJQP7kiw5Fk"]) {
const a = await roh("/workspace/api/reaktion/liste", {
method: "POST", keks: k.admin, rumpf: { video: adresse },
});
if (a.code >= 400) nichtNachsehbar(`Die Warteschlange nimmt nichts an (HTTP ${a.code}).`);
}
const liste0 = (await roh("/workspace/api/reaktion", { keks: k.admin })).j?.liste || [];
if (liste0.length !== 2) {
nichtNachsehbar(`In der Warteschlange stehen ${liste0.length} Stuecke statt 2.`);
}
/* Der Termin liegt in der ZUKUNFT und wird relativ gerechnet. Ein
festes Datum waere eine Zeitbombe: Es ist richtig, bis der Kalender
es einholt -- und dann schlaegt "ueberfaellig" an, ohne dass etwas
kaputt ist. */
{
const a = await roh(`/workspace/api/reaktion/liste/${liste0[0].id}/wann`, {
method: "PUT", keks: k.admin,
rumpf: { wann: new Date(Date.now() + 3 * 86400000).toISOString() },
});
if (a.code >= 400) nichtNachsehbar(`Der Termin laesst sich nicht setzen (HTTP ${a.code}).`);
}
await roh("/workspace/api/reaktion", {
method: "PUT", keks: k.admin,
rumpf: {
titel: "Wir schauen den neuen Trailer",
video: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
beginnt_am: new Date(Date.now() + 7 * 60_000).toISOString(),
},
});
/* ---------- Der Vorbau -------------------------------------------------- */
const schluesselDatei = join(ordner, "p.key");
const zertDatei = join(ordner, "p.crt");
try {
zertifikatBauen(schluesselDatei, zertDatei, CREW);
} catch (f) {
nichtNachsehbar(`Kein Zertifikat zu bauen: ${f?.message}\n`
+ " openssl liegt bei Git in mingw64/bin -- im System-PATH\n"
+ " steht oft nur Git/cmd.");
}
const vorbau = httpsServer({
key: readFileSync(schluesselDatei), cert: readFileSync(zertDatei),
}, (von, nach) => {
const weiter = request({
host: "127.0.0.1", port: PORT, path: von.url, method: von.method,
headers: { ...von.headers, host: `${CREW}:${HTTPS_PORT}` },
}, (antwort) => {
nach.writeHead(antwort.statusCode || 502, antwort.headers);
antwort.pipe(nach);
});
weiter.on("error", () => { try { nach.writeHead(502); nach.end(); } catch { /* egal */ } });
von.pipe(weiter);
});
await new Promise((r) => vorbau.listen(HTTPS_PORT, "127.0.0.1", r));
const BASIS = `https://${CREW}:${HTTPS_PORT}`;
for (const st of ["vorbereitung", "live"]) await roh("/workspace/api/reaktion/stand", { method: "POST", keks: k.admin, rumpf: { stand: st } });
const standNun = (await roh("/workspace/api/reaktion", { keks: k.admin })).j?.stand;
if (standNun !== "live") nichtNachsehbar(`Die Sendung geht nicht live (${standNun}).`);
for (const [w, t] of [["gast", "Erster im Saal"], ["gast2", "Zweite Nachricht"]]) await roh("/workspace/api/reaktion/chat", { method: "POST", keks: k[w], rumpf: { text: t } });
let pw = null;
try { pw = await import("file:///C:/Users/qciga/Documents/Obelix/Analyse/node_modules/playwright/index.mjs"); } catch (f) { nichtNachsehbar(`Playwright fehlt: ${f?.message}`); }
const browser = await pw.chromium.launch({ args: [`--host-resolver-rules=MAP ${CREW} 127.0.0.1`, "--ignore-certificate-errors", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--autoplay-policy=no-user-gesture-required"] });
const BILDER = process.env.NS_BILDER || "";
const warte = (ms) => new Promise((r) => setTimeout(r, ms));
const { DatabaseSync: DB2 } = await import("node:sqlite");
function rohHaus(host, pfad) {
return new Promise((fertig) => {
const a = request({ host: "127.0.0.1", port: PORT, path: pfad, method: "GET", headers: { Host: host, Cookie: k.admin } }, (an) => { an.resume(); an.on("end", () => fertig(an.statusCode)); });
a.on("error", () => fertig(0)); a.end();
});
}
/* ---------- Teil 1: der Server ---------------------------------------- */
let a = await roh("/workspace/api/reaktion/nachschauen/aufheben", { method: "POST", keks: k.gast, rumpf: { an: true } });
ok(a.code === 403, `ein Gast kann den Chat NICHT aufheben lassen (${a.code})`);
a = await roh("/workspace/api/reaktion/nachschauen/aufheben", { method: "POST", keks: k.admin, rumpf: { an: true } });
ok(a.code === 200 && a.j?.chat_aufheben === true, `die Regie schaltet „Chat zum Nachschauen aufheben“ an (${a.code}, ${a.j?.chat_aufheben})`);
const sicht = (await roh("/workspace/api/reaktion", { keks: k.gast })).j;
ok(sicht?.chat_aufheben === true, "der Saal erfährt es (für den Hinweis im Chat-Kopf)");
/* Das Video steht an bekannten Stellen (wie die Regie es meldet) – die Stelle
je Beitrag rechnet der Server aus SEINEM Stand. */
const stelle = (sek) => roh("/workspace/api/reaktion/video", { method: "POST", keks: k.admin, rumpf: { laeuft: false, sekunde: sek } });
for (const [w, t, sek] of [["gast", "Gleich kommt die Stelle!", 10], ["gast2", "Haha, wie gut", 40], ["gast", "Wird gleich entfernt", 70]]) {
await stelle(sek);
await roh("/workspace/api/reaktion/chat", { method: "POST", keks: k[w], rumpf: { text: t } });
await warte(400);
}
const db1 = new DB2(process.env.WORKSPACE_DB);
const zeilen = db1.prepare("SELECT id, text, video, sekunde FROM reaktion_chat ORDER BY id").all();
ok(zeilen.length >= 5 && JSON.stringify(zeilen.slice(-3).map((z) => z.sekunde)) === "[10,40,70]" && zeilen.slice(-3).every((z) => z.video), `jeder neue Beitrag trägt Video und Stelle, vom Server gerechnet (${JSON.stringify(zeilen.slice(-3).map((z) => z.sekunde))})`);
const weg = zeilen.find((z) => z.text === "Wird gleich entfernt");
a = await roh(`/workspace/api/reaktion/chat/${weg.id}`, { method: "DELETE", keks: k.admin });
ok(a.code < 300, `ein Beitrag wird entfernt (${a.code})`);
await stelle(55);
a = await roh("/workspace/api/reaktion/moment", { method: "POST", keks: k.admin, rumpf: {} });
ok(a.code < 300, `ein Moment wird markiert (${a.code})`);
await warte(4500); /* REAKTION_MINUTE_MS=2000: mindestens eine Protokoll-Minute */
const minuten = db1.prepare("SELECT sekunde, video FROM reaktion_protokoll WHERE art = 'minute'").all();
ok(minuten.length >= 1 && minuten.every((m) => m.sekunde != null && m.video), `die Protokoll-Minuten tragen jetzt die Stelle im Video (${minuten.length} Minuten)`);
db1.close();
const vorher = (await roh("/workspace/api/reaktion/chat", { keks: k.admin })).j?.beitraege?.length || 0;
a = await roh("/workspace/api/reaktion/stand", { method: "POST", keks: k.admin, rumpf: { stand: "zu" } });
ok(a.code < 300, `die Sendung endet (${a.code})`);
const db2 = new DB2(process.env.WORKSPACE_DB);
const v1 = db2.prepare("SELECT id FROM reaktion_verlauf ORDER BY id DESC LIMIT 1").get();
const auf = db2.prepare("SELECT name, text, sekunde FROM reaktion_nachschau_chat WHERE verlauf_id = ?").all(v1.id);
const nachZu = db2.prepare("SELECT chat_aufheben FROM reaktion WHERE id = 1").get();
db2.close();
ok(auf.length === vorher && auf.length >= 4 && !auf.some((x) => x.text === "Wird gleich entfernt"), `beim Beenden aufgehoben: ${auf.length} Beiträge, der entfernte nicht (Saal hatte ${vorher})`);
ok(nachZu.chat_aufheben === 0, "danach steht der Schalter wieder auf aus – eine Entscheidung je Abend");
let n1 = (await roh(`/workspace/api/reaktion/nachschauen?id=${v1.id}`, { keks: k.gast })).j;
ok(n1?.da && n1.chat?.length === auf.length && n1.momente.length === 1 && n1.puls.length >= 1, `Nachschauen liefert Chat, Moment und Puls (${n1?.chat?.length} / ${n1?.momente?.length} / ${n1?.puls?.length})`);
/* Ein gelöschter Zugang erscheint ohne Namen. */
const db3 = new DB2(process.env.WORKSPACE_DB);
db3.exec("PRAGMA foreign_keys = ON");
const lenny = db3.prepare("SELECT id FROM personen WHERE name = 'Lenny'").get();
db3.prepare("UPDATE reaktion_nachschau_chat SET person_id = NULL WHERE person_id = ?").run(lenny.id);
db3.close();
n1 = (await roh(`/workspace/api/reaktion/nachschauen?id=${v1.id}`, { keks: k.gast })).j;
ok(n1.chat.some((c) => c.name === "Ehemals dabei") && !n1.chat.some((c) => c.name === "Lenny"), "ein gelöschter Zugang erscheint als „Ehemals dabei“, nicht mit Namen");
/* Gegenprobe: eine zweite Sendung OHNE Aufheben */
await roh("/workspace/api/reaktion", { method: "PUT", keks: k.admin, rumpf: { titel: "Zweiter Abend", video: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" } });
for (const st of ["vorbereitung", "live"]) await roh("/workspace/api/reaktion/stand", { method: "POST", keks: k.admin, rumpf: { stand: st } });
await roh("/workspace/api/reaktion/chat", { method: "POST", keks: k.gast, rumpf: { text: "Ohne Aufheben" } });
await roh("/workspace/api/reaktion/stand", { method: "POST", keks: k.admin, rumpf: { stand: "zu" } });
const db4 = new DB2(process.env.WORKSPACE_DB);
const v2 = db4.prepare("SELECT id FROM reaktion_verlauf ORDER BY id DESC LIMIT 1").get();
const auf2 = db4.prepare("SELECT COUNT(*) AS n FROM reaktion_nachschau_chat WHERE verlauf_id = ?").get(v2.id).n;
const chatRest = db4.prepare("SELECT COUNT(*) AS n FROM reaktion_chat").get().n;
db4.close();
const n2 = (await roh(`/workspace/api/reaktion/nachschauen?id=${v2.id}`, { keks: k.gast })).j;
ok(v2.id !== v1.id && auf2 === 0 && n2?.chat === null && chatRest === 0, `Gegenprobe: ohne Schalter wird nichts aufgehoben, der Live-Chat ist weg (${auf2}, chat=${JSON.stringify(n2?.chat)}, Rest ${chatRest})`);
ok(await rohHaus("workspace.dogfather-universe.com", "/workspace/api/reaktion/nachschauen") === 404, "im Agentur-Haus gibt es den Weg nicht (404)");
/* ---------- Teil 2: die Seite des Nachberichts ------------------------- */
const FAKE_YT = () => {
window.__t = 0; window.__sprung = [];
window.YT = { Player: class { constructor(id, o) { this.o = o; const h = document.getElementById(id); if (h) { h.textContent = ""; h.style.background = "#111"; } setTimeout(() => o.events?.onReady?.({ target: this }), 50); }
getCurrentTime() { return window.__t; } getDuration() { return 212; } seekTo(s) { window.__t = s; window.__sprung.push(s); } playVideo() {} cueVideoById() {} loadVideoById() {} } };
};
const kontext = await browser.newContext({ viewport: { width: 1280, height: 900 }, ignoreHTTPSErrors: true });
await kontext.addCookies(k.gast.split("; ").filter(Boolean).map((z) => { const [n, ...r] = z.split("="); return { name: n, value: r.join("="), domain: CREW, path: "/" }; }));
const seite = await kontext.newPage();
const konsole = [];
seite.on("pageerror", (f) => konsole.push(String(f?.message || f)));
seite.on("console", (m) => { if (m.type() === "error" && !/youtube|ytimg|ERR_|net::/i.test(m.text())) konsole.push(m.text()); });
await seite.addInitScript(FAKE_YT);
await seite.goto(`${BASIS}/workspace/nachbericht.html?id=${v1.id}`, { waitUntil: "domcontentloaded" });
await seite.waitForFunction(() => window.__ns || window.__nb?.da === false, null, { timeout: 15000 }).catch(() => {});
await seite.evaluate((id) => { const w = document.getElementById("nb-wahl"); if (w && w.value !== String(id)) { w.value = String(id); w.dispatchEvent(new Event("change", { bubbles: true })); } }, v1.id);
await seite.waitForFunction((id) => window.__ns?.sendung?.id === id, v1.id, { timeout: 15000 }).catch(() => {});
await seite.waitForTimeout(700);
const s1 = await seite.evaluate(() => ({ da: !document.getElementById("ns")?.hidden, rauten: document.querySelectorAll("#ns-leiste .ns-raute").length, saeulen: document.querySelectorAll("#ns-leiste .ns-saeule").length, chat: document.querySelectorAll("#ns-chat .ns-beitrag").length, ohne: !document.getElementById("ns-ohne-chat")?.hidden }));
console.log(" Seite:", JSON.stringify(s1));
ok(s1.da && s1.rauten === 1 && s1.saeulen >= 1 && !s1.ohne, `Nachschauen steht über dem Bericht: Puls-Leiste mit Moment-Raute (${JSON.stringify(s1)})`);
const beiNull = (n1.chat || []).filter((c) => c.sekunde <= 0).length;
ok(s1.chat === beiNull && beiNull < (n1.chat || []).length, `bei 0:00 steht nur, was bei 0:00 geschrieben war (${s1.chat} von ${(n1.chat || []).length}) – der Chat verrät nichts vorab`);
const stellen = (n1.chat || []).map((c) => c.sekunde).sort((x, y) => x - y);
const ziel = stellen.find((x) => x > 0);
await seite.evaluate((t) => { window.__t = t; }, ziel + 0.05);
await seite.waitForTimeout(600);
const s2 = await seite.evaluate(() => ({ n: document.querySelectorAll("#ns-chat .ns-beitrag").length, jetzt: document.querySelectorAll("#ns-chat .ns-beitrag--jetzt").length, letzt: document.querySelector("#ns-chat .ns-beitrag:last-child")?.classList.contains("ns-beitrag--jetzt") }));
const erwartet = stellen.filter((x) => x <= ziel + 0.05).length;
ok(s2.n === erwartet && erwartet > stellen.filter((x) => x <= 0).length && s2.jetzt === 1 && s2.letzt, `der Chat läuft mit: bis zur Stelle ${erwartet} Beiträge, der jüngste hervorgehoben (${JSON.stringify(s2)})`);
await seite.evaluate(() => { window.__t = 0; });
await seite.waitForTimeout(600);
ok(await seite.evaluate(() => document.querySelectorAll("#ns-chat .ns-beitrag").length) === beiNull, "zurückgespult: der Chat geht mit zurück");
const mom = n1.momente[0].sekunde;
await seite.click("#ns-leiste .ns-raute");
await seite.waitForTimeout(300);
const sp = await seite.evaluate(() => window.__sprung.slice());
ok(sp.length === 1 && Math.abs(sp[0] - Math.max(0, mom - 3)) < 0.01, `ein Tipp auf die Raute springt an den Moment (3 s davor): ${sp[0]} bei Moment ${mom}`);
await seite.evaluate(() => { window.__t = 0; window.__sprung = []; });
await seite.click("#ns-weiter");
ok((await seite.evaluate(() => window.__sprung.length)) === 1, "„Nächster Moment“ springt weiter");
const ueber = await seite.evaluate(() => { const b = document.querySelector(".ns-bild").getBoundingClientRect(); return [...document.querySelectorAll("#ns *")].filter((e) => { if (e.closest(".ns-bild")) return false; const r = e.getBoundingClientRect(); return r.width && r.bottom > b.top + 1 && r.top < b.bottom - 1 && r.right > b.left && r.left < b.right; }).length; });
ok(ueber === 0, `nichts liegt über dem YouTube-Bild (${ueber})`);
await seite.evaluate((t) => { window.__t = t; }, stellen[stellen.length - 1] + 1);
await seite.waitForTimeout(500);
if (BILDER) await seite.locator("#ns").screenshot({ path: `${BILDER}/nachschauen-1280.png` });
/* Zweite Sendung: ohne Chat, ehrlich gesagt */
await seite.evaluate((id) => { const w = document.getElementById("nb-wahl"); w.value = String(id); w.dispatchEvent(new Event("change", { bubbles: true })); }, v2.id);
await seite.waitForFunction((id) => window.__ns?.sendung?.id === id, v2.id, { timeout: 15000 }).catch(() => {});
await seite.waitForTimeout(500);
const s3 = await seite.evaluate(() => ({ ohne: !document.getElementById("ns-ohne-chat").hidden, text: document.getElementById("ns-ohne-chat").textContent, chat: !document.getElementById("ns-chat").hidden }));
ok(s3.ohne && !s3.chat && /nicht aufgehoben/.test(s3.text), `ohne aufgehobenen Chat sagt die Seite es (${s3.text})`);
/* Handy */
await seite.setViewportSize({ width: 390, height: 844 });
await seite.evaluate((id) => { const w = document.getElementById("nb-wahl"); w.value = String(id); w.dispatchEvent(new Event("change", { bubbles: true })); }, v1.id);
await seite.waitForTimeout(1200);
const hm = await seite.evaluate(() => ({ breit: document.documentElement.scrollWidth <= innerWidth + 1, weiter: Math.round(document.getElementById("ns-weiter").getBoundingClientRect().height) }));
ok(hm.breit, `Handy: nichts ragt hinaus (${JSON.stringify(hm)})`);
if (BILDER) await seite.screenshot({ path: `${BILDER}/nachschauen-390.png`, fullPage: false });
/* Die stärksten Momente als Clip-Vorschlag (Runde 6): nur die Regie sieht die
Minuten, also nur dort; der Zuschauer bekommt keinen (Gegenprobe). */
const gastClip = await seite.evaluate(() => document.querySelectorAll('#nb-liste [data-clip="ja"]').length);
const kr = await browser.newContext({ viewport: { width: 1280, height: 900 }, ignoreHTTPSErrors: true });
await kr.addCookies(k.admin.split("; ").filter(Boolean).map((z) => { const [n2, ...r] = z.split("="); return { name: n2, value: r.join("="), domain: CREW, path: "/" }; }));
const rs = await kr.newPage();
await rs.addInitScript(FAKE_YT);
await rs.goto(`${BASIS}/workspace/nachbericht.html?id=${v1.id}`, { waitUntil: "domcontentloaded" });
await rs.waitForFunction(() => window.__nb?.da, null, { timeout: 15000 }).catch(() => {});
await rs.evaluate((id) => { const w = document.getElementById("nb-wahl"); if (w && w.value !== String(id)) { w.value = String(id); w.dispatchEvent(new Event("change", { bubbles: true })); } }, v1.id);
await rs.waitForTimeout(1200);
const regieClip = await rs.evaluate(() => [...document.querySelectorAll('#nb-liste [data-clip="ja"]')].map((x) => x.textContent));
ok(regieClip.length === 1 && /Clip-Vorschlag/.test(regieClip[0]) && gastClip === 0, `der stärkste Moment ist als Clip-Vorschlag markiert – bei der Regie, nicht beim Zuschauer (${regieClip.length} / ${gastClip})`);
await kr.close();
/* Runde 8: Das Foyer sagt an „Zuletzt“, was man nachschauen kann. */
await seite.setViewportSize({ width: 1280, height: 900 });
await seite.goto(`${BASIS}/workspace/reaktion-foyer.html`, { waitUntil: "domcontentloaded" });
await seite.waitForFunction(() => document.querySelectorAll("#zuletzt-liste .fy-ns").length >= 2, null, { timeout: 15000 }).catch(() => {});
const fy = await seite.evaluate(() => [...document.querySelectorAll("#zuletzt-liste li[data-sendung]")].map((li) => ({ id: li.dataset.sendung, ns: li.querySelector(".fy-ns")?.textContent || "" })));
const f1 = fy.find((x) => x.id === String(v1.id)), f2 = fy.find((x) => x.id === String(v2.id));
ok(f1 && /mit Chat von damals/.test(f1.ns) && f2 && /Nachschauen/.test(f2.ns) && !/Chat/.test(f2.ns), `im Foyer: „▶ Nachschauen“, mit Chat nur dort, wo er aufgehoben ist (${JSON.stringify([f1, f2])})`);
/* ---------- Teil 3: im Saal: Schalter + Hinweis ----------------------- */
await roh("/workspace/api/reaktion", { method: "PUT", keks: k.admin, rumpf: { titel: "Dritter Abend", video: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" } });
for (const st of ["vorbereitung", "live"]) await roh("/workspace/api/reaktion/stand", { method: "POST", keks: k.admin, rumpf: { stand: st } });
const ka = await browser.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: true });
await ka.addCookies(k.admin.split("; ").filter(Boolean).map((z) => { const [n, ...r] = z.split("="); return { name: n, value: r.join("="), domain: CREW, path: "/" }; }));
const regie = await ka.newPage();
regie.on("pageerror", (f) => konsole.push(String(f?.message || f)));
await regie.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
await regie.waitForSelector("body[data-stand]", { timeout: 20000 });
await regie.waitForTimeout(2000);
await regie.evaluate(() => document.getElementById("reiter-sendung")?.click());
await regie.waitForTimeout(400);
const sch = await regie.evaluate(() => { const z = document.getElementById("ah-zeile"); return z ? { da: !z.hidden && z.getBoundingClientRect().height > 0, an: document.getElementById("ah-schalter").checked } : null; });
ok(sch?.da && sch.an === false, `der Schalter steht in der Tafel „Sendung“, ab Werk aus (${JSON.stringify(sch)})`);
await regie.click("#ah-schalter");
await regie.waitForTimeout(1200);
const zu1 = await browser.newContext({ viewport: { width: 1280, height: 800 }, ignoreHTTPSErrors: true });
await zu1.addCookies(k.gast.split("; ").filter(Boolean).map((z) => { const [n, ...r] = z.split("="); return { name: n, value: r.join("="), domain: CREW, path: "/" }; }));
const saal = await zu1.newPage();
await saal.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
await saal.waitForSelector("body[data-stand]", { timeout: 20000 });
await saal.waitForTimeout(2000);
const hin = await saal.evaluate(() => { const h = document.getElementById("ah-hinweis"); return h ? { da: !h.hidden && h.getBoundingClientRect().height > 0, text: h.textContent } : null; });
ok(hin?.da && /aufgehoben/.test(hin.text), `im Saal steht der Hinweis im Chat-Kopf, bevor jemand schreibt (${JSON.stringify(hin)})`);
if (BILDER) await saal.locator("#schiene").screenshot({ path: `${BILDER}/nachschauen-hinweis.png` });
await regie.click("#ah-schalter");
await saal.waitForTimeout(1800);
ok(await saal.evaluate(() => document.getElementById("ah-hinweis")?.hidden === true), "Schalter aus: der Hinweis verschwindet");
ok(!konsole.length, `keine Fehler in der Konsole (${konsole.slice(0, 3).join(" | ")})`);
await browser.close();
vorbau.close();
console.log(`\n${geprueft} Pruefungen, ${fehler} Fehler`);
try { rmSync(ordner, { recursive: true, force: true }); } catch { /* egal */ }
process.exit(fehler ? 1 : 0);