Files
dogfather-universe/server/pruef-streamdeck-blick.mjs
T

265 lines
14 KiB
JavaScript
Raw 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.
/* =====================================================================
STREAM DECK (05.11.2026, Neuplan E9)
Tastenbericht je Modell, Lernmodus, Auslösen der Saal-Taste, eine Taste =
eine Funktion über Pads und Stream Deck. Das Gerät ist eine Attrappe
(WebHID ohne Gerät gibt es im Prüfbrowser nicht).
DREI AUSGÄNGE: 0 in Ordnung · 1 Befund · 3 konnte nicht nachsehen.
Bilder: SD_BILDER=<ordner> node server/pruef-streamdeck-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-streamdeck-"));
process.env.WORKSPACE_DB = join(ordner, "workspace.db");
const PORT = await eigenerPort(import.meta);
const HTTPS_PORT = await eigenerPort(import.meta, "pruef-streamdeck-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-streamdeck-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.SD_BILDER || "";
const warte = (ms) => new Promise((r) => setTimeout(r, ms));
const kontext = await browser.newContext({ viewport: { width: 1440, height: 900 }, ignoreHTTPSErrors: true });
await kontext.addCookies(k.admin.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" && !/compute-pressure|youtube|ytimg|googlevideo|livekit|ERR_|net::|NotAllowed|NotFound/i.test(m.text())) konsole.push(m.text()); });
/* Ein Stream Deck MK.2 als Attrappe: WebHID gibt es im Prüfbrowser ohne Gerät
nicht. Die Berichte haben die Form, die das Gerät schickt (Bericht 1,
Tasten ab Byte 3). */
await seite.addInitScript(() => {
const geraet = { 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.__sd = geraet;
window.__sdDruck = (taste) => {
const bytes = new Uint8Array(3 + 15); bytes[0] = 0; bytes[1] = 15; if (taste >= 0) bytes[3 + taste] = 1;
for (const f of geraet.h) f({ reportId: 1, device: geraet, data: new DataView(bytes.buffer) });
};
Object.defineProperty(navigator, "hid", { configurable: true, value: { requestDevice: async () => [geraet], getDevices: async () => [geraet] } });
window.__tasten = [];
document.addEventListener("keydown", (e) => { if (!e.isTrusted) window.__tasten.push(e.key); }, true);
});
await seite.goto(`${BASIS}/workspace/reaktion.html`, { waitUntil: "domcontentloaded" });
await seite.waitForSelector("body[data-stand]", { timeout: 20000 });
await seite.waitForTimeout(2000);
/* Die Zuordnung der Tasten an sich */
const sd = await seite.evaluate(() => {
const P = window.Pads;
const mk2 = P.sdDeuten(0x0080, Uint8Array.from([0, 15, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), []);
const orig = P.sdDeuten(0x0060, Uint8Array.from([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), []);
const halten = P.sdDeuten(0x0080, Uint8Array.from([0, 15, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), mk2.jetzt);
return { mk2: mk2.neu, orig: orig.neu, halten: halten.neu, gueltig: Object.keys(P.pruefen({ zuordnung: { "sd:1:4": "moment", "sd:1:999": "band", "sd:2:1": "kamera" } })) };
});
ok(JSON.stringify(sd.mk2) === "[2]", `MK.2: Byte 3+2 gedrückt = Taste 3 (${JSON.stringify(sd.mk2)})`);
ok(JSON.stringify(sd.orig) === "[4]", `Original: die erste Meldung ist die rechte Taste der Reihe (${JSON.stringify(sd.orig)})`);
ok(sd.halten.length === 0, "gehalten zählt nicht doppelt – nur das Drücken löst aus");
ok(JSON.stringify(sd.gueltig) === JSON.stringify(["sd:1:4", "sd:2:1"]), `die gespeicherte Zuordnung wird geprüft (unmögliche Taste verworfen): ${JSON.stringify(sd.gueltig)}`);
await seite.evaluate(() => window.Pads.oeffnen());
await warte(300);
await seite.click("#pads-streamdeck");
await warte(400);
const st = await seite.evaluate(() => document.getElementById("pads-stand").textContent);
ok(/Verbunden: Stream Deck MK\.2/.test(st), `„Mit Stream Deck verbinden“ verbindet (${st})`);
await seite.click('[data-lernen="moment"]');
await warte(200);
await seite.evaluate(() => { window.__sdDruck(2); window.__sdDruck(-1); });
await warte(300);
const z1 = await seite.evaluate(() => window.Pads.zuordnung());
ok(z1["sd:1:2"] === "moment", `Lernmodus: Taste 3 am Stream Deck → „Moment merken“ (${JSON.stringify(z1)})`);
await seite.evaluate(() => { window.__tasten = []; document.getElementById("pads").close(); window.__sdDruck(2); window.__sdDruck(-1); });
await warte(300);
ok((await seite.evaluate(() => window.__tasten)).includes("h"), "danach löst Taste 3 genau die Saal-Taste H aus");
/* Eine Taste, eine Funktion: dieselbe Taste für „Band“ nimmt sie dem Moment. */
await seite.evaluate(() => window.Pads.oeffnen());
await seite.click('[data-lernen="band"]');
await seite.evaluate(() => { window.__sdDruck(2); window.__sdDruck(-1); });
await warte(300);
const z2 = await seite.evaluate(() => window.Pads.zuordnung());
ok(z2["sd:1:2"] === "band" && !Object.values(z2).includes("moment"), `eine Taste, eine Funktion: Taste 3 ist jetzt nur noch „Band“ (${JSON.stringify(z2)})`);
const sagt = await seite.evaluate(() => document.getElementById("pads-sagt").textContent);
ok(/Stream Deck · Taste 3 war „Moment merken“/.test(sagt), `und das wird gesagt („${sagt}“)`);
if (BILDER) await seite.locator("#pads").screenshot({ path: `${BILDER}/streamdeck-1440.png` });
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);