275 lines
15 KiB
JavaScript
275 lines
15 KiB
JavaScript
/* =====================================================================
|
||
DER PROBEABEND (05.11.2026, Perfektionsplan Runde 3)
|
||
Server nur für die Regie, Agentur 404; jeder Punkt misst selbst und
|
||
kann „geht“, „knapp“ und „geht nicht“ sagen (Attrappen für Stream Deck,
|
||
kein Untertitel-Dienst), Freistellen stellt sich zurück, Ergebnis bleibt.
|
||
DREI AUSGÄNGE: 0 in Ordnung · 1 Befund · 3 konnte nicht nachsehen.
|
||
Bilder: PA_BILDER=<ordner> node server/pruef-probeabend-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-probeabend-"));
|
||
process.env.WORKSPACE_DB = join(ordner, "workspace.db");
|
||
|
||
const PORT = await eigenerPort(import.meta);
|
||
const HTTPS_PORT = await eigenerPort(import.meta, "pruef-probeabend-blick (HTTPS)", 1);
|
||
process.env.PORT = `${PORT}`;
|
||
process.env.SITE_ACCESS_SECRET = "lokaler-test";
|
||
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-probeabend-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.PA_BILDER || "";
|
||
const warte = (ms) => new Promise((r) => setTimeout(r, ms));
|
||
function rohHaus(host, pfad, keks) {
|
||
return new Promise((fertig) => {
|
||
const a = request({ host: "127.0.0.1", port: PORT, path: pfad, method: "GET", headers: { Host: host, Cookie: keks } }, (an) => { an.resume(); an.on("end", () => fertig(an.statusCode)); });
|
||
a.on("error", () => fertig(0)); a.end();
|
||
});
|
||
}
|
||
/* ---------- Server ---------- */
|
||
ok((await roh("/workspace/api/reaktion/probeabend", { keks: k.gast })).code === 403, "ein Zuschauer sieht den Probeabend nicht (403)");
|
||
ok((await roh("/workspace/api/reaktion/probeabend", { method: "PUT", keks: k.admin, rumpf: { punkt: "gibtsnicht", stand: "geht" } })).code === 400, "unbekannter Punkt wird abgewiesen");
|
||
ok((await roh("/workspace/api/reaktion/probeabend", { method: "PUT", keks: k.admin, rumpf: { punkt: "clip", stand: "super" } })).code === 400, "unbekannter Stand wird abgewiesen");
|
||
ok(await rohHaus("workspace.dogfather-universe.com", "/workspace/api/reaktion/probeabend", k.admin) === 404, "im Agentur-Haus gibt es den Weg nicht (404)");
|
||
|
||
/* ---------- Seite ---------- */
|
||
const konsole = [];
|
||
const kx = await browser.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: true, permissions: ["camera", "microphone"] });
|
||
await kx.addCookies(k.admin.split("; ").filter(Boolean).map((z) => { const [n, ...r] = z.split("="); return { name: n, value: r.join("="), domain: CREW, path: "/" }; }));
|
||
const s = await kx.newPage();
|
||
s.on("pageerror", (f) => konsole.push(String(f?.message || f)));
|
||
await s.addInitScript(() => {
|
||
window.__freistellenMindestrate = 0;
|
||
const g = { vendorId: 0x0fd9, productId: 0x0080, productName: "Stream Deck MK.2", opened: false, h: [], async open() { this.opened = true; }, addEventListener(a, f) { if (a === "inputreport") this.h.push(f); }, removeEventListener(a, f) { this.h = this.h.filter((x) => x !== f); } };
|
||
window.__sdDruck = (t) => { const b = new Uint8Array(18); b[1] = 15; if (t >= 0) b[3 + t] = 1; for (const f of g.h) f({ reportId: 1, device: g, data: new DataView(b.buffer) }); };
|
||
Object.defineProperty(navigator, "hid", { configurable: true, value: { requestDevice: async () => [g], getDevices: async () => [g] } });
|
||
});
|
||
await s.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
|
||
await s.waitForSelector("body[data-stand]", { timeout: 20000 });
|
||
await s.waitForFunction(() => window.RegieLaden?.fertig?.() && document.getElementById("pa"), null, { timeout: 20000 }).catch(() => {});
|
||
await s.evaluate(() => { document.getElementById("pa").open = true; document.getElementById("pa").scrollIntoView({ block: "start" }); });
|
||
const leer = await s.evaluate(() => ({ titel: document.getElementById("pa-titel")?.textContent, punkte: document.querySelectorAll("#pa-liste .pa-punkt").length, offen: document.querySelectorAll('#pa-liste .pa-punkt[data-stand="offen"]').length, neben: document.getElementById("pa").previousElementSibling?.id }));
|
||
ok(leer.punkte === 6 && leer.offen === 6 && /0 von 6/.test(leer.titel) && leer.neben === "werkstatt-startklar", `sechs Punkte, alle „noch offen“, neben „Startklar“ (${JSON.stringify(leer)})`);
|
||
const stand = (id) => s.evaluate((i) => document.querySelector(`.pa-punkt[data-punkt="${i}"]`)?.dataset.stand, id);
|
||
/* Clip ohne Dienst: ehrlich „geht nicht“ mit Grund */
|
||
await s.click('[data-messen="clip"]');
|
||
await warte(800);
|
||
ok(await stand("clip") === "geht_nicht" && /nicht verbunden/.test(await s.evaluate(() => document.querySelector('.pa-punkt[data-punkt="clip"] .pa-wert')?.textContent || "")), "Clip ohne Untertitel-Dienst: „geht nicht“, mit Grund");
|
||
/* Stream Deck mit Attrappe */
|
||
await s.click('[data-messen="streamdeck"]');
|
||
await warte(600);
|
||
await s.evaluate(() => { window.__sdDruck(4); window.__sdDruck(-1); });
|
||
await warte(800);
|
||
ok(await stand("streamdeck") === "geht", "Stream Deck: verbunden und eine Taste empfangen → „geht“");
|
||
/* Fragen */
|
||
await s.click('.pa-punkt[data-punkt="lautheit"] [data-antwort="geht"]');
|
||
await s.click('.pa-punkt[data-punkt="meinmix"] [data-antwort="geht_nicht"]');
|
||
await warte(600);
|
||
ok(await stand("lautheit") === "geht" && await stand("meinmix") === "geht_nicht", "die zwei Fragen nehmen Ja und Nein");
|
||
/* Saal-Fenster: im Prüfbrowser öffnet es; gedrückt, während der Saal vorn ist → „knapp“ */
|
||
const neu = kx.waitForEvent("page", { timeout: 5000 }).catch(() => null);
|
||
await s.click('[data-messen="fenster"]');
|
||
const pip = await neu;
|
||
if (pip) { await pip.waitForSelector("button", { timeout: 5000 }); await pip.click("button"); }
|
||
await warte(800);
|
||
const fs = await stand("fenster");
|
||
ok(pip ? fs === "knapp" : fs === "geht_nicht", `Saal-Fenster: ${pip ? "gedrückt, aber der Saal war vorn → „knapp“ (im Spiel noch einmal)" : "kein Bild-im-Bild → geht nicht"} (${fs})`);
|
||
/* Freistellen: 30 s messen, danach die alte Wahl zurück */
|
||
await s.evaluate(() => document.getElementById("reiter-ton")?.click());
|
||
await warte(400);
|
||
const vorher = await s.evaluate(() => window.Freistellen?.art());
|
||
/* Die Probe sitzt in der Tafel „Sendung“, Freistellen im Ton-Bereich – beide gibt es gleichzeitig. */
|
||
await s.evaluate(() => document.querySelector('[data-messen="freistellen"]').click());
|
||
await warte(33_000);
|
||
const fz = await s.evaluate(() => ({ stand: document.querySelector('.pa-punkt[data-punkt="freistellen"]')?.dataset.stand, wert: document.querySelector('.pa-punkt[data-punkt="freistellen"] .pa-wert')?.textContent, art: window.Freistellen?.art() }));
|
||
ok(fz.stand !== "offen" && /Bilder\/s|nicht/.test(fz.wert || "") && fz.art === vorher, `Freistellen gemessen und danach zurückgestellt (${JSON.stringify(fz)})`);
|
||
await s.evaluate(() => document.getElementById("reiter-sendung")?.click());
|
||
await warte(400);
|
||
if (BILDER) await s.locator("#pa").screenshot({ path: `${BILDER}/probeabend-1440.png` });
|
||
/* Bleibt gespeichert */
|
||
await s.reload({ waitUntil: "domcontentloaded" });
|
||
await s.waitForFunction(() => document.querySelectorAll('#pa-liste .pa-punkt:not([data-stand="offen"])').length >= 5, null, { timeout: 20000 }).catch(() => {});
|
||
const nachher = await s.evaluate(() => ({ titel: document.getElementById("pa-titel")?.textContent, offen: document.querySelectorAll('#pa-liste .pa-punkt[data-stand="offen"]').length }));
|
||
ok(nachher.offen === 0 && /6 von 6/.test(nachher.titel), `nach dem Neuladen steht alles noch da (${JSON.stringify(nachher)})`);
|
||
ok(!konsole.length, `keine Fehler (${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);
|