Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f466df2c5c | ||
|
|
25da870601 | ||
|
|
fb24d171ae | ||
|
|
5a9d7735d4 | ||
|
|
4042fe6a64 | ||
|
|
7590be66a5 | ||
|
|
08e8875cb5 | ||
|
|
7a49e66c37 |
No files matched your search
@@ -1,3 +1,20 @@
|
|||||||
# Relative paths are resolved from the project directory.
|
# Relative paths are resolved from the project directory.
|
||||||
SENDEWERK_DB_PATH=.data/sendewerk.sqlite
|
SENDEWERK_DB_PATH=.data/sendewerk.sqlite
|
||||||
SENDEWERK_UPLOAD_DIR=.data/uploads
|
SENDEWERK_UPLOAD_DIR=.data/uploads
|
||||||
|
SENDEWERK_MAIL_OUTBOX_DIR=.data/mail-outbox
|
||||||
|
BODY_SIZE_LIMIT=6M
|
||||||
|
|
||||||
|
# Generate this locally and insert it here as described in README.md. Never commit .env.
|
||||||
|
SENDEWERK_SETUP_TOKEN=
|
||||||
|
SENDEWERK_APP_ORIGIN=http://localhost:5173
|
||||||
|
|
||||||
|
# "local" writes messages to the outbox and never contacts a mail server.
|
||||||
|
SENDEWERK_MAIL_TRANSPORT=local
|
||||||
|
SENDEWERK_MAIL_FROM=Sendewerk <sendewerk@localhost>
|
||||||
|
|
||||||
|
# Required only when SENDEWERK_MAIL_TRANSPORT=smtp is explicitly selected.
|
||||||
|
SENDEWERK_SMTP_HOST=
|
||||||
|
SENDEWERK_SMTP_PORT=587
|
||||||
|
SENDEWERK_SMTP_SECURE=false
|
||||||
|
SENDEWERK_SMTP_USER=
|
||||||
|
SENDEWERK_SMTP_PASSWORD=
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
"title": "Sendewerk",
|
"title": "Sendewerk",
|
||||||
"description": "Redaktionelle Planung und Durchführung von heinzlive-Sendungen.",
|
"description": "Redaktionelle Planung und Durchführung von heinzlive-Sendungen.",
|
||||||
"tagline": "Vom Fundstück bis zur Livesendung",
|
"tagline": "Vom Fundstück bis zur Livesendung",
|
||||||
"version": "0.1.0",
|
"version": "0.5.0",
|
||||||
"healthCheckPath": "/healthz",
|
"healthCheckPath": "/healthz",
|
||||||
"httpPort": 3000,
|
"httpPort": 3000,
|
||||||
"addons": {
|
"addons": {
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
Sendewerk ist die redaktionelle Webanwendung für den Weg vom vorbereiteten
|
Sendewerk ist die redaktionelle Webanwendung für den Weg vom vorbereiteten
|
||||||
Inhalt bis zur moderierten und archivierten Sendung. Der aktuelle Stand umfasst
|
Inhalt bis zur moderierten und archivierten Sendung. Der aktuelle Stand umfasst
|
||||||
ausschließlich Etappe 1: technisches Grundgerüst, persistente Beispieldaten
|
Etappe 1 bis 5: technisches Grundgerüst, Anmeldung und Rollen, einen
|
||||||
und gekennzeichnete Gestaltungsvorschauen. Anmeldung, Bearbeitung und echte
|
persistenten Fundus, den Sendungsbaukasten sowie Live-Steuerung und eine
|
||||||
Live-Steuerung folgen in späteren Etappen.
|
abgesicherte Präsentationsausgabe. Abschluss und Archivierung folgen in Etappe 6.
|
||||||
|
|
||||||
## Voraussetzungen
|
## Voraussetzungen
|
||||||
|
|
||||||
@@ -20,6 +20,9 @@ nicht erforderlich.
|
|||||||
```sh
|
```sh
|
||||||
npm ci
|
npm ci
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
|
SETUP_TOKEN="$(openssl rand -hex 32)"
|
||||||
|
sed -i "s/^SENDEWERK_SETUP_TOKEN=.*/SENDEWERK_SETUP_TOKEN=$SETUP_TOKEN/" .env
|
||||||
|
printf 'Betreiber-Setup-Token: %s\n' "$SETUP_TOKEN"
|
||||||
npm run setup
|
npm run setup
|
||||||
npm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
@@ -29,18 +32,125 @@ erstellt die konfigurierten Verzeichnisse, führt ausstehende Migrationen aus
|
|||||||
und lädt den reproduzierbaren Beispieldatensatz. Der Seed darf beliebig oft
|
und lädt den reproduzierbaren Beispieldatensatz. Der Seed darf beliebig oft
|
||||||
ausgeführt werden und ersetzt nur die von ihm verwalteten Beispieldaten.
|
ausgeführt werden und ersetzt nur die von ihm verwalteten Beispieldaten.
|
||||||
|
|
||||||
|
Beim ersten Aufruf verlangt `/setup` den ausgegebenen Wert aus
|
||||||
|
`SENDEWERK_SETUP_TOKEN` und legt genau einen Barkeeper an. Der Befehl schreibt
|
||||||
|
den Wert in die nicht versionierte `.env`, damit auch spätere lokale Starts
|
||||||
|
dieselbe Konfiguration verwenden. Nach erfolgreicher Einrichtung ist `/setup`
|
||||||
|
dauerhaft geschlossen und der Token kann aus `.env` entfernt werden. Der Seed
|
||||||
|
enthält bewusst kein Konto und kein Standardpasswort.
|
||||||
|
|
||||||
## Konfiguration
|
## Konfiguration
|
||||||
|
|
||||||
| Variable | Vorgabe | Bedeutung |
|
| Variable | Vorgabe | Bedeutung |
|
||||||
| ---------------------- | ------------------------ | ----------------------------------- |
|
| --------------------------- | ------------------------ | ---------------------------------------------------- |
|
||||||
| `SENDEWERK_DB_PATH` | `.data/sendewerk.sqlite` | Pfad zur persistenten SQLite-Datei |
|
| `SENDEWERK_DB_PATH` | `.data/sendewerk.sqlite` | Pfad zur persistenten SQLite-Datei |
|
||||||
| `SENDEWERK_UPLOAD_DIR` | `.data/uploads` | Persistentes Upload-Verzeichnis |
|
| `SENDEWERK_UPLOAD_DIR` | `.data/uploads` | Persistentes Upload-Verzeichnis |
|
||||||
| `HOST` | adapterabhängig | Bind-Adresse des Produktionsservers |
|
| `SENDEWERK_MAIL_OUTBOX_DIR` | `.data/mail-outbox` | Lokale, nicht öffentlich ausgelieferte Testmail |
|
||||||
| `PORT` | `3000` | Port des Produktionsservers |
|
| `BODY_SIZE_LIMIT` | `6M` | Requestlimit für private Bild-Uploads bis 5 MB |
|
||||||
|
| `SENDEWERK_SETUP_TOKEN` | keine | einmaliges Betreibergeheimnis, mindestens 32 Zeichen |
|
||||||
|
| `SENDEWERK_APP_ORIGIN` | `http://localhost:5173` | feste Origin für Links und Cookie-Sicherheit |
|
||||||
|
| `SENDEWERK_MAIL_TRANSPORT` | `local` | `local` oder ausdrücklich `smtp` |
|
||||||
|
| `SENDEWERK_MAIL_FROM` | lokaler Absender | Absender; bei SMTP verpflichtend |
|
||||||
|
| `SENDEWERK_SMTP_HOST` | keine | SMTP-Server, nur im SMTP-Modus |
|
||||||
|
| `SENDEWERK_SMTP_PORT` | `587` | SMTP-Port |
|
||||||
|
| `SENDEWERK_SMTP_SECURE` | `false` | `true` für implizites TLS, üblicherweise Port 465 |
|
||||||
|
| `SENDEWERK_SMTP_USER` | keine | optionaler SMTP-Benutzer |
|
||||||
|
| `SENDEWERK_SMTP_PASSWORD` | keine | optionales SMTP-Passwort |
|
||||||
|
| `HOST` | adapterabhängig | Bind-Adresse des Produktionsservers |
|
||||||
|
| `PORT` | `3000` | Port des Produktionsservers |
|
||||||
|
|
||||||
Relative Sendewerk-Pfade werden vom Projektverzeichnis aus aufgelöst. In
|
Relative Sendewerk-Pfade werden vom Projektverzeichnis aus aufgelöst. In
|
||||||
Cloudron liegen Datenbank und Uploads unter `/app/data`.
|
Cloudron liegen Datenbank und Uploads unter `/app/data`.
|
||||||
|
|
||||||
|
Der Vorgabemodus `local` baut keine Netzwerkverbindung auf. Einladungen und
|
||||||
|
Passwort-Resets landen als JSON-Dateien in `.data/mail-outbox`; die enthaltenen
|
||||||
|
Links sind Geheimnisse und dürfen nicht veröffentlicht werden. Echter Versand
|
||||||
|
findet nur statt, wenn `SENDEWERK_MAIL_TRANSPORT=smtp` und die SMTP-Werte
|
||||||
|
explizit gesetzt sind.
|
||||||
|
|
||||||
|
## Inhalte und private Bilder
|
||||||
|
|
||||||
|
Neue Gedanken oder Links lassen sich im Eingang schnell erfassen. Im Fundus
|
||||||
|
stehen leere Pieces sowie Vorlagen für Gespräch, Reaction/Fundstück und
|
||||||
|
Interaktion bereit. Der Editor speichert Änderungen nach kurzer Pause
|
||||||
|
automatisch; ein sichtbarer Status meldet Erfolg, Fehler oder eine parallele
|
||||||
|
Änderung. In diesem Fall muss die Seite neu geladen werden, bevor erneut
|
||||||
|
gespeichert wird.
|
||||||
|
|
||||||
|
Bereits gesendete Pieces und Pieces mit einer Einplanung in einer noch nicht
|
||||||
|
abgeschlossenen Sendung sind standardmäßig ausgeblendet. Als gesendet gilt nur
|
||||||
|
eine erledigte Verwendung in einer abgeschlossenen Sendung; übersprungene oder
|
||||||
|
reservierte Inhalte gelten nicht als gesendet. Über **Auch verwendete Inhalte
|
||||||
|
zeigen** und **Auch eingeplante Inhalte zeigen** lassen sich beide Gruppen
|
||||||
|
unabhängig einblenden. Dann erscheinen auch Datum, Sendung und die aufklappbare
|
||||||
|
Verwendungshistorie.
|
||||||
|
|
||||||
|
Markdown ist in Einleitung, Recherche, Moderation, Überleitung und Präsentation
|
||||||
|
möglich. Die Ausgabe wird serverseitig auf eine begrenzte Auswahl sicherer
|
||||||
|
Elemente und Links reduziert. Bilder dürfen höchstens 5 MB groß sein und müssen
|
||||||
|
als JPEG, PNG, WebP oder GIF erkannt werden. Sie liegen im konfigurierten
|
||||||
|
Uploadverzeichnis und sind nur über eine angemeldete Route erreichbar.
|
||||||
|
|
||||||
|
Für die Präsentation kann ein Piece alternativ genau eine seiner vorhandenen
|
||||||
|
Quellen als Linkkarte oder Video verwenden. Linktitel, Anreißer und Bildadresse
|
||||||
|
lassen sich manuell korrigieren. **Vorschau laden** ruft Metadaten ausdrücklich
|
||||||
|
neu ab; manuell geänderte Felder werden dabei nicht überschrieben. Die
|
||||||
|
**Präsentation testen**-Ansicht öffnet den aktuellen Piece-Inhalt isoliert und
|
||||||
|
verändert weder eine Sendung noch deren laufende Ausgabe.
|
||||||
|
|
||||||
|
## Sendungen planen
|
||||||
|
|
||||||
|
Unter **Sendungen** lässt sich ein neuer Stream leer, mit dem Standardablauf
|
||||||
|
oder als Spieleabend anlegen. Abschnitte sind frei benennbar und können eine
|
||||||
|
explizite Dauer erhalten; andernfalls ergibt sich ihre Dauer aus den
|
||||||
|
eingeplanten Pieces. Die Reservebank zählt nie zur Planzeit.
|
||||||
|
|
||||||
|
Der sendefertige Fundus steht neben dem Ablauf. Pieces können mehrfach
|
||||||
|
eingeplant und je Verwendung mit eigenem Titel, eigener Dauer und eigenen
|
||||||
|
Redaktionstexten bearbeitet werden, ohne das Original zu verändern. Das
|
||||||
|
Stift-Symbol öffnet dafür einen auch mobil scrollbaren Editor-Dialog. **Aus
|
||||||
|
Fundus aktualisieren** übernimmt auf Wunsch Titel, Dauer und Redaktionstexte des
|
||||||
|
aktuellen Originals; eigene Notizen, Live-Status und gemessene Zeiten bleiben
|
||||||
|
erhalten. Abschnitte und Verwendungen lassen sich per Drag-and-drop sowie
|
||||||
|
gleichwertig mit sichtbaren Schaltflächen und Auswahlfeldern verschieben.
|
||||||
|
Twitch-Titel und Ankündigung sind kopierbar. Gleichzeitige Änderungen werden
|
||||||
|
über die Revision der gesamten Sendung erkannt und nicht still überschrieben.
|
||||||
|
|
||||||
|
Die Quellspalte blendet gesendete und bereits in derselben Sendung eingeplante
|
||||||
|
Originale zunächst aus; beide Gruppen lassen sich unabhängig wieder anzeigen.
|
||||||
|
Eine konkrete Einplanung kann direkt hinter sich dupliziert werden. Dabei
|
||||||
|
bleiben ihre angepassten Texte und ihre Dauer erhalten, während Live-Status und
|
||||||
|
gemessene Zeiten neu beginnen. **Piece duplizieren** im Fundus erzeugt dagegen
|
||||||
|
weiterhin einen eigenständigen Fundusinhalt.
|
||||||
|
|
||||||
|
## Live moderieren und präsentieren
|
||||||
|
|
||||||
|
Die Live-Steuerung öffnet sich aus einer geplanten Sendung. Sie zeigt
|
||||||
|
Einleitung, Moderationsstichpunkte und Überleitung in einstellbarer
|
||||||
|
Prompter-Schrift; die private Recherche bleibt standardmäßig geschlossen.
|
||||||
|
Zeiten und Ablaufleiste können ausgeblendet werden. Schriftgröße, Sichtbarkeit
|
||||||
|
und Leseposition bleiben im Browser erhalten.
|
||||||
|
|
||||||
|
Start, Erledigen, Überspringen und Zurück werden persistent mit tatsächlichen
|
||||||
|
Zeitintervallen gespeichert. Wiederholte Befehle erzeugen keine doppelte
|
||||||
|
Zeitbuchung. Offene Pieces und die Reserve lassen sich während der Sendung
|
||||||
|
sortieren beziehungsweise als nächster Beitrag einfügen.
|
||||||
|
|
||||||
|
Das separate Präsentationsfenster unter `/heinzlive/...` verwendet einen langen,
|
||||||
|
widerrufbaren Zufallstoken. Es ändert sich ausschließlich durch die Aktion
|
||||||
|
**Präsentieren** und erhält nur den bei der Einplanung gespeicherten Text-, Link-
|
||||||
|
oder Video-Snapshot. YouTube- und TikTok-Adressen werden auf validierte IDs
|
||||||
|
reduziert und ohne Autoplay in offiziellen Player-Iframes dargestellt. Andere
|
||||||
|
oder unvollständige Videoquellen erscheinen als Linkkarte. Recherche,
|
||||||
|
Moderationsnotizen, eigene Notizen, Kontodaten und interne Dateipfade werden
|
||||||
|
weder im HTML noch im JSON-Zustand ausgeliefert. Der Token ist ein
|
||||||
|
Zugangsgeheimnis und darf nicht weitergegeben oder protokolliert werden.
|
||||||
|
|
||||||
|
Metadaten und externe Vorschaubilder werden ausschließlich serverseitig mit
|
||||||
|
DNS-, Redirect-, Zeit- und Größenlimits abgerufen. Private und lokale
|
||||||
|
Netzwerkziele sind gesperrt. Eingebettetes HTML oder Skripte einer Quellseite
|
||||||
|
werden nicht übernommen.
|
||||||
|
|
||||||
## Befehle
|
## Befehle
|
||||||
|
|
||||||
| Befehl | Zweck |
|
| Befehl | Zweck |
|
||||||
@@ -48,7 +158,7 @@ Cloudron liegen Datenbank und Uploads unter `/app/data`.
|
|||||||
| `npm run setup` | Verzeichnisse, Migrationen und Seed für lokale Entwicklung |
|
| `npm run setup` | Verzeichnisse, Migrationen und Seed für lokale Entwicklung |
|
||||||
| `npm run db:migrate` | Ausstehende Migrationen atomar ausführen |
|
| `npm run db:migrate` | Ausstehende Migrationen atomar ausführen |
|
||||||
| `npm run db:seed` | Reproduzierbare Beispieldaten laden |
|
| `npm run db:seed` | Reproduzierbare Beispieldaten laden |
|
||||||
| `npm run dev` | Entwicklungsserver starten |
|
| `npm run dev` | Migrationen ausführen und Entwicklungsserver starten |
|
||||||
| `npm run check` | Svelte- und TypeScript-Prüfung |
|
| `npm run check` | Svelte- und TypeScript-Prüfung |
|
||||||
| `npm run lint` | Formatierung und ESLint prüfen |
|
| `npm run lint` | Formatierung und ESLint prüfen |
|
||||||
| `npm test` | Verhaltenstests mit temporärer, getrennter Datenbank |
|
| `npm test` | Verhaltenstests mit temporärer, getrennter Datenbank |
|
||||||
@@ -61,6 +171,7 @@ Cloudron liegen Datenbank und Uploads unter `/app/data`.
|
|||||||
```sh
|
```sh
|
||||||
npm ci
|
npm ci
|
||||||
npm run setup
|
npm run setup
|
||||||
|
export SENDEWERK_APP_ORIGIN=http://localhost:3000
|
||||||
npm run build
|
npm run build
|
||||||
HOST=127.0.0.1 PORT=3000 npm start
|
HOST=127.0.0.1 PORT=3000 npm start
|
||||||
```
|
```
|
||||||
@@ -68,6 +179,12 @@ HOST=127.0.0.1 PORT=3000 npm start
|
|||||||
Der Healthcheck liegt unter <http://localhost:3000/healthz> und prüft auch den
|
Der Healthcheck liegt unter <http://localhost:3000/healthz> und prüft auch den
|
||||||
Datenbankzugriff.
|
Datenbankzugriff.
|
||||||
|
|
||||||
|
Für lokales HTTP wird das Sitzungscookie gezielt ohne `Secure` gesetzt, bleibt
|
||||||
|
aber `HttpOnly` und `SameSite=Lax`. Bei einer `https:`-Origin ist `Secure`
|
||||||
|
automatisch aktiv. Die Build-Origin muss beim lokalen Produktionsbuild mit der
|
||||||
|
später verwendeten Browser-Origin übereinstimmen; SvelteKits Origin-Prüfung
|
||||||
|
bleibt aktiv.
|
||||||
|
|
||||||
Vor der ersten Browserprüfung wird der Testbrowser einmalig installiert:
|
Vor der ersten Browserprüfung wird der Testbrowser einmalig installiert:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -82,9 +199,17 @@ Das frühe Cloudron-Paket besteht aus `Dockerfile`, `CloudronManifest.json` und
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker build -t sendewerk:local .
|
docker build -t sendewerk:local .
|
||||||
docker run --rm -p 3000:3000 -v sendewerk-data:/app/data sendewerk:local
|
docker run --rm -p 3000:3000 \
|
||||||
|
-e SENDEWERK_APP_ORIGIN=http://localhost:3000 \
|
||||||
|
-e SENDEWERK_SETUP_TOKEN="$(openssl rand -hex 32)" \
|
||||||
|
-v sendewerk-data:/app/data sendewerk:local
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Auf Cloudron muss das Betreiber-Setup-Token vor dem ersten Browseraufruf als
|
||||||
|
Umgebungsvariable gesetzt werden. `CLOUDRON_APP_ORIGIN` liefert dort die feste
|
||||||
|
HTTPS-Origin. SMTP-Zugangsdaten werden ebenfalls ausschließlich als
|
||||||
|
Laufzeitvariablen gesetzt, nicht in Manifest oder Image geschrieben.
|
||||||
|
|
||||||
Das ersetzt keinen Test auf einem echten Cloudron. Insbesondere Addon-Backup,
|
Das ersetzt keinen Test auf einem echten Cloudron. Insbesondere Addon-Backup,
|
||||||
Restore, Proxy-Origin und das read-only Laufzeitdateisystem können erst dort
|
Restore, Proxy-Origin und das read-only Laufzeitdateisystem können erst dort
|
||||||
abschließend geprüft werden.
|
abschließend geprüft werden.
|
||||||
@@ -101,5 +226,7 @@ Medien und redaktionellen Inhalten werden dadurch nicht verändert.
|
|||||||
|
|
||||||
Die direkten Laufzeit- und Werkzeugabhängigkeiten verwenden MIT- oder
|
Die direkten Laufzeit- und Werkzeugabhängigkeiten verwenden MIT- oder
|
||||||
Apache-2.0-Lizenzen: Svelte/SvelteKit, Vite, Vitest, ESLint und
|
Apache-2.0-Lizenzen: Svelte/SvelteKit, Vite, Vitest, ESLint und
|
||||||
`better-sqlite3` sind MIT-lizenziert; TypeScript und Playwright stehen unter
|
`better-sqlite3`, `@node-rs/argon2`, Marked, sanitize-html, file-type und
|
||||||
Apache-2.0. Die Lockdatei fixiert den tatsächlich installierten Baum.
|
Metascraper sind MIT-lizenziert; Nodemailer verwendet MIT-0, TypeScript und
|
||||||
|
Playwright stehen unter Apache-2.0. Die Lockdatei fixiert den tatsächlich
|
||||||
|
installierten Baum.
|
||||||
+192
-13
@@ -2,18 +2,19 @@
|
|||||||
|
|
||||||
## Etappe 1
|
## Etappe 1
|
||||||
|
|
||||||
| Kriterium | Nachweis | Stand |
|
| Kriterium | Nachweis | Stand |
|
||||||
| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
||||||
| Frischer Checkout startet ohne Cloudron | `npm ci` erfolgreich; README-Setup und lokaler Produktionsstart ausgeführt | erfüllt am 21.10.2026 |
|
| Frischer Checkout startet ohne Cloudron | `npm ci` erfolgreich; README-Setup und lokaler Produktionsstart ausgeführt | erfüllt am 21.10.2026 |
|
||||||
| Typprüfung und Build erfolgreich | `npm run check`, `npm run build` | erfüllt am 21.10.2026 |
|
| Typprüfung und Build erfolgreich | `npm run check`, `npm run build` | erfüllt am 21.10.2026 |
|
||||||
| Theme bleibt nach Neuladen erhalten | Playwright: System auf Hell wechseln, Reload, DOM und Schalterzustand prüfen | erfüllt am 21.10.2026 |
|
| Theme bleibt nach Neuladen erhalten | Playwright: System auf Hell wechseln, Reload, DOM und Schalterzustand prüfen | erfüllt am 21.10.2026 |
|
||||||
| Testdaten überleben Neustart | Gebauten Server zweimal gegen `.data/sendewerk.sqlite` gestartet; Fundusdaten und `/healthz` jeweils vorhanden | erfüllt am 21.10.2026 |
|
| Testdaten überleben Neustart | Gebauten Server zweimal gegen `.data/sendewerk.sqlite` gestartet; Fundusdaten und `/healthz` jeweils vorhanden | erfüllt am 21.10.2026 |
|
||||||
| Migration wiederholt ausführbar | lokal mehrfach ausgeführt; Verhaltenstest führt Migration zweimal in temporärer DB aus | erfüllt am 21.10.2026 |
|
| Migration wiederholt ausführbar | lokal mehrfach ausgeführt; Verhaltenstest führt Migration zweimal in temporärer DB aus | erfüllt am 21.10.2026 |
|
||||||
| Seed reproduzierbar | lokal und im Verhaltenstest zweimal ausgeführt; danach 4 Pieces, 1 Sendung und 3 Verwendungen | erfüllt am 21.10.2026 |
|
| Seed reproduzierbar | lokal und im Verhaltenstest zweimal ausgeführt; danach 4 Pieces, 1 Sendung und 3 Verwendungen | erfüllt am 21.10.2026 |
|
||||||
| Tests verwenden getrennte Daten | Vitest und Playwright erzeugen je eigene Datenbank im Betriebssystem-Tempdir | erfüllt am 21.10.2026 |
|
| Tests verwenden getrennte Daten | Vitest und Playwright erzeugen je eigene Datenbank im Betriebssystem-Tempdir | erfüllt am 21.10.2026 |
|
||||||
| Desktop und Smartphone ohne horizontales Scrollen | 4 Playwright-Abläufe; 1440x1000, 1280x900 und 390x844; Screenshots visuell kontrolliert | erfüllt am 21.10.2026 |
|
| Desktop und Smartphone ohne horizontales Scrollen | 8 Playwright-Abläufe bei 390, 768, 960, 1280 und 1440 Pixeln; Screenshots visuell kontrolliert | erfüllt am 21.10.2026 |
|
||||||
| Cloudron-Pfade und Healthcheck vorbereitet | Manifestpfad `/app/data/sendewerk.sqlite`, `/healthz`, `start.sh`; JSON-Kernfelder und Bash-Syntax geprüft | vorbereitet; Container offen |
|
| Kompakte Arbeitsoberfläche in beiden Farbmodi | 390, 768 und 1440 Pixel jeweils in Light/Dark; einspaltige Mobilkarten, lange Titel, Metadatenumbrüche und Leerzustände | erfüllt am 21.10.2026 |
|
||||||
| Echte Cloudron-Prüfung | Installation, Backup/Restore, Proxy und read-only Laufzeit | offen, kein Serverzugang |
|
| Cloudron-Pfade und Healthcheck vorbereitet | Manifestpfad `/app/data/sendewerk.sqlite`, `/healthz`, `start.sh`; JSON-Kernfelder und Bash-Syntax geprüft | vorbereitet; Container offen |
|
||||||
|
| Echte Cloudron-Prüfung | Installation, Backup/Restore, Proxy und read-only Laufzeit | offen, kein Serverzugang |
|
||||||
|
|
||||||
## Ausgeführte Prüfungen
|
## Ausgeführte Prüfungen
|
||||||
|
|
||||||
@@ -23,7 +24,9 @@
|
|||||||
- `npm run lint`: erfolgreich
|
- `npm run lint`: erfolgreich
|
||||||
- `npm run check`: 0 Fehler und 0 Warnungen
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
- `npm run test:e2e`: 4 von 4 Browsertests erfolgreich
|
- `npm run test:e2e`: 8 von 8 Browsertests erfolgreich; 390, 768 und 1440 Pixel
|
||||||
|
jeweils in Light- und Darkmode sowie Tastaturbedienung, feste Navigation,
|
||||||
|
einspaltige Funduskarten, lange Inhalte und Überläufe geprüft
|
||||||
- Zwei getrennte `npm start`-Läufe: Healthcheck und persistente Daten erfolgreich
|
- Zwei getrennte `npm start`-Läufe: Healthcheck und persistente Daten erfolgreich
|
||||||
- `bash -n start.sh` und programmatische Manifest-Kernfeldprüfung: erfolgreich
|
- `bash -n start.sh` und programmatische Manifest-Kernfeldprüfung: erfolgreich
|
||||||
|
|
||||||
@@ -36,3 +39,179 @@
|
|||||||
- Ein zusätzlicher Python-Playwright-Lauf: nicht gestartet, weil das optionale
|
- Ein zusätzlicher Python-Playwright-Lauf: nicht gestartet, weil das optionale
|
||||||
Python-Modul `playwright` nicht installiert war. Die projektgebundene
|
Python-Modul `playwright` nicht installiert war. Die projektgebundene
|
||||||
TypeScript-Playwright-Suite lief stattdessen vollständig erfolgreich.
|
TypeScript-Playwright-Suite lief stattdessen vollständig erfolgreich.
|
||||||
|
|
||||||
|
## Etappe 2
|
||||||
|
|
||||||
|
| Kriterium | Nachweis | Stand |
|
||||||
|
| ------------------------------- | ----------------------------------------------------------------------------------- | --------------------- |
|
||||||
|
| Erstadmin danach geschlossen | Browser-Setup sowie wiederholter Service-Aufruf geprüft; Seed enthält kein Konto | erfüllt am 21.10.2026 |
|
||||||
|
| Login, Logout und lokales HTTP | Browserablauf; `HttpOnly`, `SameSite=Lax`, ohne `Secure` bei expliziter HTTP-Origin | erfüllt am 21.10.2026 |
|
||||||
|
| Einladung und Reset | lokale Outbox bis Kontoaktivierung und neuem Login im Browser durchlaufen | erfüllt am 21.10.2026 |
|
||||||
|
| Einmalige und abgelaufene Links | Verhaltenstests für Wiederverwendung und Ablauf von Einladung und Reset | erfüllt am 21.10.2026 |
|
||||||
|
| Direkte Admin-Aktion verweigert | Thekencrew-POST auf Einladungsaction liefert 403 | erfüllt am 21.10.2026 |
|
||||||
|
| Sperrung entzieht Zugriff | aktive Thekencrew-Sitzung wird gelöscht und beim nächsten Request abgewiesen | erfüllt am 21.10.2026 |
|
||||||
|
| Keine echte Mail ungefragt | Browser- und Verhaltenstests nutzen ausschließlich temporäre lokale Outbox | erfüllt am 21.10.2026 |
|
||||||
|
| Echter SMTP-Versand | nicht ausgeführt, keine Zugangsdaten bereitgestellt | offen |
|
||||||
|
|
||||||
|
## Ausgeführte Prüfungen Etappe 2
|
||||||
|
|
||||||
|
- `npm run lint`: erfolgreich
|
||||||
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
|
- `npm test`: 9 Auth-, Migrations-, Mail- und Dauer-Verhaltenstests erfolgreich
|
||||||
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
|
- `npm run test:e2e`: 9 von 9 Browsertests erfolgreich; Erstadmin,
|
||||||
|
Login/Logout, fremder Origin, Einladung, direkte Rollenprüfung, Sperrung,
|
||||||
|
Reset sowie bestehende responsive Arbeitsansichten geprüft
|
||||||
|
- Lokale Outbox in isolierten temporären Verzeichnissen geprüft
|
||||||
|
- Lokaler Produktionsserver der Browsertests über HTTP gestartet; Healthcheck
|
||||||
|
und Migration vor Start erfolgreich
|
||||||
|
- `bash -n start.sh`: erfolgreich
|
||||||
|
|
||||||
|
## Etappe 3
|
||||||
|
|
||||||
|
| Kriterium | Nachweis | Stand |
|
||||||
|
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------- |
|
||||||
|
| Anlegen, Bearbeiten, Suchen, Filtern und Reload | Browserrundlauf mit Vorlage, Autosave, Quellen, Status, Suche und Neuladen | erfüllt am 21.10.2026 |
|
||||||
|
| Taxonomien unabhängig | Format einzeln sowie Themen und Abschnittskategorien mehrfach gespeichert und gefiltert | erfüllt am 21.10.2026 |
|
||||||
|
| Sicheres Markdown | Verhaltenstest und Browservorschau entfernen Skript/JavaScript, Formatierung bleibt erhalten | erfüllt am 21.10.2026 |
|
||||||
|
| Private Bilder | Signatur-/Größenprüfung; anonymer Direktrequest erhält keinen Dateiinhalt | erfüllt am 21.10.2026 |
|
||||||
|
| Sichtbare Speicherfehler | Actionfehler und Autosave-Fehlerstatus bleiben am Formular sichtbar | erfüllt am 21.10.2026 |
|
||||||
|
| Konflikterkennung | zwei Browserseiten; veraltete Revision erhält Konflikt und überschreibt die neue Fassung nicht | erfüllt am 21.10.2026 |
|
||||||
|
| Archiv und Wiederherstellung | Browserrundlauf blendet Piece aus und stellt den vorherigen Status wieder her | erfüllt am 21.10.2026 |
|
||||||
|
| Duplikat | Verhaltenstest und Browser prüfen unabhängige Kopie samt Zuordnungen und Bild | erfüllt am 21.10.2026 |
|
||||||
|
|
||||||
|
## Ausgeführte Prüfungen Etappe 3
|
||||||
|
|
||||||
|
- `npm run lint`: erfolgreich
|
||||||
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
|
- `npm test`: 13 Tests in 3 Dateien erfolgreich
|
||||||
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
|
- `npm run test:e2e`: 10 von 10 Browsertests erfolgreich
|
||||||
|
- Browserprüfung bei 390, 768, 960, 1280 und 1440 Pixeln in beiden Themes ohne
|
||||||
|
ungewollten horizontalen Überlauf
|
||||||
|
- Mobile Darkmode-Aufnahme des Piece-Editors visuell kontrolliert
|
||||||
|
- `bash -n start.sh` und `git diff --check`: erfolgreich
|
||||||
|
|
||||||
|
## Etappe 4
|
||||||
|
|
||||||
|
| Kriterium | Nachweis | Stand |
|
||||||
|
| ----------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------- |
|
||||||
|
| Spieleabend und mehrere JC-/Spieleblöcke | persistierte Spieleabend-Vorlage, Seed-Sendung und Browserrundlauf mit Standardablauf | erfüllt am 21.10.2026 |
|
||||||
|
| Reihenfolge und Texte bleiben nach Reload | Verhaltenstests sowie Browsertest für Tastatur- und Drag-and-drop-Sortierung | erfüllt am 21.10.2026 |
|
||||||
|
| Original bleibt unverändert | Service- und Browsertest planen dasselbe Piece mehrfach mit eigenen Titeln, Notizen, Dauern | erfüllt am 21.10.2026 |
|
||||||
|
| Keine doppelte Dauer; Reserve zählt nicht | explizite und summierte Abschnitte sowie Reserve in Verhaltenstest und Browser geprüft | erfüllt am 21.10.2026 |
|
||||||
|
| Entfernen betrifft nur Einplanung | Verhaltenstest löscht Verwendung und Abschnittskopie, nicht das Original | erfüllt am 21.10.2026 |
|
||||||
|
| Sendungsänderung verändert keine Vorlage | tiefe Vorlagenkopie vor und nach Abschnittsänderung verglichen | erfüllt am 21.10.2026 |
|
||||||
|
| Smartphone-Planungsablauf | Abschnittsanlage, Pane-Umschaltung und Überlauf bei 390 Pixeln geprüft | erfüllt am 21.10.2026 |
|
||||||
|
| Gleichwertige Bedienwege | Drag-and-drop, Enter auf Verschiebeschaltfläche sowie klick-/touchbare Zielauswahl geprüft | erfüllt am 21.10.2026 |
|
||||||
|
| Lokale Planungsaktualisierung | Quelle und Reserve per Drag-and-drop ohne Dokumentreload; lokaler Speicherzustand geprüft | erfüllt am 21.10.2026 |
|
||||||
|
| Sichtbare Einfügeposition | Abschnitt, Fundusquelle und Reserve zeigen vor dem Drop Vorschau und transparentes Original | erfüllt am 21.10.2026 |
|
||||||
|
| Piece-Dauer in Minuten | Fundus- und Verwendungseditor rechnen Minuten serverseitig in ganze Sekunden um | erfüllt am 21.10.2026 |
|
||||||
|
| Gleichzeitige Änderungen | veraltete showweite Revision rollt die gesamte Mutation zurück | erfüllt am 21.10.2026 |
|
||||||
|
|
||||||
|
## Ausgeführte Prüfungen Etappe 4
|
||||||
|
|
||||||
|
- `npm run lint`: erfolgreich
|
||||||
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
|
- `npm test`: 18 Tests in 4 Dateien erfolgreich
|
||||||
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
|
- `npm run test:e2e`: 11 von 11 Browsertests erfolgreich
|
||||||
|
- Browserprüfung bei 390, 768, 960, 1280 und 1440 Pixeln in beiden Themes ohne
|
||||||
|
ungewollten horizontalen Überlauf
|
||||||
|
- Mobile Aufnahme des vollständigen Sendungsbaukastens visuell kontrolliert
|
||||||
|
- `bash -n start.sh` und `git diff --check`: erfolgreich
|
||||||
|
|
||||||
|
## Etappe 5
|
||||||
|
|
||||||
|
| Kriterium | Nachweis | Stand |
|
||||||
|
| ------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------- |
|
||||||
|
| Lesbare Moderation | Prompter-Schrift, Einleitung und Überleitung im Browser; Recherche initial geschlossen | erfüllt am 22.10.2026 |
|
||||||
|
| Wiederherstellung | Live-Stand, Laufintervalle, Schriftgröße und Leseposition nach Neuladen geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Keine doppelte Zeiterfassung | Verhaltenstest wiederholt dieselbe Befehls-ID und findet genau ein Zeitintervall | erfüllt am 22.10.2026 |
|
||||||
|
| Explizite Präsentation | Zweitfenster bleibt nach Start leer und ändert sich erst durch „Präsentieren“ | erfüllt am 22.10.2026 |
|
||||||
|
| Getrennte sichere Ausgabe | anonymer Browserkontext prüft Text, Bild, HTML, JSON und fremde Medien ohne private Daten | erfüllt am 22.10.2026 |
|
||||||
|
| Reserve und Reihenfolge | Reserve als nächstes Piece eingefügt; offene Reihenfolge und serverseitige Live-Grenze geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Popup- und Verbindungsfehler sichtbar | blockiertes Popup sowie unterbrochenes und wiederhergestelltes State-Polling im Browser geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Persistente Linkvorschau | Quellwahl, manuelle Felder, Reload, fehlendes Bild und isolierte Testansicht im Browser geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Sichere Metadatenabrufe | Tests sperren private IPv4-/IPv6-Ziele; Redirect-, Größen- und Zeitlimits sind implementiert | erfüllt am 22.10.2026 |
|
||||||
|
| Validierte Videoplayer | YouTube-URL-Varianten, TikTok-ID, Zeitmarke und Playerwechsel automatisiert geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Präsentationssnapshot | Einplanung, Duplikation und explizite Aktualisierung aus dem Original im Servicetest geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Reale OBS-Browserquelle | lokale tokenisierte Browserausgabe vorhanden; kein OBS auf der Prüfmaschine | offen |
|
||||||
|
| Reale Anbieterwiedergabe | automatisierte Tests fangen YouTube-/TikTok-Requests lokal ab | offen |
|
||||||
|
|
||||||
|
## Ausgeführte Prüfungen Etappe 5
|
||||||
|
|
||||||
|
- `npm run lint`: erfolgreich
|
||||||
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
|
- `npm test`: 29 Tests in 6 Dateien erfolgreich
|
||||||
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
|
- `npm run test:e2e`: 14 von 14 Browsertests erfolgreich
|
||||||
|
- Anonymer zweiter Chromium-Kontext mit Präsentationstext, Quelle, geschütztem
|
||||||
|
Bild und gefiltertem JSON geprüft
|
||||||
|
- Mobile Aufnahme der Live-Steuerung bei 390 × 844 Pixeln und Desktopaufnahme
|
||||||
|
der heinzlive-Ausgabe visuell kontrolliert
|
||||||
|
- Popup-Blockade sowie Verbindungsabbruch und automatische Wiederverbindung im
|
||||||
|
Browser geprüft
|
||||||
|
- YouTube-/TikTok-Iframes, Playerwechsel, mobile Hochformatausgabe,
|
||||||
|
Linkkartenvorschau ohne Bild, isolierte Testansicht und private Datenfilterung
|
||||||
|
mit lokal abgefangenen Anbieterrequests geprüft
|
||||||
|
- SSRF-Blockade einer privaten Zieladresse über die sichtbare Editorfehlermeldung
|
||||||
|
geprüft
|
||||||
|
- `bash -n start.sh` und `git diff --check`: erfolgreich
|
||||||
|
|
||||||
|
## Gezielte Fundus- und Einplanungsanpassung
|
||||||
|
|
||||||
|
| Kriterium | Nachweis | Stand |
|
||||||
|
| ------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------- |
|
||||||
|
| Gesendet korrekt abgeleitet | Servicetest schließt offene, übersprungene, Reserve- und nicht abgeschlossene Nutzung aus | erfüllt am 22.10.2026 |
|
||||||
|
| Historie und Fundusfilter | Browser prüft letztes Datum, Sendungslink, weitere Verwendungen und Sofortfilter | erfüllt am 22.10.2026 |
|
||||||
|
| Unabhängige Quellfilter | Browser kombiniert verwendet/eingeplant getrennt und erhält sie über Suchfilter | erfüllt am 22.10.2026 |
|
||||||
|
| Reserve und Mehrfacheinplanung | Reserve zählt als eingeplant; bewusstes Wiedereinblenden erlaubt weitere Einplanung | erfüllt am 22.10.2026 |
|
||||||
|
| Rückkehr nach Entfernen | Browser entfernt die letzte Reserveeinplanung und bietet das Original sofort wieder an | erfüllt am 22.10.2026 |
|
||||||
|
| Angepasste Einplanung dupliziert | Service und Browser prüfen Position, Texte, Notizen, Dauer und Reload | erfüllt am 22.10.2026 |
|
||||||
|
| Live-Zustand des Duplikats zurückgesetzt | Servicetest prüft `open`, neue ID und fehlende Zeitintervalle | erfüllt am 22.10.2026 |
|
||||||
|
| Original unverändert | Piece-Anzahl und Original-ID vor und nach Einplanungsduplikation verglichen | erfüllt am 22.10.2026 |
|
||||||
|
| Speicherfehler nicht als Erfolg dargestellt | veraltete Revision rollt Duplikation vollständig zurück | erfüllt am 22.10.2026 |
|
||||||
|
| Globale aktive Einplanung ausgeblendet | Browser prüft den unabhängigen Filter über mehrere nicht abgeschlossene Sendungen | erfüllt am 22.10.2026 |
|
||||||
|
| Snapshot ausdrücklich aktualisiert | Service prüft neue Originaltexte und erhaltene Notizen/Intervalle; Browser löst Aktion aus | erfüllt am 22.10.2026 |
|
||||||
|
| Fehlendes Original atomar behandelt | Servicetest prüft Fehler und unveränderte Sendungsrevision | erfüllt am 22.10.2026 |
|
||||||
|
| Verwendungsdialog responsiv | Browser prüft Desktop/Mobil, Reserve, erreichbare Aktionen und sichtbare Konfliktfehler | erfüllt am 22.10.2026 |
|
||||||
|
|
||||||
|
## Ausgeführte Prüfungen Fundus und Einplanung
|
||||||
|
|
||||||
|
- `npm test`: 22 Tests in 5 Dateien erfolgreich
|
||||||
|
- `npm run lint`: erfolgreich
|
||||||
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
|
- gezielter Playwright-Lauf: 4 von 4 Browsertests erfolgreich
|
||||||
|
- `npm run test:e2e`: 12 von 12 Browsertests erfolgreich
|
||||||
|
- Desktopansichten von Fundushistorie, kombinierten Sendungsfiltern und
|
||||||
|
Verwendungsdialog sowie mobile Quellspalte und mobiler Dialog bei 390 × 844
|
||||||
|
Pixeln visuell kontrolliert
|
||||||
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
|
- `bash -n start.sh` und `git diff --check`: erfolgreich
|
||||||
|
|
||||||
|
## Redaktionelles Piece-Arbeitsblatt
|
||||||
|
|
||||||
|
| Kriterium | Nachweis | Stand |
|
||||||
|
| ---------------------------------------- | ------------------------------------------------------------------------------------------------- | --------------------- |
|
||||||
|
| Schreiben steht im Mittelpunkt | Desktop- und Mobilprüfung zeigt Fundstück, Recherche und drei Sendungstexte im primären Lesefluss | erfüllt am 22.10.2026 |
|
||||||
|
| Kontext bleibt vollständig erreichbar | Quellen, Einordnung, Präsentation und Bilder auf Desktop sowie als vier mobile Werkzeuge geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Textfelder unabhängig bearbeitbar | Recherche und Moderationsstichpunkte im Browser gleichzeitig geöffnet und gespeichert | erfüllt am 22.10.2026 |
|
||||||
|
| Bestehender Formvertrag bleibt erhalten | Autosave, Reload, Taxonomie, Quelle, Markdown, Upload, Archiv und Duplikat im Browser durchlaufen | erfüllt am 22.10.2026 |
|
||||||
|
| Konflikte und Speicherfehler sichtbar | parallele Revision sowie Offline-Autosave mit erfolgreicher manueller Wiederholung geprüft | erfüllt am 22.10.2026 |
|
||||||
|
| Schneller Video-Einstieg ohne Einordnung | Link im Eingang aufgenommen, direkt geöffnet, beschrieben und isoliert als Video getestet | erfüllt am 22.10.2026 |
|
||||||
|
| Responsive Darstellung und beide Themes | 1440 × 1000 und 390 × 844 in Light/Dark ohne horizontalen Überlauf visuell kontrolliert | erfüllt am 22.10.2026 |
|
||||||
|
|
||||||
|
## Ausgeführte Prüfungen Piece-Arbeitsblatt
|
||||||
|
|
||||||
|
- `npm run lint`: erfolgreich
|
||||||
|
- `npm run check`: 0 Fehler und 0 Warnungen
|
||||||
|
- `npm test`: 29 Tests in 6 Dateien erfolgreich
|
||||||
|
- `npm run build`: erfolgreich mit `@sveltejs/adapter-node`
|
||||||
|
- gezielter Playwright-Lauf für Autosave, Offline-Fehler, Konflikt und Upload:
|
||||||
|
1 von 1 Browsertest erfolgreich
|
||||||
|
- `npm run test:e2e`: 15 von 15 Browsertests erfolgreich
|
||||||
|
- Desktop Light/Dark sowie Smartphone Light/Dark und mobiles
|
||||||
|
Präsentationswerkzeug visuell kontrolliert; langer Titel bricht vollständig um,
|
||||||
|
Werkzeugfläche ist opak und die Speicherleiste überdeckt mobil keine Eingaben
|
||||||
|
- `bash -n start.sh` und `git diff --check`: erfolgreich
|
||||||
+204
-28
@@ -31,23 +31,24 @@ spätere API dieselben Regeln verwenden.
|
|||||||
- Zeitpunkte werden als ISO-8601-UTC-Text gespeichert. Dauern sind nichtnegative
|
- Zeitpunkte werden als ISO-8601-UTC-Text gespeichert. Dauern sind nichtnegative
|
||||||
ganze Sekunden. Zeitzonendarstellung ist `Europe/Berlin`.
|
ganze Sekunden. Zeitzonendarstellung ist `Europe/Berlin`.
|
||||||
|
|
||||||
## Geplantes Gesamtdatenmodell
|
## Gesamtdatenmodell
|
||||||
|
|
||||||
Etappe 1 materialisiert nur den für echte Vorschau- und Seed-Daten benötigten
|
Die ersten fünf Etappen materialisieren Identität, Inhaltsverwaltung,
|
||||||
Kern. Folgende Grenzen sind für spätere Migrationen bereits festgelegt.
|
Sendungsplanung und Live-Durchführung. Folgende Grenzen gelten für umgesetzte
|
||||||
|
und spätere Bereiche.
|
||||||
|
|
||||||
| Bereich | Geplante Entitäten und Beziehungen |
|
| Bereich | Geplante Entitäten und Beziehungen |
|
||||||
| ----------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| Identität | `users`, Rollen, Sessions, Einladungen, Reset-Tokens, Sperren und technische Zugänge; Tokens nur gehasht |
|
| Identität | `users`, Rollen, Sessions, Einladungen, Reset-Tokens und Sperren sind umgesetzt; technische Zugänge folgen später |
|
||||||
| Taxonomie | getrennte `section_categories`, `formats`, `topics`; Pieces und Vorschläge über Zuordnungstabellen mehrfach verknüpft |
|
| Taxonomie | getrennte `section_categories`, `formats`, `topics`; Pieces und Vorschläge über Zuordnungstabellen mehrfach verknüpft |
|
||||||
| Inhalt | `pieces` mit Status und Dauer; Quellen, Medien, private Recherche, Moderation, Präsentation und Vorlagen als getrennte Daten |
|
| Inhalt | `pieces` mit Status, Dauer, Revision, getrennten Textbereichen, Quellen und privaten Medien; Vorlagen sind definierte Startwerte |
|
||||||
| Sendungsbau | `shows`, geordnete `show_sections`, kopierte `piece_usages`, Reservebank und Sendungsvorlagen; Original-ID bleibt Referenz |
|
| Sendungsbau | `shows`, geordnete `show_sections`, kopierte `piece_usages`, Reservebank und Sendungsvorlagen sind umgesetzt; Original-ID bleibt Referenz |
|
||||||
| Live | expliziter Live-Stand, aktuelles Element, Status je Verwendung, tatsächliche Zeiten und getrennte Präsentationsausgabe |
|
| Live | expliziter Live-Stand, aktuelles Element, Status je Verwendung, tatsächliche Zeiten und getrennte Präsentationsausgabe |
|
||||||
| Historie | unveränderliche Abschluss-Snapshots und Verwendungshistorie; Übersprungenes zählt nicht als gesendet |
|
| Historie | unveränderliche Abschluss-Snapshots und Verwendungshistorie; Übersprungenes zählt nicht als gesendet |
|
||||||
| Freigaben | widerrufbare, gehashte Lesetokens mit Sendung, Umfang, Passwortoption und Ablaufzeit |
|
| Freigaben | widerrufbare, gehashte Lesetokens mit Sendung, Umfang, Passwortoption und Ablaufzeit |
|
||||||
| RSS | Feedquellen, Abrufläufe und externe Einträge mit stabiler Herkunfts-ID sowie Status neu/übernommen/verworfen |
|
| RSS | Feedquellen, Abrufläufe und externe Einträge mit stabiler Herkunfts-ID sowie Status neu/übernommen/verworfen |
|
||||||
| API/Audit | technische Berechtigungen, Idempotenzschlüssel und Audit-Ereignisse mit Akteur, Aktion und Ziel |
|
| API/Audit | technische Berechtigungen, Idempotenzschlüssel und Audit-Ereignisse mit Akteur, Aktion und Ziel |
|
||||||
| Betrieb | Anwendungseinstellungen und spätere Job-Zustände, keine Geheimnisse im Klartext ohne begründete Schutzstrategie |
|
| Betrieb | Anwendungseinstellungen und spätere Job-Zustände, keine Geheimnisse im Klartext ohne begründete Schutzstrategie |
|
||||||
|
|
||||||
### Historien- und Kopierregel
|
### Historien- und Kopierregel
|
||||||
|
|
||||||
@@ -63,22 +64,197 @@ oder eine explizite Abschnittsdauer. Beides wird nie addiert. Reserveelemente
|
|||||||
zählen erst nach dem Einplanen. Geplante und tatsächliche Dauer bleiben
|
zählen erst nach dem Einplanen. Geplante und tatsächliche Dauer bleiben
|
||||||
getrennt.
|
getrennt.
|
||||||
|
|
||||||
|
## Anmeldung und Rechte
|
||||||
|
|
||||||
|
Etappe 2 ergänzt lokale Konten mit den festen Rollen `barkeeper` und
|
||||||
|
`thekencrew`. Passwörter werden mit Argon2id gespeichert. Sitzungs-, Einladungs-
|
||||||
|
und Reset-Tokens entstehen aus kryptografischem Zufall; in SQLite liegt jeweils
|
||||||
|
nur ihr SHA-256-Hash. Der Browser erhält ausschließlich das rohe Sitzungstoken
|
||||||
|
in einem `HttpOnly`-, `SameSite=Lax`-Cookie.
|
||||||
|
|
||||||
|
`hooks.server.ts` löst die Sitzung für jeden Request auf. Die Datenbankabfrage
|
||||||
|
verbindet die Session immer mit dem aktuellen Nutzerzustand, sodass Sperren und
|
||||||
|
Rollenwechsel ohne verzögerte Token-Erneuerung wirken. Geschützte Routen
|
||||||
|
erfordern eine Anmeldung; Verwaltungs-Loads und jede Verwaltungs-Action prüfen
|
||||||
|
zusätzlich die Barkeeper-Rolle. Sperrung und Passwortwechsel löschen bestehende
|
||||||
|
Sessions transaktional.
|
||||||
|
|
||||||
|
Der Erstadmin benötigt sowohl eine leere Nutzertabelle als auch ein extern
|
||||||
|
konfiguriertes Setup-Token. Einladungs- und Reset-Links sind 24 Stunden gültig,
|
||||||
|
werden erst beim bestätigenden POST verbraucht und sind genau einmal nutzbar.
|
||||||
|
Fehlgeschlagene Loginversuche werden pro E-Mail-Schlüssel und Clientadresse in
|
||||||
|
einem Zeitfenster begrenzt, ohne das Konto dauerhaft zu sperren.
|
||||||
|
|
||||||
|
Mail verwendet einen Adapter: `local` schreibt geschützte Dateien in den
|
||||||
|
konfigurierten Outbox-Pfad, `smtp` nutzt Nodemailer nur nach expliziter Auswahl.
|
||||||
|
Die feste Anwendungs-Origin erzeugt Links und bestimmt den `Secure`-Status der
|
||||||
|
Cookies; sie wird nicht aus ungeprüften Request-Headern übernommen.
|
||||||
|
|
||||||
|
## Inhalte, Markdown und Medien
|
||||||
|
|
||||||
|
Etappe 3 führt die Inhaltslogik in `src/lib/server/content.ts` zusammen. Listen
|
||||||
|
erhalten ausschließlich kompakte Piece-Daten; private Recherche und vollständige
|
||||||
|
Redaktionstexte werden nur an den angemeldeten Editor ausgeliefert. Themen und
|
||||||
|
Abschnittskategorien sind Mehrfachzuordnungen, das Format bleibt eine einzelne
|
||||||
|
unabhängige Zuordnung. Quellen werden gemeinsam mit einem Piece atomar ersetzt.
|
||||||
|
Ein Piece kann für die Präsentation Text oder genau eine vorhandene Quelle als
|
||||||
|
Linkkarte beziehungsweise Video auswählen. Abgerufene Metadaten und Kennzeichen
|
||||||
|
für manuell korrigierte Felder liegen am Piece; ein erneuter Abruf überschreibt
|
||||||
|
diese Felder nicht.
|
||||||
|
|
||||||
|
Jedes Piece besitzt eine ganzzahlige Revision. Speichern, Archivieren und
|
||||||
|
Medienänderungen verwenden ein bedingtes Update auf die erwartete Revision.
|
||||||
|
Eine veraltete Bearbeitung liefert einen Konflikt und verändert weder Piece noch
|
||||||
|
Zuordnungen. Archivieren merkt sich den vorherigen Arbeitsstatus für die
|
||||||
|
Wiederherstellung. Duplikate erhalten neue IDs und unabhängige Bilddateien.
|
||||||
|
Piece-Dauern werden in den Fundus- und Verwendungseditoren als Minuten erfasst,
|
||||||
|
an der Servergrenze auf volle Sekunden gerundet und ausschließlich als ganze
|
||||||
|
Sekunden persistiert.
|
||||||
|
|
||||||
|
Markdown wird roh gespeichert, mit Marked serverseitig gerendert und danach mit
|
||||||
|
sanitize-html auf eine kleine Allowlist reduziert. Bilder werden nicht über
|
||||||
|
Markdown eingebettet. Uploads akzeptieren höchstens 5 MB und nur anhand ihrer
|
||||||
|
Dateisignatur erkannte JPEG-, PNG-, WebP- oder GIF-Dateien. Interne Dateinamen
|
||||||
|
sind zufällige IDs; Originalnamen werden nie als Pfad verwendet. `/media/[id]`
|
||||||
|
prüft die Anmeldung und liefert private Antworten mit `no-store`, `nosniff`,
|
||||||
|
Same-Origin-Ressourcenrichtlinie und restriktiver CSP aus.
|
||||||
|
|
||||||
|
## Sendungsbau
|
||||||
|
|
||||||
|
Etappe 4 bündelt alle Planungsmutationen in `src/lib/server/shows.ts`. Eine
|
||||||
|
Sendung ist die Konflikt- und Transaktionsgrenze: Jede Änderung an Metadaten,
|
||||||
|
Abschnitten, Verwendungen oder Reihenfolge vergleicht die erwartete Revision und
|
||||||
|
erhöht sie atomar. Abgeschlossene Sendungen sind bereits an dieser Grenze gegen
|
||||||
|
weitere Bearbeitung geschützt.
|
||||||
|
|
||||||
|
Beim Einplanen werden Titel, Dauer, Einleitung, Recherche, Moderation,
|
||||||
|
Überleitung und der vollständige Präsentationszustand aus dem sendefertigen
|
||||||
|
Piece kopiert. Dazu gehören Modus, ausgewählte Quelladresse samt Zeitmarke,
|
||||||
|
Metadaten und validierte Anbieter-ID. Eigene Notizen liegen ausschließlich an
|
||||||
|
der Verwendung. Die Referenz zum Original bleibt für Historie und
|
||||||
|
Nachvollziehbarkeit erhalten, wird aber nicht live gespiegelt. Eine explizite
|
||||||
|
Aktualisierung aus dem Fundus ersetzt Titel, Dauer, alle fünf Redaktionstexte
|
||||||
|
und den Präsentationszustand atomar aus dem referenzierten Original. Eigene
|
||||||
|
Notizen, Status und vorhandene Live-Intervalle werden dabei nicht verändert;
|
||||||
|
fehlt das Original oder ist die Sendungsrevision veraltet, wird die gesamte
|
||||||
|
Mutation verworfen.
|
||||||
|
Eine Einplanung zu duplizieren kopiert genau diesen Snapshot mit derselben
|
||||||
|
Original-ID direkt hinter das Ausgangselement. Die neue Verwendung erhält den
|
||||||
|
Status `open`, eine neue ID und damit weder Live-Referenzen noch Zeitintervalle.
|
||||||
|
|
||||||
|
Die Verwendungshistorie wird nicht separat gepflegt. Sie wird über die
|
||||||
|
Original-ID aus Verwendungen mit Status `done` in abgeschlossenen Sendungen
|
||||||
|
abgeleitet; Reservebank und alle anderen Verwendungs- oder Sendungsstatus sind
|
||||||
|
ausgeschlossen. Über dieselbe Original-ID wird unabhängig davon ermittelt, ob
|
||||||
|
mindestens eine Verwendung in einer noch nicht abgeschlossenen Sendung liegt.
|
||||||
|
Der allgemeine Fundus blendet diesen globalen Kontext standardmäßig aus. Die
|
||||||
|
Quellspalte einer Sendung betrachtet für ihren separaten Einplanungsfilter nur
|
||||||
|
die aktuelle Sendung einschließlich Reservebank.
|
||||||
|
|
||||||
|
Jede Sendung besitzt intern genau einen ausgeblendeten Reserveabschnitt. Dadurch
|
||||||
|
verwenden Plan und Reserve dieselbe geprüfte Verwendungslogik, während die
|
||||||
|
Reserve in der öffentlichen Struktur und allen Dauerberechnungen getrennt
|
||||||
|
bleibt. Positionen werden nach jeder Transaktion kollisionsfrei normalisiert.
|
||||||
|
Eine explizite Abschnittsdauer ersetzt die Summe der Verwendungen vollständig.
|
||||||
|
|
||||||
|
Sendungsvorlagen und ihre Abschnitte sind eigene Tabellen. Beim Anlegen werden
|
||||||
|
die Abschnitte mit neuen IDs kopiert; spätere Änderungen an der Sendung können
|
||||||
|
die Vorlage deshalb nicht verändern.
|
||||||
|
|
||||||
|
Die Editorformulare bleiben progressive SvelteKit-Form-Actions, werden im
|
||||||
|
Browser aber mit `use:enhance` gesendet. Der Verwendungseditor liegt in einem
|
||||||
|
nativen Dialog, den ein beschrifteter Icon-Button öffnet. Dadurch bleibt das
|
||||||
|
Dokument bei Planungsmutationen bestehen; nur die serverseitigen Seitendaten
|
||||||
|
werden aktualisiert. Ladeanzeige und FLIP-Animation liegen am betroffenen
|
||||||
|
Abschnitt oder an der betroffenen Verwendung. Eindeutige Drag-Griffe übertragen
|
||||||
|
entweder eine Quellenkopie, einen Abschnitt oder eine Verwendung auf dieselben
|
||||||
|
serverseitig geprüften Actions wie die alternativen Schaltflächen. Während des
|
||||||
|
Ziehens bleibt das Original transparent an seinem Ausgangsort; eine flüchtige
|
||||||
|
Vorschau in der Liste belegt bereits die anhand der Zeigerposition berechnete
|
||||||
|
Zielhöhe und verdrängt dadurch die benachbarten Elemente. Persistiert wird erst
|
||||||
|
beim Loslassen.
|
||||||
|
|
||||||
|
Die Ausschlussfilter für gesendete und bereits eingeplante Pieces arbeiten
|
||||||
|
clientseitig auf der serverseitig berechneten Kontextmenge. Ihr Zustand wird
|
||||||
|
ohne Navigation in die URL übernommen und bei nachfolgenden Suchfiltern
|
||||||
|
mitgesendet. Planmutationen invalidieren anschließend die Seitendaten, sodass
|
||||||
|
das Entfernen der letzten Einplanung ein Original unmittelbar wieder anbietet.
|
||||||
|
|
||||||
|
## Live-Modus und Präsentationsgrenze
|
||||||
|
|
||||||
|
`src/lib/server/live.ts` ist die Transaktionsgrenze der Live-Durchführung. Der
|
||||||
|
Live-Stand besitzt eine eigene Revision. Jeder steuernde Befehl trägt zusätzlich
|
||||||
|
eine vom Browser erzeugte Befehls-ID; `(show_id, command_id)` ist eindeutig und
|
||||||
|
liefert bei Wiederholung das bereits gespeicherte Ergebnis. Tatsächliche Zeiten
|
||||||
|
liegen als mehrere Start-/Endintervalle je Verwendung vor. Damit bleiben
|
||||||
|
Zurückgehen, Wiederaufnahme und bereits abgeschlossene Laufzeit getrennt von der
|
||||||
|
geplanten Dauer nachvollziehbar.
|
||||||
|
|
||||||
|
Die interne Route `/live` benötigt weiterhin eine aktive Sitzung und darf
|
||||||
|
Recherche, Moderation und eigene Arbeitsdaten lesen. Die separate Ausgabe
|
||||||
|
`/heinzlive/[token]` liegt dagegen in einem reduzierten Layout ohne Navigation
|
||||||
|
oder Nutzerdaten. In SQLite liegt nur der SHA-256-Hash des 256-Bit-Tokens; ein
|
||||||
|
neu erzeugter Ausgabezugang widerruft den vorherigen. Page, Polling-JSON und
|
||||||
|
Medienroute leiten ihre Daten aus einer eigenen Positivliste ab. Bilder werden
|
||||||
|
nur ausgeliefert, wenn sie zum aktuell ausdrücklich präsentierten Piece gehören.
|
||||||
|
Normale Auswahl, Fortschaltung oder Wiederaufnahme verändern den
|
||||||
|
Präsentationsstand nicht. Die öffentliche Projektion liest ausschließlich den
|
||||||
|
gespeicherten Verwendungssnapshot; spätere Änderungen am Original erscheinen
|
||||||
|
erst nach einer ausdrücklichen Snapshot-Aktualisierung.
|
||||||
|
|
||||||
|
Linkmetadaten werden nur auf ausdrückliche Aktion durch
|
||||||
|
`src/lib/server/presentation.ts` geladen. Jeder HTTP(S)-Abruf löst den Zielhost
|
||||||
|
serverseitig auf, sperrt lokale und private IPv4-/IPv6-Ziele und bindet den
|
||||||
|
Request an die geprüfte Adresse. Dieselbe Prüfung gilt nach höchstens drei
|
||||||
|
Redirects. Zeit- und Größenlimits begrenzen HTML, Anbieter-Metadaten und Bilder.
|
||||||
|
Externe Vorschaubilder gelangen nur über token- beziehungsweise
|
||||||
|
sitzungsgebundene Proxyrouten in die Ausgabe; fremdes HTML und fremde Skripte
|
||||||
|
werden nie übernommen.
|
||||||
|
|
||||||
|
Videoquellen werden aus der gespeicherten URL erneut auf eine streng validierte
|
||||||
|
YouTube- oder TikTok-ID reduziert. Der Browser erhält nur daraus erzeugte
|
||||||
|
offizielle Embed-URLs, startet sie nicht automatisch und ersetzt das Iframe bei
|
||||||
|
jedem Inhaltswechsel. YouTube erhält die Startsekunde als Embed-Parameter;
|
||||||
|
TikTok wird nach dessen Bereitschaft über die offizielle Player-`postMessage`-
|
||||||
|
Schnittstelle positioniert. Nicht unterstützte oder unvollständige Videoquellen
|
||||||
|
fallen auf eine normale Linkkarte zurück. Eine authentifizierte Testansicht
|
||||||
|
verwendet denselben Renderer, schreibt aber keinen Live-Zustand.
|
||||||
|
|
||||||
|
Die Ausgabe synchronisiert ihren kleinen öffentlichen Zustand per
|
||||||
|
`no-store`-Polling. Der letzte gültige Inhalt bleibt bei einem Verbindungsfehler
|
||||||
|
sichtbar; die Oberfläche kennzeichnet den Abbruch und versucht die Verbindung
|
||||||
|
mit verlangsamtem Intervall erneut. Private Live-Daten werden nicht Teil dieses
|
||||||
|
Zustandsobjekts.
|
||||||
|
|
||||||
## Oberflächenstruktur
|
## Oberflächenstruktur
|
||||||
|
|
||||||
Die Hauptnavigation umfasst Eingang, Fundus, Sendungen, Archiv und Verwaltung.
|
Die Hauptnavigation umfasst Eingang, Fundus, Sendungen, Archiv und Verwaltung.
|
||||||
Auf breiten Ansichten stehen Fundus und Ablauf nebeneinander. Auf schmalen
|
Auf dem Desktop bleibt eine feste Seitenleiste sichtbar; Verwaltung liegt an
|
||||||
Ansichten werden sie über eine gut erreichbare Umschaltung einzeln gezeigt.
|
ihrem unteren Ende. Bis einschließlich `52rem` ersetzen eine obere Leiste und
|
||||||
Der Live-Modus ist eine eigene, fokussierte Ansicht; die spätere
|
die untere Hauptnavigation die Seitenleiste vollständig. Auf breiten Ansichten
|
||||||
Präsentationsausgabe erhält eine separate, strikt reduzierte Datenansicht.
|
stehen Fundus und Ablauf nebeneinander. Bis einschließlich `72rem` werden sie
|
||||||
|
über eine gut erreichbare Umschaltung einzeln gezeigt, damit auch schmale
|
||||||
|
Desktopfenster ohne horizontalen Überlauf bedienbar bleiben.
|
||||||
|
Der Live-Modus ist eine eigene, fokussierte Arbeitsansicht. Die
|
||||||
|
Präsentationsausgabe verwendet eine separate, strikt reduzierte Datenansicht
|
||||||
|
ohne interne Anwendungsnavigation.
|
||||||
|
|
||||||
Etappe 1 zeigt Fundus, Sendungsbau und Live-Modus als sichtbare
|
Der eigenständige Piece-Editor ordnet denselben Formvertrag als redaktionelles
|
||||||
`Gestaltungsvorschau`. Die Daten kommen bereits aus SQLite, mutierende
|
Arbeitsblatt an. Titel, Fundstück, private Recherche sowie Einleitung,
|
||||||
Fachabläufe werden jedoch nicht vorgetäuscht.
|
Moderationsstichpunkte und Überleitung bilden die primäre Schreibfläche.
|
||||||
|
Quellen, Einordnung, Präsentation und eine Bildzusammenfassung liegen auf breiten
|
||||||
|
Ansichten in einer kontextuellen Seitenleiste; auf kleinen Ansichten öffnen
|
||||||
|
dieselben DOM-Formfelder als fokussierbare Werkzeugflächen und werden dabei nicht
|
||||||
|
neu erzeugt oder ausgehängt. `EditorialMarkdownField` hält Lese- und
|
||||||
|
Bearbeitungszustand je Textfeld lokal, während alle Werte weiterhin gemeinsam
|
||||||
|
über die bestehende `save`-Action und Piece-Revision gespeichert werden. Die
|
||||||
|
separate Bild-Action und alle Präsentationsactions bleiben eigene serverseitige
|
||||||
|
Mutationen.
|
||||||
|
|
||||||
## Sicherheitsgrenzen ab den Folgeetappen
|
## Sicherheitsgrenzen
|
||||||
|
|
||||||
Authentifizierung und Autorisierung werden serverseitig an jeder Route und
|
Authentifizierung und Autorisierung werden seit Etappe 2 serverseitig an jeder
|
||||||
Action geprüft. Markdown und fremdes HTML werden vor Ausgabe bereinigt.
|
betroffenen Route und Action geprüft. Markdown und fremdes HTML werden vor
|
||||||
Uploadzugriff folgt denselben Rechten. Netzwerkabrufe erhalten Schutz gegen
|
Ausgabe bereinigt. Uploadzugriff folgt denselben Rechten. Netzwerkabrufe für
|
||||||
interne Ziele, Größen-/Zeitlimits und kontrollierte Redirects. Diese Regeln
|
Präsentationsmetadaten und Vorschaubilder schützen interne Ziele auch nach
|
||||||
sind geplant, aber nicht Bestandteil der Etappe-1-Vorschauen.
|
DNS-Auflösung und Redirects und besitzen Größen-, Zeit- und Redirectlimits.
|
||||||
+196
-1
@@ -1,6 +1,6 @@
|
|||||||
# Entscheidungen
|
# Entscheidungen
|
||||||
|
|
||||||
Stand der Quellenprüfung: 21. Oktober 2026. Verwendet wurden offizielle
|
Stand der Quellenprüfung: 22. Oktober 2026. Verwendet wurden offizielle
|
||||||
Dokumentationen und die npm-Registry für konkrete Paket-Metadaten.
|
Dokumentationen und die npm-Registry für konkrete Paket-Metadaten.
|
||||||
|
|
||||||
## D-001: SvelteKit 3 und Node-Unterstützung
|
## D-001: SvelteKit 3 und Node-Unterstützung
|
||||||
@@ -81,3 +81,198 @@ Vorschauseiten lesen echte persistente SQLite-Seed-Daten, bieten aber keine
|
|||||||
funktionslosen Speichern- oder Live-Schaltflächen. Ein sichtbarer Hinweis
|
funktionslosen Speichern- oder Live-Schaltflächen. Ein sichtbarer Hinweis
|
||||||
grenzt Gestaltungsvorschauen von den späteren Fachfunktionen ab. Damit wird
|
grenzt Gestaltungsvorschauen von den späteren Fachfunktionen ab. Damit wird
|
||||||
keine noch nicht implementierte Funktion als fertig dargestellt.
|
keine noch nicht implementierte Funktion als fertig dargestellt.
|
||||||
|
|
||||||
|
## D-007: Arbeitsansicht nach verfügbarem Platz
|
||||||
|
|
||||||
|
Die feste Desktop-Seitenleiste wird bis `52rem` verwendet und dann vollständig
|
||||||
|
durch mobile Kopf- und Fußnavigation ersetzt. Der Sendungsbau schaltet bereits
|
||||||
|
bis `72rem` von zwei Spalten auf eine bedienbare Pane-Umschaltung um. Dadurch
|
||||||
|
bleibt die Desktopnavigation in schmalen Fenstern erhalten, ohne Fundus und
|
||||||
|
Ablauf zusammenzudrücken.
|
||||||
|
|
||||||
|
Der Fundus erscheint auf dem Desktop als kompakte Liste und auf kleinen
|
||||||
|
Bildschirmen als Kartenfolge. Vorschau- und Schreibschutzinformationen sind in
|
||||||
|
einem nativen, tastaturbedienbaren `details`-Element gebündelt. Diese
|
||||||
|
Darstellungsentscheidung ändert weder Datenmodell noch Funktionsumfang.
|
||||||
|
|
||||||
|
## D-008: Widerrufbare Datenbanksitzungen und Argon2id
|
||||||
|
|
||||||
|
Sendewerk verwendet Datenbanksitzungen statt JWT. SvelteKit empfiehlt diesen
|
||||||
|
Ansatz, wenn sofortiger Widerruf wichtiger als eine zusätzliche Datenbankabfrage
|
||||||
|
ist. Ein zufälliges Sitzungstoken liegt nur als SHA-256-Hash in SQLite; der
|
||||||
|
Browser erhält es als `HttpOnly`-, `SameSite=Lax`-Cookie. Nutzerstatus und Rolle
|
||||||
|
werden bei jedem Request erneut verbunden. Lokal erlaubt eine explizite
|
||||||
|
`http:`-Origin Cookies ohne `Secure`, bei `https:` wird `Secure` gesetzt.
|
||||||
|
|
||||||
|
Passwörter hasht `@node-rs/argon2` 2.2.2 mit Argon2id und den dokumentierten
|
||||||
|
Paketparametern. Zufallstokens und SHA-256 stammen aus `node:crypto`; eigene
|
||||||
|
Kryptoprimitive werden nicht implementiert.
|
||||||
|
|
||||||
|
Quellen:
|
||||||
|
|
||||||
|
- <https://svelte.dev/docs/kit/auth>
|
||||||
|
- <https://svelte.dev/docs/kit/hooks>
|
||||||
|
- <https://github.com/napi-rs/node-rs/tree/main/packages/argon2>
|
||||||
|
|
||||||
|
## D-009: Form-Actions, geschlossenes Setup und Rollenprüfung
|
||||||
|
|
||||||
|
Alle Auth-Schreibvorgänge verwenden POST-Form-Actions beziehungsweise einen
|
||||||
|
POST-Endpunkt. SvelteKits gleichursprüngliche Formularprüfung bleibt aktiv. Der
|
||||||
|
Erstadmin erfordert ein mindestens 32 Zeichen langes Betreiber-Setup-Token und
|
||||||
|
eine transaktional geprüfte leere Nutzertabelle. Danach bleibt `/setup`
|
||||||
|
geschlossen. Barkeeper-Rechte werden in jeder Verwaltungsaktion erneut geprüft;
|
||||||
|
UI-Sichtbarkeit ist keine Sicherheitsgrenze.
|
||||||
|
|
||||||
|
Quelle: <https://svelte.dev/docs/kit/form-actions>
|
||||||
|
|
||||||
|
## D-010: Lokale Mail-Outbox als sichere Vorgabe
|
||||||
|
|
||||||
|
Der Mailmodus ist standardmäßig `local` und schreibt Einladungs-/Resetnachrichten
|
||||||
|
in einen konfigurierten persistenten Pfad. Dadurch wird lokal keine echte Mail
|
||||||
|
ungefragt versandt. Nur die explizite Auswahl `smtp` initialisiert Nodemailer;
|
||||||
|
bei SMTP sind Host und Absender verpflichtend. Outbox-Dateien sind private
|
||||||
|
Geheimnisträger und werden weder versioniert noch über eine Route ausgeliefert.
|
||||||
|
|
||||||
|
Nodemailer 10.1.7 unterstützt Node 20 oder neuer und ist MIT-0-lizenziert.
|
||||||
|
Quelle: <https://github.com/nodemailer/nodemailer>
|
||||||
|
|
||||||
|
## D-011: Form-Actions und optimistische Piece-Revisionen
|
||||||
|
|
||||||
|
Piece-Schreibvorgänge bleiben normale SvelteKit-Form-Actions und funktionieren
|
||||||
|
damit ohne clientseitiges JavaScript. `use:enhance` ergänzt den Editor um
|
||||||
|
verzögertes Autospeichern und sichtbare Zustände. Vor interner Navigation wird
|
||||||
|
eine ausstehende Änderung gespeichert; beim Verlassen der Seite greift die
|
||||||
|
Browserwarnung. Jede Mutation vergleicht eine erwartete ganzzahlige Revision in
|
||||||
|
derselben SQLite-Transaktion. Veraltete Änderungen liefern 409 und überschreiben
|
||||||
|
keine aktuelleren Inhalte oder Zuordnungen.
|
||||||
|
|
||||||
|
Quelle: <https://svelte.dev/docs/kit/form-actions>
|
||||||
|
|
||||||
|
## D-012: Markdown immer nach dem Parsen bereinigen
|
||||||
|
|
||||||
|
Marked 18.1.1 rendert die gespeicherten Markdown-Texte serverseitig. Marked
|
||||||
|
weist ausdrücklich darauf hin, dass seine HTML-Ausgabe nicht bereinigt ist.
|
||||||
|
Darum reduziert sanitize-html 2.18.1 das Ergebnis anschließend auf ausgewählte
|
||||||
|
Text-, Listen-, Code- und Linkelemente. Skripte, Bilder, Ereignisattribute,
|
||||||
|
relative Protokoll-URLs und andere Schemata werden nicht zugelassen.
|
||||||
|
|
||||||
|
Quellen:
|
||||||
|
|
||||||
|
- <https://github.com/markedjs/marked>
|
||||||
|
- <https://github.com/apostrophecms/apostrophe/tree/main/packages/sanitize-html>
|
||||||
|
|
||||||
|
## D-013: Private Rasterbilder außerhalb statischer Assets
|
||||||
|
|
||||||
|
Uploads liegen ausschließlich im konfigurierten privaten Uploadverzeichnis und
|
||||||
|
werden über zufällige interne Namen adressiert. file-type 22.2.0 erkennt den Typ
|
||||||
|
aus dem Dateiinhalt; Client-MIME und Originalname entscheiden nicht über Typ oder
|
||||||
|
Pfad. Zugelassen sind JPEG, PNG, WebP und GIF bis 5 MB. SVG und allgemeine
|
||||||
|
Dokumente bleiben ausgeschlossen. Eine authentifizierte ID-Route liefert Bilder
|
||||||
|
mit sicherheitsrelevanten Headern aus. Das Adapter-Requestlimit liegt mit 6 MB
|
||||||
|
knapp oberhalb des fachlichen Dateilimits.
|
||||||
|
|
||||||
|
Quelle: <https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload>
|
||||||
|
|
||||||
|
## D-014: Sendung als transaktionales Aggregat
|
||||||
|
|
||||||
|
Eine ganzzahlige Revision auf `shows` schützt in Etappe 4 sämtliche Metadaten,
|
||||||
|
Abschnitte, Verwendungen und Reihenfolgen gemeinsam. Jede Mutation erhöht die
|
||||||
|
Revision in derselben SQLite-Transaktion. Damit können voneinander abhängige
|
||||||
|
Listenänderungen nicht teilweise gespeichert oder durch einen veralteten
|
||||||
|
Browserstand unbemerkt überschrieben werden.
|
||||||
|
|
||||||
|
Verwendungen speichern vollständige redaktionelle Text- und Dauerkopien. Die
|
||||||
|
Original-ID bleibt Referenz, ist aber keine Live-Datenquelle. Eine interne,
|
||||||
|
eindeutige Reservesection pro Sendung erlaubt dieselben geprüften Verschiebe-
|
||||||
|
und Löschoperationen für Plan und Reserve; Dauerabfragen schließen sie aus.
|
||||||
|
|
||||||
|
## D-015: Drag-and-drop nur als zusätzliche Bedienung
|
||||||
|
|
||||||
|
Abschnitte, Verwendungen und gefilterte Quellen können über eindeutige Griffe
|
||||||
|
gezogen werden. Dieselben Ergebnisse sind mit sichtbaren
|
||||||
|
Hoch-/Runter-Schaltflächen und Zielauswahl erreichbar. Diese Bedienelemente
|
||||||
|
funktionieren mit einfachem Klick, Touch und Tastatur auch ohne Drag-and-drop
|
||||||
|
oder clientseitige Spezialgesten. Das folgt WCAG 2.2 SC 2.5.7;
|
||||||
|
Tastaturzugang allein wäre keine ausreichende Zeigeralternative. Die
|
||||||
|
zugehörigen Form-Actions werden progressiv verbessert: Ohne JavaScript bleiben
|
||||||
|
normale POSTs möglich, mit JavaScript erfolgt die Aktualisierung ohne
|
||||||
|
Dokumentreload und mit lokalem Speicherzustand.
|
||||||
|
|
||||||
|
Quellen:
|
||||||
|
|
||||||
|
- <https://www.w3.org/WAI/WCAG22/Understanding/dragging-movements>
|
||||||
|
- <https://svelte.dev/docs/kit/form-actions>
|
||||||
|
|
||||||
|
## D-016: Live-Befehle idempotent, tatsächliche Zeiten als Intervalle
|
||||||
|
|
||||||
|
Die Live-Steuerung verwendet eine eigene Revision und zusätzlich eine pro
|
||||||
|
Bedienaktion erzeugte Befehls-ID. Die Datenbank akzeptiert jede Kombination aus
|
||||||
|
Sendung und Befehls-ID nur einmal. Ein nach Verbindungsabbruch wiederholter
|
||||||
|
Befehl liefert dieselbe Ergebnisrevision und erzeugt weder einen zweiten
|
||||||
|
Statuswechsel noch ein zweites Zeitintervall. Laufzeit wird nicht als einzelner
|
||||||
|
überschreibbarer Wert, sondern als Summe abgeschlossener und höchstens eines
|
||||||
|
aktiven Intervalls ermittelt. Dadurch bleiben Zurückgehen und Wiederaufnahme
|
||||||
|
korrekt.
|
||||||
|
|
||||||
|
## D-017: Präsentationsausgabe als Positivliste mit gehashtem Zugang
|
||||||
|
|
||||||
|
Die heinzlive-Ausgabe ist kein eingeschränkter Aufruf der internen Live-Ansicht,
|
||||||
|
sondern eine eigene Datenprojektion. Zulässig sind ausschließlich ausdrücklich
|
||||||
|
präsentierter Titel und Präsentationstext, öffentliche Quellen sowie zugehörige
|
||||||
|
Bilder und Alternativtexte. Recherche, Einleitung, Moderation, eigene Notizen,
|
||||||
|
Ablauf, Nutzer und interne Dateinamen werden nicht in HTML oder JSON übernommen.
|
||||||
|
Ein zufälliger 256-Bit-Token steht in der URL, während SQLite nur seinen
|
||||||
|
SHA-256-Hash speichert. Medienzugriff prüft Token, aktuelle Präsentation und
|
||||||
|
Bildzuordnung gemeinsam. Synchronisierung erfolgt über kleines `no-store`-
|
||||||
|
Polling statt über eine dauerhaft offene Serververbindung.
|
||||||
|
|
||||||
|
## D-018: Verwendung aus bestehenden Sendungsdaten ableiten
|
||||||
|
|
||||||
|
„Gesendet“ ist kein Zustand am Fundus-Piece. Die Anzeige wird ausschließlich
|
||||||
|
aus der vorhandenen Original-ID, einer erledigten Verwendung außerhalb der
|
||||||
|
Reservebank und dem Status `completed` ihrer Sendung abgeleitet. Dadurch können
|
||||||
|
Einplanung, Reserve und Überspringen ein Original nicht versehentlich als
|
||||||
|
gesendet markieren, und mehrere tatsächliche Verwendungen bleiben als Historie
|
||||||
|
sichtbar.
|
||||||
|
|
||||||
|
Eine Duplikation im Sendungsablauf kopiert den konkreten Verwendungssnapshot und
|
||||||
|
nicht das Original-Piece. Die neue ID, der Status `open` und fehlende
|
||||||
|
Live-Intervalle trennen sie von der bisherigen Durchführung. Der allgemeine
|
||||||
|
Verwendungseditor darf den Live-Status nicht mehr aus Formulardaten schreiben;
|
||||||
|
Statuswechsel bleiben der Live-Geschäftslogik vorbehalten.
|
||||||
|
|
||||||
|
Eine bestehende Einplanung wird nicht automatisch mit späteren Änderungen am
|
||||||
|
Original synchronisiert. Die ausdrücklich ausgelöste Aktion **Aus Fundus
|
||||||
|
aktualisieren** überschreibt nur Titel, Dauer und Redaktionstexte. Eigene
|
||||||
|
Notizen, Status und Messintervalle bleiben erhalten. Alle Zuordnungen und Filter
|
||||||
|
verwenden ausschließlich `original_piece_id`, niemals veränderliche Titel. Im
|
||||||
|
allgemeinen Fundus gilt „eingeplant“ global für jede nicht abgeschlossene
|
||||||
|
Sendung; im Sendungsbau gilt es lokal für die aktuelle Sendung samt Reserve.
|
||||||
|
|
||||||
|
## D-019: Lokale Linkmetadaten und streng abgeleitete Video-Embeds
|
||||||
|
|
||||||
|
Sendewerk verwendet Metascraper ausschließlich serverseitig, um Titel,
|
||||||
|
Beschreibung, Bild und Herausgeber einer ausdrücklich gewählten vorhandenen
|
||||||
|
Quelle zu ermitteln. Die Ergebnisse werden gespeichert und nicht bei jedem
|
||||||
|
Seitenaufruf neu geladen. Manuell korrigierte Felder haben Vorrang. Ein eigener
|
||||||
|
HTTP(S)-Client prüft Protokoll, Port, DNS-Ergebnisse und jedes Redirectziel,
|
||||||
|
bindet den Request an die geprüfte öffentliche Adresse und begrenzt Redirects,
|
||||||
|
Laufzeit und Antwortgröße. Damit ist weder ein externer Vorschaudienst noch die
|
||||||
|
Übernahme fremden HTMLs erforderlich.
|
||||||
|
|
||||||
|
Player werden nur für streng erkannte YouTube- und TikTok-URLs erzeugt. Aus der
|
||||||
|
validierten Anbieter-ID baut Sendewerk die offiziellen Embed-Adressen selbst;
|
||||||
|
gespeichertes oder fremd geliefertes Embed-HTML wird nicht verwendet. YouTube
|
||||||
|
nutzt die datenschutzreduzierte `youtube-nocookie.com`-Adresse und den
|
||||||
|
`start`-Parameter. TikTok erhält eine Startposition nach `onPlayerReady` über
|
||||||
|
die dokumentierte Player-`postMessage`-API. Autoplay bleibt ausgeschaltet, und
|
||||||
|
ein Inhaltswechsel ersetzt das Iframe vollständig.
|
||||||
|
|
||||||
|
Quellen:
|
||||||
|
|
||||||
|
- <https://github.com/microlinkhq/metascraper>
|
||||||
|
- <https://developers.google.com/youtube/player_parameters>
|
||||||
|
- <https://developers.google.com/youtube/terms/required-minimum-functionality>
|
||||||
|
- <https://developers.tiktok.com/doc/embed-player>
|
||||||
|
- <https://developers.tiktok.com/doc/embed-videos>
|
||||||
|
- <https://owasp.org/www-community/attacks/Server_Side_Request_Forgery>
|
||||||
+140
-7
@@ -2,8 +2,10 @@
|
|||||||
|
|
||||||
## Aktueller Umfang
|
## Aktueller Umfang
|
||||||
|
|
||||||
Etappe 1 ist abgeschlossen. Architektur, Gesamtdatenmodell, Entscheidungen und
|
Etappe 1 bis Etappe 5 sind abgeschlossen. Architektur, Gesamtdatenmodell,
|
||||||
lokaler Betriebsweg sind dokumentiert. Etappe 2 wurde nicht begonnen.
|
Anmeldung, Rollen, persistente Inhaltsbearbeitung, Sendungsplanung,
|
||||||
|
Live-Steuerung, Präsentationsausgabe und lokaler Betriebsweg sind dokumentiert.
|
||||||
|
Etappe 6 wurde nicht begonnen.
|
||||||
|
|
||||||
## Umgesetzter Stand Etappe 1
|
## Umgesetzter Stand Etappe 1
|
||||||
|
|
||||||
@@ -13,6 +15,8 @@ lokaler Betriebsweg sind dokumentiert. Etappe 2 wurde nicht begonnen.
|
|||||||
- persistentes Light-/Dark-/System-Theme
|
- persistentes Light-/Dark-/System-Theme
|
||||||
- responsive Navigation und gekennzeichnete Vorschauen für Fundus,
|
- responsive Navigation und gekennzeichnete Vorschauen für Fundus,
|
||||||
Sendungsbau und Live-Modus
|
Sendungsbau und Live-Modus
|
||||||
|
- kompakte Desktop-Arbeitsansicht mit fester Seitenleiste, Fundusliste und
|
||||||
|
zweigeteiltem Sendungsbau; auf schmalen Ansichten Umschaltung statt Engpass
|
||||||
- Healthcheck, Produktionsstart und frühes Cloudron-Paket
|
- Healthcheck, Produktionsstart und frühes Cloudron-Paket
|
||||||
- getrennte Unit-/Integrations- und Browser-Testdaten
|
- getrennte Unit-/Integrations- und Browser-Testdaten
|
||||||
|
|
||||||
@@ -20,12 +24,132 @@ Die Vorschauen lesen echte Daten aus SQLite. Suche und mobile Pane-Umschaltung
|
|||||||
funktionieren lokal; redaktionelle Schreiboperationen bleiben bewusst den
|
funktionieren lokal; redaktionelle Schreiboperationen bleiben bewusst den
|
||||||
späteren Etappen vorbehalten.
|
späteren Etappen vorbehalten.
|
||||||
|
|
||||||
## Nicht Bestandteil dieser Etappe
|
Die abschließende Oberflächenüberarbeitung von Etappe 1 reduziert große
|
||||||
|
Seitenköpfe und verschachtelte Karten, bündelt den Schreibschutzhinweis
|
||||||
|
aufklappbar und hält Entwicklungsinformationen aus der Arbeitsoberfläche heraus.
|
||||||
|
Eingang und Archiv zeigen kurze Leerzustände, die Verwaltung trennt
|
||||||
|
Abschnittskategorien, Formate und Themen kompakt.
|
||||||
|
|
||||||
Anmeldung, Rollen, echte Inhaltsbearbeitung, Autospeichern, Sendungsplanung,
|
Die abschließende responsive Prüfung verdichtet Seitenleiste, Navigation und
|
||||||
Live-Steuerung, Präsentationsfenster, Archivabschluss, Freigaben, RSS und API.
|
Funduszeilen weiter. Mobile Funduskarten sind intern einspaltig; lange Titel,
|
||||||
Die Vorschauen dürfen nicht als Implementierung dieser Funktionen verstanden
|
Beschreibungen und Metadaten bleiben ohne feste Kartenhöhe sichtbar. Suche und
|
||||||
werden.
|
Statusfilter sind gleich hoch, und die Filtergruppe wird nur als Ganzes
|
||||||
|
umgebrochen.
|
||||||
|
|
||||||
|
## Noch nicht umgesetzt
|
||||||
|
|
||||||
|
Archivabschluss, Freigaben, RSS und API. Diese späteren Bereiche dürfen nicht
|
||||||
|
als bereits implementiert verstanden werden.
|
||||||
|
|
||||||
|
## Umgesetzter Stand Etappe 2
|
||||||
|
|
||||||
|
- einmalige Erstadmin-Einrichtung mit externem Betreiber-Token
|
||||||
|
- Login und POST-Logout mit widerrufbaren Datenbanksitzungen
|
||||||
|
- Rollen Barkeeper und Thekencrew mit serverseitiger Prüfung
|
||||||
|
- Einladungen und Passwortreset über befristete, einmalige Links
|
||||||
|
- Kontensperrung mit sofortigem Entzug bestehender Sitzungen
|
||||||
|
- zeitfensterbasiertes Login-Rate-Limit ohne dauerhafte Kontensperre
|
||||||
|
- lokale Mail-Outbox als Vorgabe und explizit konfigurierbarer SMTP-Versand
|
||||||
|
- responsive Authentifizierungs- und Kontenverwaltungsoberflächen
|
||||||
|
|
||||||
|
## Umgesetzter Stand Etappe 3
|
||||||
|
|
||||||
|
- persistente Piece-Neuanlage aus leerem Entwurf oder drei redaktionellen Vorlagen
|
||||||
|
- Schnellaufnahme von Gedanken und HTTP-/HTTPS-Links im Eingang
|
||||||
|
- vollständiger Editor für Quellen, Dauer in Minuten, Status und getrennte
|
||||||
|
Einleitung, Recherche, Moderation, Überleitung und Präsentation
|
||||||
|
- serverseitig bereinigte Markdown-Vorschau
|
||||||
|
- unabhängige Themen, Formate und Abschnittskategorien mit Barkeeper-Verwaltung
|
||||||
|
- serverseitige Suche und Filter nach Status, Format, Thema und Abschnitt
|
||||||
|
- Autospeichern mit sichtbarem Zustand und Warten vor interner Navigation
|
||||||
|
- optimistische Revisionen verhindern unbemerktes Überschreiben
|
||||||
|
- Duplizieren einschließlich Quellen, Taxonomie und Bildern
|
||||||
|
- Archivieren und Wiederherstellen in den vorherigen Arbeitsstatus
|
||||||
|
- private Rasterbilder mit Größen-/Signaturprüfung und geschützter Auslieferung
|
||||||
|
- erweiterter Seed mit Eingangs-, Archiv-, Markdown- und Recherchebeispielen
|
||||||
|
- standardmäßig ausgeblendete gesendete Pieces mit verlinkter, aufklappbarer
|
||||||
|
Verwendungshistorie; gesendet bedeutet erledigt in abgeschlossener Sendung
|
||||||
|
- standardmäßig ausgeblendete Pieces, die in mindestens einer noch nicht
|
||||||
|
abgeschlossenen Sendung eingeplant sind, mit unabhängigem Sofortfilter
|
||||||
|
- Fundus-Originale und sendungsspezifische Verwendungen nutzen denselben
|
||||||
|
großzügigen Dialograhmen mit den Bereichen „Sendungstext“, „Recherche &
|
||||||
|
Quellen“ und „Präsentation“; der jeweilige Speicherkontext ist sichtbar und
|
||||||
|
Original sowie Verwendung bleiben getrennte Revisionsgrenzen
|
||||||
|
- Titel, Einleitung, Moderationsstichpunkte und Überleitung sind ohne
|
||||||
|
vorgeschaltete Lese-/Bearbeitungsschalter direkt beschreibbar; eine kleine
|
||||||
|
Markdown-Leiste ergänzt Formatierung ohne Änderung des Speicherformats
|
||||||
|
- Recherche, Quellen, verwendungseigene Notizen und Material sind in einem
|
||||||
|
Bereich gebündelt; öffentliche Texte, Darstellungswahl und tatsächliche
|
||||||
|
Vorschau stehen gemeinsam im Präsentationsbereich
|
||||||
|
- der Dialog bleibt innerhalb der Desktop-Fensterhöhe, hält Kopf,
|
||||||
|
Bereichsnavigation und Aktionen sichtbar und nutzt mobil die volle
|
||||||
|
Bildschirmfläche; Bereichswechsel hängen Eingaben nicht aus und merken die
|
||||||
|
jeweilige Scrollposition
|
||||||
|
- die Schnellaufnahme akzeptiert Gedanke oder URL, bleibt nach dem Ablegen im
|
||||||
|
Eingang und öffnet die Ausarbeitung erst über eine bewusste Aktion
|
||||||
|
|
||||||
|
Für diese gezielte Überarbeitung wurden `npm run check` sowie kurze
|
||||||
|
Chromium-Sichtkontrollen des Original- und Verwendungseditors bei 1440 × 1000
|
||||||
|
und 390 × 844 Pixeln ausgeführt. Dabei waren Dialoggrenzen, feste Bedienbereiche,
|
||||||
|
alle drei Arbeitsbereiche und horizontaler Überlauf unauffällig. Die vollständige
|
||||||
|
Unit-, E2E- und Build-Matrix ist gemäß Auftrag noch offen.
|
||||||
|
|
||||||
|
## Umgesetzter Stand Etappe 4
|
||||||
|
|
||||||
|
- Sendungsübersicht mit leerem Start, Standardablauf und Spieleabend-Vorlage
|
||||||
|
- frei benennbare, kategorisierte und sortierbare Abschnitte einschließlich
|
||||||
|
eigenständiger Spieleblöcke
|
||||||
|
- Einplanung ausschließlich sendefertiger Pieces als unabhängige Text- und
|
||||||
|
Dauerkopien; Mehrfachverwendung desselben Originals ist möglich
|
||||||
|
- showweite Reservebank, die nicht in Abschnitts- oder Gesamtdauer einfließt
|
||||||
|
- explizite Abschnittsdauer ersetzt die Piece-Summe statt sie zu addieren
|
||||||
|
- Bearbeiten, Entfernen sowie Verschieben innerhalb und zwischen Abschnitten
|
||||||
|
- zugänglicher Stift-Dialog für alle sendungsspezifischen Felder und Aktionen,
|
||||||
|
auf Desktop zweispaltig und auf kleinen Bildschirmen einspaltig scrollbar
|
||||||
|
- explizites Aktualisieren eines Verwendungssnapshots aus dem Original für
|
||||||
|
Titel, Dauer und Redaktionstexte bei erhaltenen Notizen und Live-Daten
|
||||||
|
- Duplizieren einer konkreten Einplanung direkt hinter dem Ausgangselement mit
|
||||||
|
erhaltenen Anpassungen, aber zurückgesetztem Live-Zustand
|
||||||
|
- Piece-Dauern werden im Editor in Minuten eingegeben und intern weiterhin als
|
||||||
|
ganze Sekunden gespeichert
|
||||||
|
- Drag-and-drop über eindeutige Griffe, auch direkt aus gefilterten Quellen,
|
||||||
|
mit positionsgenauer Einfügevorschau, transparentem Original und
|
||||||
|
gleichwertigen Klick-, Touch- und Tastaturaktionen
|
||||||
|
- Planungsmutationen ohne Dokumentreload mit lokalem Speicherzustand und
|
||||||
|
animierter Neusortierung der betroffenen Elemente
|
||||||
|
- unabhängige Sofortfilter für verwendete sowie in der aktuellen Sendung schon
|
||||||
|
eingeplante Originale einschließlich Reservebank
|
||||||
|
- kopierbare Twitch-Titel und Ankündigungstexte
|
||||||
|
- showweite optimistische Revision schützt Metadaten, Reihenfolge und Inhalte
|
||||||
|
vor unbemerktem parallelem Überschreiben
|
||||||
|
- realistischer Seed mit Standardablauf und eigenständigem Spieleabend
|
||||||
|
|
||||||
|
## Umgesetzter Stand Etappe 5
|
||||||
|
|
||||||
|
- fokussierte Moderationsansicht mit Prompter-Schrift, Einleitung, Moderation,
|
||||||
|
Überleitung und standardmäßig geschlossener privater Recherche
|
||||||
|
- ausblendbare Zeit- und Ablaufanzeige sowie persistente lokale Leseposition
|
||||||
|
- aktuelles und nächstes Piece samt Abschnitt und geplantem Zeitbedarf
|
||||||
|
- persistenter Live-Stand mit tatsächlichen Laufintervallen, Erledigen,
|
||||||
|
Überspringen, Zurück und Wiederaufnahme
|
||||||
|
- idempotente Live-Befehle verhindern doppelte Wirkung bei Wiederholung
|
||||||
|
- serverseitig geschützte Umsortierung offener Pieces und Reserveeinfügung
|
||||||
|
- explizite Präsentationsaktion; normale Live-Navigation verändert die Ausgabe
|
||||||
|
nicht
|
||||||
|
- getrennte, tokenisierte heinzlive-Ausgabe mit Polling, Verbindungsanzeige,
|
||||||
|
Präsentationstext, Quellen und erlaubten Bildern
|
||||||
|
- wählbare Text-, Linkkarten- und Videodarstellung aus genau einer vorhandenen
|
||||||
|
Piece-Quelle mit manuell korrigierbaren, persistenten Metadaten
|
||||||
|
- ausdrückliches serverseitiges Neuladen von Linkmetadaten über Metascraper mit
|
||||||
|
DNS-, Redirect-, Zeit-, Größen- und Privatnetzschutz
|
||||||
|
- validierte YouTube- und TikTok-IDs, offizielle Player-Iframes ohne Autoplay
|
||||||
|
sowie Linkkarten-Fallback für nicht unterstützte Videoquellen
|
||||||
|
- unveränderliche Präsentationssnapshots je Einplanung und explizite
|
||||||
|
Aktualisierung aus dem Fundus
|
||||||
|
- isolierte Präsentationstestansicht ohne Änderung des Live-Stands sowie
|
||||||
|
tokengebundene, serverseitig geschützte Proxys für externe Vorschaubilder
|
||||||
|
- Ausgabe-HTML, JSON und Medienzugriff enthalten keine Recherche,
|
||||||
|
Moderationsnotizen, eigenen Notizen, Kontodaten oder internen Dateipfade
|
||||||
|
|
||||||
## Bekannte offene Betriebsprüfung
|
## Bekannte offene Betriebsprüfung
|
||||||
|
|
||||||
@@ -35,6 +159,15 @@ durchgeführt werden. Auch der lokale Container-Smoke-Test blieb offen, weil
|
|||||||
auf der Prüfmaschine kein Docker-Daemon lief. Manifestkernfelder und
|
auf der Prüfmaschine kein Docker-Daemon lief. Manifestkernfelder und
|
||||||
Startskript-Syntax wurden lokal geprüft.
|
Startskript-Syntax wurden lokal geprüft.
|
||||||
|
|
||||||
|
Eine reale OBS-Browserquelle stand nicht zur Verfügung. Die tokenisierte
|
||||||
|
Präsentationsausgabe wurde stattdessen in einem anonymen zweiten Chromium-
|
||||||
|
Browserkontext einschließlich Bild, JSON-Filterung, Polling und sichtbarem
|
||||||
|
Verbindungsabbruch geprüft.
|
||||||
|
|
||||||
|
Die automatisierten Playerprüfungen fingen YouTube- und TikTok-Requests lokal
|
||||||
|
ab. URL-Erkennung, Iframe-Wechsel, Zeitmarkenübergabe und mobile Ausgabe sind
|
||||||
|
damit geprüft, nicht jedoch die reale Wiedergabe oder Verfügbarkeit der Anbieter.
|
||||||
|
|
||||||
## Verifizierte Umgebung
|
## Verifizierte Umgebung
|
||||||
|
|
||||||
- Node.js 22.23.1, npm 10.9.8
|
- Node.js 22.23.1, npm 10.9.8
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL,
|
||||||
|
email_normalized TEXT NOT NULL UNIQUE,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK (role IN ('barkeeper', 'thekencrew')),
|
||||||
|
locked_at_utc TEXT,
|
||||||
|
password_changed_at_utc TEXT NOT NULL,
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
updated_at_utc TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
expires_at_utc TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX sessions_user_idx ON sessions(user_id);
|
||||||
|
CREATE INDEX sessions_expiry_idx ON sessions(expires_at_utc);
|
||||||
|
|
||||||
|
CREATE TABLE invitations (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL,
|
||||||
|
email_normalized TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK (role IN ('barkeeper', 'thekencrew')),
|
||||||
|
token_hash TEXT NOT NULL UNIQUE,
|
||||||
|
created_by_user_id TEXT NOT NULL REFERENCES users(id),
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
expires_at_utc TEXT NOT NULL,
|
||||||
|
accepted_at_utc TEXT,
|
||||||
|
revoked_at_utc TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX invitations_email_idx ON invitations(email_normalized, created_at_utc);
|
||||||
|
|
||||||
|
CREATE TABLE password_reset_tokens (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token_hash TEXT NOT NULL UNIQUE,
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
expires_at_utc TEXT NOT NULL,
|
||||||
|
consumed_at_utc TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX password_resets_user_idx ON password_reset_tokens(user_id, created_at_utc);
|
||||||
|
|
||||||
|
CREATE TABLE login_attempts (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
email_key TEXT NOT NULL,
|
||||||
|
address_key TEXT NOT NULL,
|
||||||
|
attempted_at_utc TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX login_attempts_email_idx ON login_attempts(email_key, attempted_at_utc);
|
||||||
|
CREATE INDEX login_attempts_address_idx ON login_attempts(address_key, attempted_at_utc);
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
ALTER TABLE pieces ADD COLUMN research_text TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN revision INTEGER NOT NULL DEFAULT 1 CHECK (revision >= 1);
|
||||||
|
ALTER TABLE pieces ADD COLUMN archived_from_status TEXT CHECK (
|
||||||
|
archived_from_status IS NULL OR archived_from_status IN ('inbox', 'preparing', 'ready')
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE piece_media (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
piece_id TEXT NOT NULL REFERENCES pieces(id) ON DELETE CASCADE,
|
||||||
|
storage_name TEXT NOT NULL UNIQUE,
|
||||||
|
original_name TEXT NOT NULL,
|
||||||
|
mime_type TEXT NOT NULL CHECK (mime_type IN ('image/jpeg', 'image/png', 'image/webp', 'image/gif')),
|
||||||
|
byte_size INTEGER NOT NULL CHECK (byte_size > 0 AND byte_size <= 5242880),
|
||||||
|
alt_text TEXT NOT NULL DEFAULT '',
|
||||||
|
position INTEGER NOT NULL CHECK (position >= 0),
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
UNIQUE (piece_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_piece_media_piece ON piece_media(piece_id, position);
|
||||||
|
CREATE INDEX idx_piece_topics_topic ON piece_topics(topic_id, piece_id);
|
||||||
|
CREATE INDEX idx_piece_categories_category ON piece_category_suggestions(category_id, piece_id);
|
||||||
|
CREATE INDEX idx_piece_sources_piece ON piece_sources(piece_id, position);
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
CREATE TABLE shows_v4 (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
starts_at_utc TEXT,
|
||||||
|
twitch_title TEXT NOT NULL DEFAULT '',
|
||||||
|
announcement_text TEXT NOT NULL DEFAULT '',
|
||||||
|
status TEXT NOT NULL CHECK (status IN ('draft', 'ready', 'live', 'completed')),
|
||||||
|
revision INTEGER NOT NULL DEFAULT 1 CHECK (revision >= 1),
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
updated_at_utc TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE show_sections_v4 (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
show_id TEXT NOT NULL REFERENCES shows_v4(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
category_id TEXT REFERENCES section_categories(id) ON DELETE SET NULL,
|
||||||
|
position INTEGER NOT NULL CHECK (position >= 0),
|
||||||
|
explicit_duration_seconds INTEGER CHECK (
|
||||||
|
explicit_duration_seconds IS NULL OR
|
||||||
|
(explicit_duration_seconds >= 0 AND explicit_duration_seconds <= 86400)
|
||||||
|
),
|
||||||
|
is_reserve_bank INTEGER NOT NULL DEFAULT 0 CHECK (is_reserve_bank IN (0, 1)),
|
||||||
|
UNIQUE (show_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE piece_usages_v4 (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
show_section_id TEXT NOT NULL REFERENCES show_sections_v4(id) ON DELETE CASCADE,
|
||||||
|
original_piece_id TEXT REFERENCES pieces(id) ON DELETE SET NULL,
|
||||||
|
position INTEGER NOT NULL CHECK (position >= 0),
|
||||||
|
status TEXT NOT NULL CHECK (status IN ('open', 'current', 'done', 'skipped')),
|
||||||
|
duration_seconds INTEGER NOT NULL CHECK (duration_seconds >= 0 AND duration_seconds <= 86400),
|
||||||
|
title_snapshot TEXT NOT NULL,
|
||||||
|
intro_snapshot TEXT NOT NULL DEFAULT '',
|
||||||
|
research_snapshot TEXT NOT NULL DEFAULT '',
|
||||||
|
moderation_snapshot TEXT NOT NULL DEFAULT '',
|
||||||
|
transition_snapshot TEXT NOT NULL DEFAULT '',
|
||||||
|
presentation_snapshot TEXT NOT NULL DEFAULT '',
|
||||||
|
own_notes TEXT NOT NULL DEFAULT '',
|
||||||
|
is_reserve INTEGER NOT NULL DEFAULT 0 CHECK (is_reserve IN (0, 1)),
|
||||||
|
UNIQUE (show_section_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO shows_v4 (
|
||||||
|
id, title, starts_at_utc, twitch_title, announcement_text, status, revision,
|
||||||
|
created_at_utc, updated_at_utc
|
||||||
|
)
|
||||||
|
SELECT id, title, starts_at_utc, twitch_title, announcement_text, status, 1,
|
||||||
|
created_at_utc, updated_at_utc
|
||||||
|
FROM shows;
|
||||||
|
|
||||||
|
INSERT INTO show_sections_v4 (
|
||||||
|
id, show_id, name, category_id, position, explicit_duration_seconds, is_reserve_bank
|
||||||
|
)
|
||||||
|
SELECT id, show_id, name, category_id, position, explicit_duration_seconds, 0
|
||||||
|
FROM show_sections;
|
||||||
|
|
||||||
|
INSERT INTO show_sections_v4 (
|
||||||
|
id, show_id, name, category_id, position, explicit_duration_seconds, is_reserve_bank
|
||||||
|
)
|
||||||
|
SELECT 'reserve-bank-' || id, id, 'Reservebank', NULL,
|
||||||
|
COALESCE((SELECT max(position) + 1 FROM show_sections WHERE show_id = shows.id), 0), NULL, 1
|
||||||
|
FROM shows;
|
||||||
|
|
||||||
|
INSERT INTO piece_usages_v4 (
|
||||||
|
id, show_section_id, original_piece_id, position, status, duration_seconds,
|
||||||
|
title_snapshot, intro_snapshot, research_snapshot, moderation_snapshot,
|
||||||
|
transition_snapshot, presentation_snapshot, own_notes, is_reserve
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
u.id,
|
||||||
|
CASE WHEN u.is_reserve = 1 THEN 'reserve-bank-' || s.show_id ELSE u.show_section_id END,
|
||||||
|
u.original_piece_id,
|
||||||
|
CASE WHEN u.is_reserve = 1 THEN
|
||||||
|
(
|
||||||
|
SELECT count(*) - 1
|
||||||
|
FROM piece_usages earlier
|
||||||
|
JOIN show_sections earlier_section ON earlier_section.id = earlier.show_section_id
|
||||||
|
WHERE earlier.is_reserve = 1 AND earlier_section.show_id = s.show_id
|
||||||
|
AND (earlier_section.position < s.position OR
|
||||||
|
(earlier_section.position = s.position AND earlier.position < u.position) OR
|
||||||
|
(earlier_section.position = s.position AND earlier.position = u.position AND earlier.id <= u.id))
|
||||||
|
)
|
||||||
|
ELSE u.position END,
|
||||||
|
u.status,
|
||||||
|
u.duration_seconds,
|
||||||
|
u.title_snapshot,
|
||||||
|
u.intro_snapshot,
|
||||||
|
COALESCE(p.research_text, ''),
|
||||||
|
u.moderation_snapshot,
|
||||||
|
u.transition_snapshot,
|
||||||
|
u.presentation_snapshot,
|
||||||
|
'',
|
||||||
|
u.is_reserve
|
||||||
|
FROM piece_usages u
|
||||||
|
JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
LEFT JOIN pieces p ON p.id = u.original_piece_id;
|
||||||
|
|
||||||
|
DROP TABLE piece_usages;
|
||||||
|
DROP TABLE show_sections;
|
||||||
|
DROP TABLE shows;
|
||||||
|
|
||||||
|
ALTER TABLE shows_v4 RENAME TO shows;
|
||||||
|
ALTER TABLE show_sections_v4 RENAME TO show_sections;
|
||||||
|
ALTER TABLE piece_usages_v4 RENAME TO piece_usages;
|
||||||
|
|
||||||
|
CREATE INDEX idx_shows_status_start ON shows(status, starts_at_utc);
|
||||||
|
CREATE INDEX idx_sections_show ON show_sections(show_id, position);
|
||||||
|
CREATE INDEX idx_usages_section ON piece_usages(show_section_id, position);
|
||||||
|
CREATE UNIQUE INDEX idx_one_reserve_bank_per_show
|
||||||
|
ON show_sections(show_id) WHERE is_reserve_bank = 1;
|
||||||
|
|
||||||
|
CREATE TABLE show_templates (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
description TEXT NOT NULL DEFAULT ''
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE show_template_sections (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
template_id TEXT NOT NULL REFERENCES show_templates(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
category_id TEXT REFERENCES section_categories(id) ON DELETE SET NULL,
|
||||||
|
position INTEGER NOT NULL CHECK (position >= 0),
|
||||||
|
explicit_duration_seconds INTEGER CHECK (
|
||||||
|
explicit_duration_seconds IS NULL OR
|
||||||
|
(explicit_duration_seconds >= 0 AND explicit_duration_seconds <= 86400)
|
||||||
|
),
|
||||||
|
UNIQUE (template_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_show_template_sections_template
|
||||||
|
ON show_template_sections(template_id, position);
|
||||||
|
|
||||||
|
INSERT INTO show_templates (id, name, description) VALUES
|
||||||
|
('template-default', 'Standardablauf', 'Start, zwei JC-Blöcke und zwei Spiele.'),
|
||||||
|
('template-games', 'Spieleabend', 'Ein ruhiger Einstieg und drei flexible Spieleblöcke.');
|
||||||
|
|
||||||
|
INSERT INTO show_template_sections (
|
||||||
|
id, template_id, name, category_id, position, explicit_duration_seconds
|
||||||
|
) VALUES
|
||||||
|
('template-default-start', 'template-default', 'Start', NULL, 0, 300),
|
||||||
|
('template-default-jc-reaction', 'template-default', 'JC / Reaction', NULL, 1, NULL),
|
||||||
|
('template-default-game-1', 'template-default', 'Spiel 1', NULL, 2, 3600),
|
||||||
|
('template-default-jc', 'template-default', 'JC', NULL, 3, NULL),
|
||||||
|
('template-default-game-2', 'template-default', 'Spiel 2', NULL, 4, 3600),
|
||||||
|
('template-games-start', 'template-games', 'Start', NULL, 0, 300),
|
||||||
|
('template-games-game-1', 'template-games', 'Spiel 1', NULL, 1, 2700),
|
||||||
|
('template-games-break', 'template-games', 'Pause & Chat', NULL, 2, 600),
|
||||||
|
('template-games-game-2', 'template-games', 'Spiel 2', NULL, 3, 2700),
|
||||||
|
('template-games-game-3', 'template-games', 'Spiel 3', NULL, 4, 2700);
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
CREATE TABLE show_live_states (
|
||||||
|
show_id TEXT PRIMARY KEY REFERENCES shows(id) ON DELETE CASCADE,
|
||||||
|
revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),
|
||||||
|
current_usage_id TEXT REFERENCES piece_usages(id) ON DELETE SET NULL,
|
||||||
|
started_at_utc TEXT,
|
||||||
|
ended_at_utc TEXT,
|
||||||
|
presentation_usage_id TEXT REFERENCES piece_usages(id) ON DELETE SET NULL,
|
||||||
|
presentation_revision INTEGER NOT NULL DEFAULT 0 CHECK (presentation_revision >= 0),
|
||||||
|
updated_at_utc TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE live_usage_runs (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
show_id TEXT NOT NULL REFERENCES shows(id) ON DELETE CASCADE,
|
||||||
|
usage_id TEXT NOT NULL REFERENCES piece_usages(id) ON DELETE CASCADE,
|
||||||
|
started_at_utc TEXT NOT NULL,
|
||||||
|
ended_at_utc TEXT,
|
||||||
|
CHECK (ended_at_utc IS NULL OR ended_at_utc >= started_at_utc)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX idx_one_active_live_run_per_show
|
||||||
|
ON live_usage_runs(show_id) WHERE ended_at_utc IS NULL;
|
||||||
|
CREATE INDEX idx_live_runs_usage ON live_usage_runs(usage_id, started_at_utc);
|
||||||
|
|
||||||
|
CREATE TABLE live_commands (
|
||||||
|
show_id TEXT NOT NULL REFERENCES shows(id) ON DELETE CASCADE,
|
||||||
|
command_id TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
result_revision INTEGER NOT NULL CHECK (result_revision >= 0),
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (show_id, command_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE presentation_access_tokens (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
show_id TEXT NOT NULL REFERENCES shows(id) ON DELETE CASCADE,
|
||||||
|
token_hash TEXT NOT NULL UNIQUE,
|
||||||
|
created_at_utc TEXT NOT NULL,
|
||||||
|
revoked_at_utc TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_presentation_tokens_show
|
||||||
|
ON presentation_access_tokens(show_id, revoked_at_utc);
|
||||||
|
|
||||||
|
UPDATE piece_usages SET status = 'open' WHERE status = 'current';
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
ALTER TABLE pieces ADD COLUMN presentation_mode TEXT NOT NULL DEFAULT 'text'
|
||||||
|
CHECK (presentation_mode IN ('text', 'link', 'video'));
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_source_position INTEGER;
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_title TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_description TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_image_url TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_site_name TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_provider TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_provider_id TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_title_manual INTEGER NOT NULL DEFAULT 0
|
||||||
|
CHECK (presentation_title_manual IN (0, 1));
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_description_manual INTEGER NOT NULL DEFAULT 0
|
||||||
|
CHECK (presentation_description_manual IN (0, 1));
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_image_manual INTEGER NOT NULL DEFAULT 0
|
||||||
|
CHECK (presentation_image_manual IN (0, 1));
|
||||||
|
ALTER TABLE pieces ADD COLUMN presentation_metadata_fetched_at_utc TEXT;
|
||||||
|
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_mode_snapshot TEXT NOT NULL DEFAULT 'text'
|
||||||
|
CHECK (presentation_mode_snapshot IN ('text', 'link', 'video'));
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_source_label_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_source_url_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_source_timecode_snapshot INTEGER;
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_title_meta_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_description_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_image_url_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_site_name_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_provider_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
|
ALTER TABLE piece_usages ADD COLUMN presentation_provider_id_snapshot TEXT NOT NULL DEFAULT '';
|
||||||
Generated
+2126
-15
File diff suppressed because it is too large.
Load diff
+16
-5
@@ -1,15 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "sendewerk",
|
"name": "sendewerk",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.0",
|
"version": "0.5.3",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=22.17 <25"
|
"node": ">=22.17 <25"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "npm run db:migrate && node --env-file-if-exists=.env ./node_modules/vite/bin/vite.js dev",
|
||||||
"build": "vite build",
|
"build": "node --env-file-if-exists=.env ./node_modules/vite/bin/vite.js build",
|
||||||
"preview": "vite preview",
|
"preview": "node --env-file-if-exists=.env ./node_modules/vite/bin/vite.js preview",
|
||||||
"start": "npm run db:migrate && node --env-file-if-exists=.env build",
|
"start": "npm run db:migrate && node --env-file-if-exists=.env build",
|
||||||
"setup": "npm run db:migrate && npm run db:seed",
|
"setup": "npm run db:migrate && npm run db:seed",
|
||||||
"db:migrate": "node --env-file-if-exists=.env scripts/migrate.mjs",
|
"db:migrate": "node --env-file-if-exists=.env scripts/migrate.mjs",
|
||||||
@@ -24,7 +24,17 @@
|
|||||||
"test:e2e": "playwright test"
|
"test:e2e": "playwright test"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"better-sqlite3": "^13.0.3"
|
"@node-rs/argon2": "^2.2.2",
|
||||||
|
"better-sqlite3": "^13.0.3",
|
||||||
|
"file-type": "^22.2.0",
|
||||||
|
"marked": "^18.1.1",
|
||||||
|
"metascraper": "^5.58.5",
|
||||||
|
"metascraper-description": "^5.58.4",
|
||||||
|
"metascraper-image": "^5.58.4",
|
||||||
|
"metascraper-publisher": "^5.58.4",
|
||||||
|
"metascraper-title": "^5.58.4",
|
||||||
|
"nodemailer": "^10.1.7",
|
||||||
|
"sanitize-html": "^2.18.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
@@ -34,6 +44,7 @@
|
|||||||
"@sveltejs/vite-plugin-svelte": "^7.2.0",
|
"@sveltejs/vite-plugin-svelte": "^7.2.0",
|
||||||
"@types/better-sqlite3": "^7.6.13",
|
"@types/better-sqlite3": "^7.6.13",
|
||||||
"@types/node": "^22.18.13",
|
"@types/node": "^22.18.13",
|
||||||
|
"@types/sanitize-html": "^2.16.2",
|
||||||
"eslint": "^10.4.1",
|
"eslint": "^10.4.1",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-svelte": "^3.19.0",
|
"eslint-plugin-svelte": "^3.19.0",
|
||||||
|
|||||||
+10
-1
@@ -3,7 +3,11 @@ import { mkdtempSync } from 'node:fs';
|
|||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
|
||||||
const dataDirectory = mkdtempSync(path.join(tmpdir(), 'sendewerk-e2e-'));
|
const dataDirectory =
|
||||||
|
process.env.SENDEWERK_E2E_DATA_DIR || mkdtempSync(path.join(tmpdir(), 'sendewerk-e2e-'));
|
||||||
|
const mailOutboxDirectory = path.join(dataDirectory, 'mail-outbox');
|
||||||
|
process.env.SENDEWERK_E2E_DATA_DIR = dataDirectory;
|
||||||
|
process.env.SENDEWERK_E2E_OUTBOX_DIR = mailOutboxDirectory;
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
testDir: 'tests',
|
testDir: 'tests',
|
||||||
@@ -18,6 +22,11 @@ export default defineConfig({
|
|||||||
env: {
|
env: {
|
||||||
SENDEWERK_DB_PATH: path.join(dataDirectory, 'e2e.sqlite'),
|
SENDEWERK_DB_PATH: path.join(dataDirectory, 'e2e.sqlite'),
|
||||||
SENDEWERK_UPLOAD_DIR: path.join(dataDirectory, 'uploads'),
|
SENDEWERK_UPLOAD_DIR: path.join(dataDirectory, 'uploads'),
|
||||||
|
SENDEWERK_MAIL_OUTBOX_DIR: mailOutboxDirectory,
|
||||||
|
SENDEWERK_MAIL_TRANSPORT: 'local',
|
||||||
|
SENDEWERK_APP_ORIGIN: 'http://127.0.0.1:4173',
|
||||||
|
SENDEWERK_SETUP_TOKEN: 'e2e-only-setup-token-32-characters',
|
||||||
|
ORIGIN: 'http://127.0.0.1:4173',
|
||||||
HOST: '127.0.0.1',
|
HOST: '127.0.0.1',
|
||||||
PORT: '4173'
|
PORT: '4173'
|
||||||
}
|
}
|
||||||
|
|||||||
+161
-10
@@ -124,9 +124,49 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
'Pixel als bewusste Entscheidung.',
|
'Pixel als bewusste Entscheidung.',
|
||||||
timestamp,
|
timestamp,
|
||||||
timestamp
|
timestamp
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'piece-inbox-link',
|
||||||
|
'Indie-Showcase nachhören',
|
||||||
|
'Ein Fundstück aus dem letzten Showcase, das noch eingeordnet werden muss.',
|
||||||
|
'format-find',
|
||||||
|
'inbox',
|
||||||
|
0,
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
timestamp,
|
||||||
|
timestamp
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'piece-archive-demo',
|
||||||
|
'Controller mit eingebautem Bildschirm',
|
||||||
|
'Ein früheres Fundstück, das bewusst im Archiv liegt.',
|
||||||
|
'format-find',
|
||||||
|
'archived',
|
||||||
|
300,
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
timestamp,
|
||||||
|
timestamp
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
database
|
||||||
|
.prepare('UPDATE pieces SET research_text = ? WHERE id = ?')
|
||||||
|
.run(
|
||||||
|
'## Recherche\n\n- Herstellerangaben gegen unabhängige Tests prüfen\n- Fokus auf Bedienidee statt Leistungsdaten',
|
||||||
|
'piece-console'
|
||||||
|
);
|
||||||
|
database
|
||||||
|
.prepare('UPDATE pieces SET presentation_text = ? WHERE id = ?')
|
||||||
|
.run(
|
||||||
|
'## Weniger Leistung, mehr Idee\n\nDie Kurbel ist Teil des Spiels, nicht nur Dekoration.',
|
||||||
|
'piece-console'
|
||||||
|
);
|
||||||
|
|
||||||
database.prepare('DELETE FROM piece_topics WHERE piece_id LIKE ?').run('piece-%');
|
database.prepare('DELETE FROM piece_topics WHERE piece_id LIKE ?').run('piece-%');
|
||||||
const addTopic = database.prepare(
|
const addTopic = database.prepare(
|
||||||
@@ -137,7 +177,9 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
['piece-effects', 'topic-film'],
|
['piece-effects', 'topic-film'],
|
||||||
['piece-quiz', 'topic-gaming'],
|
['piece-quiz', 'topic-gaming'],
|
||||||
['piece-pixels', 'topic-gaming'],
|
['piece-pixels', 'topic-gaming'],
|
||||||
['piece-pixels', 'topic-internet']
|
['piece-pixels', 'topic-internet'],
|
||||||
|
['piece-inbox-link', 'topic-gaming'],
|
||||||
|
['piece-archive-demo', 'topic-gaming']
|
||||||
])
|
])
|
||||||
addTopic.run(...values);
|
addTopic.run(...values);
|
||||||
|
|
||||||
@@ -149,7 +191,9 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
['piece-console', 'cat-jc'],
|
['piece-console', 'cat-jc'],
|
||||||
['piece-effects', 'cat-reaction'],
|
['piece-effects', 'cat-reaction'],
|
||||||
['piece-quiz', 'cat-jc'],
|
['piece-quiz', 'cat-jc'],
|
||||||
['piece-pixels', 'cat-reaction']
|
['piece-pixels', 'cat-reaction'],
|
||||||
|
['piece-inbox-link', 'cat-reaction'],
|
||||||
|
['piece-archive-demo', 'cat-reaction']
|
||||||
])
|
])
|
||||||
addCategory.run(...values);
|
addCategory.run(...values);
|
||||||
|
|
||||||
@@ -173,7 +217,47 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
95,
|
95,
|
||||||
0
|
0
|
||||||
],
|
],
|
||||||
['source-pixels', 'piece-pixels', 'Galerie', 'https://example.com/pixels', null, 0]
|
['source-pixels', 'piece-pixels', 'Galerie', 'https://example.com/pixels', null, 0],
|
||||||
|
[
|
||||||
|
'source-inbox-showcase',
|
||||||
|
'piece-inbox-link',
|
||||||
|
'Showcase-Aufzeichnung',
|
||||||
|
'https://example.com/showcase',
|
||||||
|
120,
|
||||||
|
0
|
||||||
|
]
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
replace(
|
||||||
|
'show_templates',
|
||||||
|
['id', 'name', 'description'],
|
||||||
|
[
|
||||||
|
['template-default', 'Standardablauf', 'Start, zwei JC-Blöcke und zwei Spiele.'],
|
||||||
|
['template-games', 'Spieleabend', 'Ein ruhiger Einstieg und drei flexible Spieleblöcke.']
|
||||||
|
]
|
||||||
|
);
|
||||||
|
replace(
|
||||||
|
'show_template_sections',
|
||||||
|
['id', 'template_id', 'name', 'category_id', 'position', 'explicit_duration_seconds'],
|
||||||
|
[
|
||||||
|
['template-default-start', 'template-default', 'Start', 'cat-jc', 0, 300],
|
||||||
|
[
|
||||||
|
'template-default-jc-reaction',
|
||||||
|
'template-default',
|
||||||
|
'JC / Reaction',
|
||||||
|
'cat-reaction',
|
||||||
|
1,
|
||||||
|
null
|
||||||
|
],
|
||||||
|
['template-default-game-1', 'template-default', 'Spiel 1', 'cat-game', 2, 3600],
|
||||||
|
['template-default-jc', 'template-default', 'JC', 'cat-jc', 3, null],
|
||||||
|
['template-default-game-2', 'template-default', 'Spiel 2', 'cat-game', 4, 3600],
|
||||||
|
['template-games-start', 'template-games', 'Start', 'cat-jc', 0, 300],
|
||||||
|
['template-games-game-1', 'template-games', 'Spiel 1', 'cat-game', 1, 2700],
|
||||||
|
['template-games-break', 'template-games', 'Pause & Chat', 'cat-jc', 2, 600],
|
||||||
|
['template-games-game-2', 'template-games', 'Spiel 2', 'cat-game', 3, 2700],
|
||||||
|
['template-games-game-3', 'template-games', 'Spiel 3', 'cat-game', 4, 2700]
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -186,6 +270,7 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
'twitch_title',
|
'twitch_title',
|
||||||
'announcement_text',
|
'announcement_text',
|
||||||
'status',
|
'status',
|
||||||
|
'revision',
|
||||||
'created_at_utc',
|
'created_at_utc',
|
||||||
'updated_at_utc'
|
'updated_at_utc'
|
||||||
],
|
],
|
||||||
@@ -197,6 +282,18 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
'Kleine Welten, große Ideen | heinzlive',
|
'Kleine Welten, große Ideen | heinzlive',
|
||||||
'Heute schauen wir auf Hardware mit Kurbel, handgemachte Filmtricks und Pixel mit Haltung.',
|
'Heute schauen wir auf Hardware mit Kurbel, handgemachte Filmtricks und Pixel mit Haltung.',
|
||||||
'ready',
|
'ready',
|
||||||
|
1,
|
||||||
|
timestamp,
|
||||||
|
timestamp
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'show-games-evening',
|
||||||
|
'Spieleabend: Kurbeln & Pixel',
|
||||||
|
'2026-10-16T18:00:00.000Z',
|
||||||
|
'Kurbeln, Pixel und ein langer Spieleabend | heinzlive',
|
||||||
|
'Heute spielen wir uns von ungewöhnlicher Hardware bis zu moderner Pixelart.',
|
||||||
|
'draft',
|
||||||
|
1,
|
||||||
timestamp,
|
timestamp,
|
||||||
timestamp
|
timestamp
|
||||||
]
|
]
|
||||||
@@ -205,11 +302,25 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
|
|
||||||
replace(
|
replace(
|
||||||
'show_sections',
|
'show_sections',
|
||||||
['id', 'show_id', 'name', 'category_id', 'position', 'explicit_duration_seconds'],
|
|
||||||
[
|
[
|
||||||
['section-start', 'show-october', 'Ankommen & Warmwerden', 'cat-jc', 0, 300],
|
'id',
|
||||||
['section-stories', 'show-october', 'Kleine Welten', 'cat-reaction', 1, null],
|
'show_id',
|
||||||
['section-game', 'show-october', 'Spiel 1', 'cat-game', 2, 3600]
|
'name',
|
||||||
|
'category_id',
|
||||||
|
'position',
|
||||||
|
'explicit_duration_seconds',
|
||||||
|
'is_reserve_bank'
|
||||||
|
],
|
||||||
|
[
|
||||||
|
['section-start', 'show-october', 'Ankommen & Warmwerden', 'cat-jc', 0, 300, 0],
|
||||||
|
['section-stories', 'show-october', 'Kleine Welten', 'cat-reaction', 1, null, 0],
|
||||||
|
['section-game', 'show-october', 'Spiel 1', 'cat-game', 2, 3600, 0],
|
||||||
|
['reserve-bank-show-october', 'show-october', 'Reservebank', null, 3, null, 1],
|
||||||
|
['games-start', 'show-games-evening', 'Start', 'cat-jc', 0, 300, 0],
|
||||||
|
['games-first', 'show-games-evening', 'Spiel 1', 'cat-game', 1, 2700, 0],
|
||||||
|
['games-chat', 'show-games-evening', 'Pause & Chat', 'cat-jc', 2, 600, 0],
|
||||||
|
['games-second', 'show-games-evening', 'Spiel 2', 'cat-game', 3, 2700, 0],
|
||||||
|
['reserve-bank-show-games-evening', 'show-games-evening', 'Reservebank', null, 4, null, 1]
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -224,9 +335,11 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
'duration_seconds',
|
'duration_seconds',
|
||||||
'title_snapshot',
|
'title_snapshot',
|
||||||
'intro_snapshot',
|
'intro_snapshot',
|
||||||
|
'research_snapshot',
|
||||||
'moderation_snapshot',
|
'moderation_snapshot',
|
||||||
'transition_snapshot',
|
'transition_snapshot',
|
||||||
'presentation_snapshot',
|
'presentation_snapshot',
|
||||||
|
'own_notes',
|
||||||
'is_reserve'
|
'is_reserve'
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
@@ -235,13 +348,15 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
'section-stories',
|
'section-stories',
|
||||||
'piece-console',
|
'piece-console',
|
||||||
0,
|
0,
|
||||||
'current',
|
'open',
|
||||||
480,
|
480,
|
||||||
'Die kleine Konsole mit dem großen Dreh',
|
'Die kleine Konsole mit dem großen Dreh',
|
||||||
'Eine Kurbel, ein gelber Knopf und sehr viel Charme: Was macht kleine Hardware spannend?',
|
'Eine Kurbel, ein gelber Knopf und sehr viel Charme: Was macht kleine Hardware spannend?',
|
||||||
|
'## Recherche\n\n- Herstellerangaben gegen unabhängige Tests prüfen\n- Fokus auf Bedienidee statt Leistungsdaten',
|
||||||
'Erst Formfaktor zeigen, dann über bewusst gesetzte Grenzen sprechen.',
|
'Erst Formfaktor zeigen, dann über bewusst gesetzte Grenzen sprechen.',
|
||||||
'Von der kleinen Konsole geht es zur ganz großen Leinwand.',
|
'Von der kleinen Konsole geht es zur ganz großen Leinwand.',
|
||||||
'Weniger Leistung, mehr Idee.',
|
'Weniger Leistung, mehr Idee.',
|
||||||
|
'',
|
||||||
0
|
0
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
@@ -253,24 +368,60 @@ export function seed(databasePath = getPaths().database) {
|
|||||||
720,
|
720,
|
||||||
'Warum praktische Effekte wieder auffallen',
|
'Warum praktische Effekte wieder auffallen',
|
||||||
'Man sieht manchmal gerade deshalb weniger Trick, weil wieder mehr vor der Kamera passiert.',
|
'Man sieht manchmal gerade deshalb weniger Trick, weil wieder mehr vor der Kamera passiert.',
|
||||||
|
'',
|
||||||
'Beispiele vergleichen, nicht analog gegen digital ausspielen.',
|
'Beispiele vergleichen, nicht analog gegen digital ausspielen.',
|
||||||
'Nach so viel Handarbeit wird es spielerisch.',
|
'Nach so viel Handarbeit wird es spielerisch.',
|
||||||
'Wenn das Licht wirklich auf ein Modell fällt.',
|
'Wenn das Licht wirklich auf ein Modell fällt.',
|
||||||
|
'',
|
||||||
0
|
0
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
'usage-reserve',
|
'usage-reserve',
|
||||||
'section-stories',
|
'reserve-bank-show-october',
|
||||||
'piece-pixels',
|
'piece-pixels',
|
||||||
2,
|
0,
|
||||||
'open',
|
'open',
|
||||||
540,
|
540,
|
||||||
'Pixelart, die nicht nostalgisch sein will',
|
'Pixelart, die nicht nostalgisch sein will',
|
||||||
'Pixel sind längst keine technische Notlösung mehr.',
|
'Pixel sind längst keine technische Notlösung mehr.',
|
||||||
|
'',
|
||||||
'Großaufnahmen vorbereiten, drei Stilmittel benennen.',
|
'Großaufnahmen vorbereiten, drei Stilmittel benennen.',
|
||||||
'Genug Theorie, jetzt spielen wir selbst.',
|
'Genug Theorie, jetzt spielen wir selbst.',
|
||||||
'Pixel als bewusste Entscheidung.',
|
'Pixel als bewusste Entscheidung.',
|
||||||
|
'Ersatz, falls ein Spiel technisch ausfällt.',
|
||||||
1
|
1
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'usage-games-console',
|
||||||
|
'games-first',
|
||||||
|
'piece-console',
|
||||||
|
0,
|
||||||
|
'open',
|
||||||
|
480,
|
||||||
|
'Die kleine Konsole mit dem großen Dreh',
|
||||||
|
'Wir beginnen mit Hardware, die ihr Spielprinzip gleich mitbringt.',
|
||||||
|
'Kurbelmechanik und verfügbare Spiele prüfen.',
|
||||||
|
'Konsole zeigen und Publikum nach Lieblingsmechaniken fragen.',
|
||||||
|
'Danach wechseln wir von Mechanik zu Grafik.',
|
||||||
|
'Eine Kurbel verändert, wie wir spielen.',
|
||||||
|
'Controller vor Sendungsbeginn laden.',
|
||||||
|
0
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'usage-games-pixels',
|
||||||
|
'games-second',
|
||||||
|
'piece-pixels',
|
||||||
|
0,
|
||||||
|
'open',
|
||||||
|
540,
|
||||||
|
'Pixelart, die nicht nostalgisch sein will',
|
||||||
|
'Unser zweites Spiel nutzt Pixel nicht als Rückblick.',
|
||||||
|
'Drei aktuelle Beispiele vergleichen.',
|
||||||
|
'Auf Licht, Bewegung und Materialwirkung achten.',
|
||||||
|
'Zum Schluss sammeln wir eure Empfehlungen.',
|
||||||
|
'Pixel als bewusste Entscheidung.',
|
||||||
|
'',
|
||||||
|
0
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|||||||
+3628
-233
File diff suppressed because it is too large.
Load diff
Vendored
+11
-1
@@ -1,5 +1,15 @@
|
|||||||
|
import type { AuthUser } from '#lib/server/auth.js';
|
||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
namespace App {}
|
namespace App {
|
||||||
|
interface Locals {
|
||||||
|
user: AuthUser | null;
|
||||||
|
}
|
||||||
|
interface PageData {
|
||||||
|
user?: AuthUser | null;
|
||||||
|
presentationMode?: boolean;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import type { Handle } from '@sveltejs/kit/hooks';
|
||||||
|
import { deleteSession, getSessionUser, hasUsers, SESSION_COOKIE } from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
const publicPaths = new Set([
|
||||||
|
'/',
|
||||||
|
'/healthz',
|
||||||
|
'/login',
|
||||||
|
'/setup',
|
||||||
|
'/einladung',
|
||||||
|
'/passwort-vergessen',
|
||||||
|
'/passwort-zuruecksetzen'
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const handle: Handle = async ({ event, resolve }) => {
|
||||||
|
const presentationPath = event.url.pathname.startsWith('/heinzlive/');
|
||||||
|
const presentationTestPath = /^\/fundus\/[^/]+\/praesentation(?:\/|$)/.test(event.url.pathname);
|
||||||
|
const token = event.cookies.get(SESSION_COOKIE);
|
||||||
|
event.locals.user = getSessionUser(token);
|
||||||
|
if (token && !event.locals.user) deleteSession(event.cookies);
|
||||||
|
|
||||||
|
if (!presentationPath && !publicPaths.has(event.url.pathname) && !event.locals.user) {
|
||||||
|
redirect(303, hasUsers() ? '/login' : '/setup');
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await resolve(event);
|
||||||
|
response.headers.set('Referrer-Policy', 'same-origin');
|
||||||
|
response.headers.set('X-Content-Type-Options', 'nosniff');
|
||||||
|
response.headers.set('X-Frame-Options', 'DENY');
|
||||||
|
if (presentationPath || presentationTestPath) {
|
||||||
|
response.headers.set('Cache-Control', 'no-store');
|
||||||
|
response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||||
|
response.headers.set(
|
||||||
|
'Content-Security-Policy',
|
||||||
|
"frame-src https://www.youtube-nocookie.com https://www.youtube.com https://www.tiktok.com; frame-ancestors 'none'"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (event.url.pathname === '/einladung' || event.url.pathname === '/passwort-zuruecksetzen') {
|
||||||
|
response.headers.set('Cache-Control', 'no-store');
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
};
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { tick } from 'svelte';
|
||||||
|
|
||||||
|
let {
|
||||||
|
name,
|
||||||
|
label,
|
||||||
|
value = $bindable(),
|
||||||
|
rows = 7,
|
||||||
|
placeholder = '',
|
||||||
|
privateField = false,
|
||||||
|
form
|
||||||
|
}: {
|
||||||
|
name: string;
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
rows?: number;
|
||||||
|
placeholder?: string;
|
||||||
|
privateField?: boolean;
|
||||||
|
form?: string;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
let textarea: HTMLTextAreaElement;
|
||||||
|
|
||||||
|
async function replaceSelection(before: string, after = before, fallback = 'Text') {
|
||||||
|
const start = textarea.selectionStart;
|
||||||
|
const end = textarea.selectionEnd;
|
||||||
|
const selected = value.slice(start, end) || fallback;
|
||||||
|
value = `${value.slice(0, start)}${before}${selected}${after}${value.slice(end)}`;
|
||||||
|
await tick();
|
||||||
|
textarea.focus();
|
||||||
|
textarea.setSelectionRange(start + before.length, start + before.length + selected.length);
|
||||||
|
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addList() {
|
||||||
|
const start = textarea.selectionStart;
|
||||||
|
const end = textarea.selectionEnd;
|
||||||
|
const selected = value.slice(start, end) || 'Stichpunkt';
|
||||||
|
const replacement = selected
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => `- ${line}`)
|
||||||
|
.join('\n');
|
||||||
|
value = `${value.slice(0, start)}${replacement}${value.slice(end)}`;
|
||||||
|
await tick();
|
||||||
|
textarea.focus();
|
||||||
|
textarea.setSelectionRange(start + 2, start + replacement.length);
|
||||||
|
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class:private-field={privateField} class="markdown-editor-field">
|
||||||
|
<div class="markdown-editor-heading">
|
||||||
|
<span
|
||||||
|
>{label}{#if privateField}<small>Nur intern</small>{/if}</span
|
||||||
|
>
|
||||||
|
<span class="markdown-toolbar" role="toolbar" aria-label={`${label} formatieren`}>
|
||||||
|
<button type="button" aria-label="Fett" title="Fett" onclick={() => replaceSelection('**')}
|
||||||
|
><strong>B</strong></button
|
||||||
|
>
|
||||||
|
<button type="button" aria-label="Kursiv" title="Kursiv" onclick={() => replaceSelection('_')}
|
||||||
|
><em>I</em></button
|
||||||
|
>
|
||||||
|
<button type="button" aria-label="Liste" title="Liste" onclick={addList}>• Liste</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Link"
|
||||||
|
title="Link"
|
||||||
|
onclick={() => replaceSelection('[', '](https://)', 'Linktext')}>↗ Link</button
|
||||||
|
>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
bind:this={textarea}
|
||||||
|
aria-label={label}
|
||||||
|
{name}
|
||||||
|
{rows}
|
||||||
|
{placeholder}
|
||||||
|
{form}
|
||||||
|
maxlength="50000"
|
||||||
|
bind:value></textarea>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
let { html }: { html: string } = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- html is produced exclusively by the allowlist sanitizer in $lib/server/markdown.ts. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
<div class="markdown-preview">{@html html}</div>
|
||||||
@@ -16,6 +16,8 @@
|
|||||||
<path
|
<path
|
||||||
d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6 7 7M17 17l1.4 1.4M18.4 5.6 17 7M7 17l-1.4 1.4"
|
d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6 7 7M17 17l1.4 1.4M18.4 5.6 17 7M7 17l-1.4 1.4"
|
||||||
/>
|
/>
|
||||||
|
{:else if name === 'edit'}
|
||||||
|
<path d="M4 20h4L19 9l-4-4L4 16v4zM13.5 6.5l4 4" />
|
||||||
{/if}
|
{/if}
|
||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { tick, type Snippet } from 'svelte';
|
||||||
|
|
||||||
|
let {
|
||||||
|
labelledby,
|
||||||
|
activeSection = $bindable(),
|
||||||
|
onrequestclose,
|
||||||
|
header,
|
||||||
|
children,
|
||||||
|
footer
|
||||||
|
}: {
|
||||||
|
labelledby: string;
|
||||||
|
activeSection: 'script' | 'research' | 'presentation';
|
||||||
|
onrequestclose: () => void;
|
||||||
|
header: Snippet;
|
||||||
|
children: Snippet;
|
||||||
|
footer: Snippet;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
let dialog: HTMLDialogElement;
|
||||||
|
let workspace: HTMLDivElement;
|
||||||
|
const scrollPositions = { script: 0, research: 0, presentation: 0 };
|
||||||
|
|
||||||
|
async function selectSection(section: typeof activeSection) {
|
||||||
|
scrollPositions[activeSection] = workspace.scrollTop;
|
||||||
|
activeSection = section;
|
||||||
|
await tick();
|
||||||
|
workspace.scrollTop = scrollPositions[section];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function showModal() {
|
||||||
|
if (!dialog.open) dialog.showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function close() {
|
||||||
|
dialog.close();
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<dialog
|
||||||
|
bind:this={dialog}
|
||||||
|
class="piece-editor-dialog"
|
||||||
|
aria-labelledby={labelledby}
|
||||||
|
oncancel={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
onrequestclose();
|
||||||
|
}}
|
||||||
|
onclick={(event) => event.target === dialog && onrequestclose()}
|
||||||
|
>
|
||||||
|
<header class="piece-dialog-header">
|
||||||
|
<div class="piece-dialog-heading">{@render header()}</div>
|
||||||
|
<button
|
||||||
|
class="dialog-close"
|
||||||
|
type="button"
|
||||||
|
aria-label="Editor schließen"
|
||||||
|
onclick={onrequestclose}>×</button
|
||||||
|
>
|
||||||
|
</header>
|
||||||
|
<nav class="piece-dialog-tabs" aria-label="Editorbereiche">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class:active={activeSection === 'script'}
|
||||||
|
aria-current={activeSection === 'script' ? 'page' : undefined}
|
||||||
|
onclick={() => selectSection('script')}>Sendungstext</button
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class:active={activeSection === 'research'}
|
||||||
|
aria-current={activeSection === 'research' ? 'page' : undefined}
|
||||||
|
onclick={() => selectSection('research')}>Recherche & Quellen</button
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class:active={activeSection === 'presentation'}
|
||||||
|
aria-current={activeSection === 'presentation' ? 'page' : undefined}
|
||||||
|
onclick={() => selectSection('presentation')}>Präsentation</button
|
||||||
|
>
|
||||||
|
</nav>
|
||||||
|
<div bind:this={workspace} class="piece-dialog-workspace">{@render children()}</div>
|
||||||
|
<footer class="piece-dialog-footer">{@render footer()}</footer>
|
||||||
|
</dialog>
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import type { SentPieceUsage } from '#lib/server/shows.js';
|
||||||
|
|
||||||
|
let { history }: { history: SentPieceUsage[] } = $props();
|
||||||
|
|
||||||
|
function berlinDate(value: string) {
|
||||||
|
return new Intl.DateTimeFormat('de-DE', {
|
||||||
|
timeZone: 'Europe/Berlin',
|
||||||
|
dateStyle: 'medium'
|
||||||
|
}).format(new Date(value));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if history.length}
|
||||||
|
<div class="piece-usage-history">
|
||||||
|
<p>
|
||||||
|
<strong>Gesendet am {berlinDate(history[0].usedAtUtc)}</strong>
|
||||||
|
in <a href={resolve('/sendungen/[id]', { id: history[0].showId })}>{history[0].showTitle}</a>
|
||||||
|
{#if history.length > 1}<span>+ {history.length - 1} weitere</span>{/if}
|
||||||
|
</p>
|
||||||
|
{#if history.length > 1}
|
||||||
|
<details>
|
||||||
|
<summary>Vollständige Verwendungshistorie</summary>
|
||||||
|
<ul>
|
||||||
|
{#each history as usage (usage.usageId)}
|
||||||
|
<li>
|
||||||
|
<time datetime={usage.usedAtUtc}>{berlinDate(usage.usedAtUtc)}</time>
|
||||||
|
<a href={resolve('/sendungen/[id]', { id: usage.showId })}>{usage.showTitle}</a>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import type { PresentationContent } from '#lib/server/presentation.js';
|
||||||
|
|
||||||
|
let {
|
||||||
|
content,
|
||||||
|
imageSrc = ''
|
||||||
|
}: {
|
||||||
|
content: PresentationContent & {
|
||||||
|
sources?: { label: string; url: string }[];
|
||||||
|
images?: { id: string; altText: string }[];
|
||||||
|
};
|
||||||
|
imageSrc?: string;
|
||||||
|
} = $props();
|
||||||
|
let frame = $state<HTMLIFrameElement>();
|
||||||
|
let playerUnavailable = $state(false);
|
||||||
|
let imageUnavailable = $state(false);
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const receive = (event: MessageEvent) => {
|
||||||
|
if (content.provider !== 'tiktok' || event.origin !== 'https://www.tiktok.com') return;
|
||||||
|
if (event.source !== frame?.contentWindow || typeof event.data !== 'object' || !event.data)
|
||||||
|
return;
|
||||||
|
const message = event.data as { type?: string; value?: unknown };
|
||||||
|
if (message.type === 'onPlayerReady' && content.source?.timecodeSeconds) {
|
||||||
|
frame.contentWindow?.postMessage(
|
||||||
|
{
|
||||||
|
type: 'seekTo',
|
||||||
|
value: content.source.timecodeSeconds,
|
||||||
|
'x-tiktok-player': true
|
||||||
|
},
|
||||||
|
'https://www.tiktok.com'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (message.type === 'onPlayerError') playerUnavailable = true;
|
||||||
|
};
|
||||||
|
addEventListener('message', receive);
|
||||||
|
return () => removeEventListener('message', receive);
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if content.mode === 'text'}
|
||||||
|
<article class="output-content output-text">
|
||||||
|
<p class="output-kicker">heinzlive</p>
|
||||||
|
<h1>{content.title}</h1>
|
||||||
|
<!-- HTML is produced exclusively by the server-side allowlist sanitizer. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
<div class="output-copy">{@html content.html}</div>
|
||||||
|
{#if content.images?.length}<div class="output-images">
|
||||||
|
{#each content.images as image (image.id)}
|
||||||
|
<img src={`${imageSrc}/${image.id}`} alt={image.altText} />
|
||||||
|
{/each}
|
||||||
|
</div>{/if}
|
||||||
|
{#if content.sources?.length}<footer class="output-sources">
|
||||||
|
<span>Quellen</span>
|
||||||
|
{#each content.sources as source, index (`${index}-${source.url}`)}
|
||||||
|
<!-- The URL is a server-validated external HTTP(S) source. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-navigation-without-resolve -->
|
||||||
|
<a href={source.url} target="_blank" rel="noopener noreferrer">{source.label}</a>
|
||||||
|
{/each}
|
||||||
|
</footer>{/if}
|
||||||
|
</article>
|
||||||
|
{:else if content.mode === 'link'}
|
||||||
|
<article class="output-content output-link-card">
|
||||||
|
{#if imageSrc && !imageUnavailable}<div class="output-link-image">
|
||||||
|
<img src={imageSrc} alt="" onerror={() => (imageUnavailable = true)} />
|
||||||
|
</div>{/if}
|
||||||
|
<div class="output-link-copy">
|
||||||
|
<p class="output-kicker">{content.siteName || content.source?.label || 'Webseite'}</p>
|
||||||
|
<h1>{content.previewTitle || content.title}</h1>
|
||||||
|
{#if content.description}<p>{content.description}</p>{/if}
|
||||||
|
<!-- The URL is a server-validated external HTTP(S) source. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-navigation-without-resolve -->
|
||||||
|
{#if content.source}<a href={content.source.url} target="_blank" rel="noopener noreferrer"
|
||||||
|
>Original öffnen</a
|
||||||
|
>{/if}
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
{:else}
|
||||||
|
<article class:portrait={content.provider === 'tiktok'} class="output-content output-video">
|
||||||
|
<header>
|
||||||
|
<p class="output-kicker">{content.siteName || content.source?.label || 'Video'}</p>
|
||||||
|
<h1>{content.previewTitle || content.title}</h1>
|
||||||
|
</header>
|
||||||
|
{#if content.embedUrl && !playerUnavailable}
|
||||||
|
<div class="output-player">
|
||||||
|
<iframe
|
||||||
|
bind:this={frame}
|
||||||
|
title={content.previewTitle || content.title}
|
||||||
|
src={content.embedUrl}
|
||||||
|
allow="encrypted-media; fullscreen; picture-in-picture"
|
||||||
|
allowfullscreen
|
||||||
|
onerror={() => (playerUnavailable = true)}
|
||||||
|
></iframe>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<section class="output-fallback">
|
||||||
|
<strong>Video kann nicht eingebettet werden</strong>
|
||||||
|
<p>Der Anbieter oder diese URL ist für die eingebettete Wiedergabe nicht verfügbar.</p>
|
||||||
|
<!-- The URL is a server-validated external HTTP(S) source. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-navigation-without-resolve -->
|
||||||
|
{#if content.source}<a href={content.source.url} target="_blank" rel="noopener noreferrer"
|
||||||
|
>Original öffnen</a
|
||||||
|
>{/if}
|
||||||
|
</section>
|
||||||
|
{/if}
|
||||||
|
{#if content.source}<footer class="output-video-source">
|
||||||
|
<!-- The URL is a server-validated external HTTP(S) source. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-navigation-without-resolve -->
|
||||||
|
<a href={content.source.url} target="_blank" rel="noopener noreferrer">Original öffnen</a>
|
||||||
|
</footer>{/if}
|
||||||
|
</article>
|
||||||
|
{/if}
|
||||||
@@ -2,12 +2,13 @@
|
|||||||
let { area }: { area: string } = $props();
|
let { area }: { area: string } = $props();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<aside class="preview-notice" aria-label="Hinweis zur Gestaltungsvorschau">
|
<details class="preview-notice">
|
||||||
<span class="preview-dot" aria-hidden="true"></span>
|
<summary>
|
||||||
<div>
|
<span class="preview-dot" aria-hidden="true"></span>
|
||||||
<strong>Gestaltungsvorschau: {area}</strong>
|
<strong>Vorschau · {area}</strong>
|
||||||
<p>
|
<span class="preview-chevron" aria-hidden="true">⌄</span>
|
||||||
In Etappe 1 schreibgeschützt. Die gezeigten Inhalte stammen aus der lokalen SQLite-Datenbank.
|
</summary>
|
||||||
</p>
|
<p>
|
||||||
</div>
|
Diese Ansicht ist schreibgeschützt. Bearbeiten und Speichern folgen in einer späteren Etappe.
|
||||||
</aside>
|
</p>
|
||||||
|
</details>
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { enhance, type SubmitFunction } from '$app/forms';
|
||||||
|
import { untrack } from 'svelte';
|
||||||
|
import MarkdownEditorField from './MarkdownEditorField.svelte';
|
||||||
|
import NavIcon from './NavIcon.svelte';
|
||||||
|
import PieceEditorDialog from './PieceEditorDialog.svelte';
|
||||||
|
import type { PieceUsage } from '#lib/server/shows.js';
|
||||||
|
|
||||||
|
let {
|
||||||
|
usage,
|
||||||
|
revision,
|
||||||
|
sectionId,
|
||||||
|
sections,
|
||||||
|
error,
|
||||||
|
enhanceCommand
|
||||||
|
}: {
|
||||||
|
usage: PieceUsage;
|
||||||
|
revision: number;
|
||||||
|
sectionId: string;
|
||||||
|
sections: { id: string; name: string }[];
|
||||||
|
error?: string;
|
||||||
|
enhanceCommand: SubmitFunction;
|
||||||
|
} = $props();
|
||||||
|
|
||||||
|
let formId = $derived(`usage-editor-form-${usage.id}`);
|
||||||
|
let editor: { showModal: () => void; close: () => void };
|
||||||
|
let activeSection = $state<'script' | 'research' | 'presentation'>('script');
|
||||||
|
let draft = $state(untrack(() => ({ ...usage })));
|
||||||
|
let dirty = $state(false);
|
||||||
|
|
||||||
|
function durationInMinutes(seconds: number) {
|
||||||
|
return Number((seconds / 60).toFixed(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestClose() {
|
||||||
|
if (dirty && !confirm('Ungespeicherte Änderungen verwerfen und Editor schließen?')) return;
|
||||||
|
dirty = false;
|
||||||
|
editor.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
const enhanceEditor: SubmitFunction = async (input) => {
|
||||||
|
const finish = await enhanceCommand(input);
|
||||||
|
return async (result) => {
|
||||||
|
if (finish) await finish(result);
|
||||||
|
if (result.result.type === 'success') dirty = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<button
|
||||||
|
class="usage-edit-button"
|
||||||
|
type="button"
|
||||||
|
aria-label={`${usage.title} bearbeiten und verschieben`}
|
||||||
|
title="Bearbeiten und verschieben"
|
||||||
|
onclick={() => editor.showModal()}
|
||||||
|
>
|
||||||
|
<NavIcon name="edit" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<PieceEditorDialog
|
||||||
|
bind:this={editor}
|
||||||
|
bind:activeSection
|
||||||
|
labelledby={`usage-editor-title-${usage.id}`}
|
||||||
|
onrequestclose={requestClose}
|
||||||
|
>
|
||||||
|
{#snippet header()}
|
||||||
|
<p class="eyebrow">Verwendung in dieser Sendung</p>
|
||||||
|
<label class="piece-dialog-title">
|
||||||
|
<span class="sr-only">Titel</span>
|
||||||
|
<textarea
|
||||||
|
form={formId}
|
||||||
|
name="title"
|
||||||
|
required
|
||||||
|
rows="1"
|
||||||
|
maxlength="200"
|
||||||
|
aria-label="Titel"
|
||||||
|
bind:value={draft.title}
|
||||||
|
oninput={() => (dirty = true)}></textarea>
|
||||||
|
</label>
|
||||||
|
<h2 class="sr-only" id={`usage-editor-title-${usage.id}`}>{draft.title}</h2>
|
||||||
|
<small>Änderungen gelten nur für diese Einplanung.</small>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<form
|
||||||
|
id={formId}
|
||||||
|
use:enhance={enhanceEditor}
|
||||||
|
method="POST"
|
||||||
|
action="?/updateUsage"
|
||||||
|
class="piece-dialog-form"
|
||||||
|
oninput={() => (dirty = true)}
|
||||||
|
onchange={() => (dirty = true)}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
|
||||||
|
<section class="piece-editor-panel" hidden={activeSection !== 'script'}>
|
||||||
|
<div class="piece-panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Für die Moderation</p>
|
||||||
|
<h3>Sendungstext</h3>
|
||||||
|
</div>
|
||||||
|
<small>Die drei Teile bleiben getrennt gespeichert.</small>
|
||||||
|
</div>
|
||||||
|
<div class="piece-writing-stack">
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="intro"
|
||||||
|
label="Einleitung"
|
||||||
|
placeholder="Wie beginnt dieses Thema in der Sendung?"
|
||||||
|
bind:value={draft.intro}
|
||||||
|
/>
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="moderation"
|
||||||
|
label="Moderationsstichpunkte"
|
||||||
|
placeholder="Argumente, Fragen und Ablaufpunkte"
|
||||||
|
rows={10}
|
||||||
|
bind:value={draft.moderation}
|
||||||
|
/>
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="transition"
|
||||||
|
label="Überleitung"
|
||||||
|
placeholder="Wie geht es zum nächsten Thema weiter?"
|
||||||
|
bind:value={draft.transition}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<details class="piece-meta-details">
|
||||||
|
<summary>Dauer und Einplanung</summary>
|
||||||
|
<div class="piece-meta-grid">
|
||||||
|
<label
|
||||||
|
>Dauer in Minuten<input
|
||||||
|
name="durationMinutes"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
max="1440"
|
||||||
|
step="any"
|
||||||
|
value={durationInMinutes(usage.durationSeconds)}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="piece-editor-panel" hidden={activeSection !== 'research'}>
|
||||||
|
<div class="piece-panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Nicht öffentlich</p>
|
||||||
|
<h3>Recherche & Quellen</h3>
|
||||||
|
</div>
|
||||||
|
<small>Diese Inhalte bleiben innerhalb der Redaktion.</small>
|
||||||
|
</div>
|
||||||
|
<div class="piece-writing-stack">
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="research"
|
||||||
|
label="Private Recherche"
|
||||||
|
placeholder="Hintergrund, Prüfung und offene Fragen"
|
||||||
|
rows={10}
|
||||||
|
privateField
|
||||||
|
bind:value={draft.research}
|
||||||
|
/>
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="ownNotes"
|
||||||
|
label="Interne Notizen zu dieser Verwendung"
|
||||||
|
placeholder="Absprachen und Hinweise nur für diese Sendung"
|
||||||
|
privateField
|
||||||
|
bind:value={draft.ownNotes}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<section class="piece-source-summary">
|
||||||
|
<p class="eyebrow">Snapshot-Quelle</p>
|
||||||
|
{#if draft.presentationSourceUrl}
|
||||||
|
<strong>{draft.presentationSourceLabel || draft.presentationSourceUrl}</strong>
|
||||||
|
<small>{draft.presentationSourceUrl}</small>
|
||||||
|
{:else}
|
||||||
|
<p>Für diese Verwendung wurde keine Präsentationsquelle kopiert.</p>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="piece-editor-panel" hidden={activeSection !== 'presentation'}>
|
||||||
|
<div class="piece-panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Öffentliche Ausgabe</p>
|
||||||
|
<h3>Präsentation</h3>
|
||||||
|
</div>
|
||||||
|
<small>Private Recherche und Notizen werden nicht ausgegeben.</small>
|
||||||
|
</div>
|
||||||
|
<div class="piece-presentation-layout">
|
||||||
|
<div class="piece-presentation-controls">
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="presentation"
|
||||||
|
label="Öffentlicher Text"
|
||||||
|
placeholder="Text für die Publikumsausgabe"
|
||||||
|
bind:value={draft.presentation}
|
||||||
|
/>
|
||||||
|
<div class="presentation-mode-picker" role="group" aria-label="Darstellung">
|
||||||
|
{#each [['text', 'Text'], ['link', 'Linkvorschau'], ['video', 'Video']] as mode (mode[0])}
|
||||||
|
<label
|
||||||
|
><input
|
||||||
|
type="radio"
|
||||||
|
name="presentationMode"
|
||||||
|
value={mode[0]}
|
||||||
|
bind:group={draft.presentationMode}
|
||||||
|
/>{mode[1]}</label
|
||||||
|
>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationSourceLabel"
|
||||||
|
value={draft.presentationSourceLabel}
|
||||||
|
/>
|
||||||
|
<input type="hidden" name="presentationSourceUrl" value={draft.presentationSourceUrl} />
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationSourceTimecodeSeconds"
|
||||||
|
value={draft.presentationSourceTimecodeSeconds ?? ''}
|
||||||
|
/>
|
||||||
|
<input type="hidden" name="presentationSiteName" value={draft.presentationSiteName} />
|
||||||
|
{#if draft.presentationMode !== 'text'}
|
||||||
|
<div class="presentation-settings">
|
||||||
|
<div class="presentation-source-summary wide-field">
|
||||||
|
<span>Ausgewählte Quelle</span>
|
||||||
|
<strong
|
||||||
|
>{draft.presentationSourceLabel ||
|
||||||
|
draft.presentationSourceUrl ||
|
||||||
|
'Keine Quelle'}</strong
|
||||||
|
>
|
||||||
|
{#if draft.presentationSourceUrl}<small>{draft.presentationSourceUrl}</small>{/if}
|
||||||
|
</div>
|
||||||
|
<label
|
||||||
|
>Titel<input
|
||||||
|
name="presentationTitle"
|
||||||
|
maxlength="300"
|
||||||
|
bind:value={draft.presentationTitle}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Bild-URL<input
|
||||||
|
name="presentationImageUrl"
|
||||||
|
type="url"
|
||||||
|
maxlength="2000"
|
||||||
|
bind:value={draft.presentationImageUrl}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label class="wide-field"
|
||||||
|
>Anreißer<textarea
|
||||||
|
name="presentationDescription"
|
||||||
|
rows="3"
|
||||||
|
maxlength="1000"
|
||||||
|
bind:value={draft.presentationDescription}></textarea></label
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<input type="hidden" name="presentationTitle" value={draft.presentationTitle} />
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationDescription"
|
||||||
|
value={draft.presentationDescription}
|
||||||
|
/>
|
||||||
|
<input type="hidden" name="presentationImageUrl" value={draft.presentationImageUrl} />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<aside class="piece-presentation-preview" aria-label="Präsentationsvorschau">
|
||||||
|
<p class="output-kicker">Vorschau · {draft.presentationMode}</p>
|
||||||
|
<h4>{draft.presentationTitle || draft.title}</h4>
|
||||||
|
{#if draft.presentationMode === 'text'}
|
||||||
|
<p class="preview-markdown-source">
|
||||||
|
{draft.presentation || 'Noch kein öffentlicher Text.'}
|
||||||
|
</p>
|
||||||
|
{:else}
|
||||||
|
{#if draft.presentationImageUrl}<img src={draft.presentationImageUrl} alt="" />{/if}
|
||||||
|
<p>
|
||||||
|
{draft.presentationDescription ||
|
||||||
|
draft.presentationSourceUrl ||
|
||||||
|
'Noch keine Vorschauangaben.'}
|
||||||
|
</p>
|
||||||
|
{/if}
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{#snippet footer()}
|
||||||
|
<div class="piece-dialog-secondary-actions">
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/refreshUsage">
|
||||||
|
<input type="hidden" name="revision" value={revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<button class="text-button" type="submit" disabled={!usage.originalPieceId || dirty}
|
||||||
|
>Aus Fundus aktualisieren</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/duplicateUsage">
|
||||||
|
<input type="hidden" name="revision" value={revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/>
|
||||||
|
<button class="text-button" type="submit" disabled={dirty}>Duplizieren</button>
|
||||||
|
</form>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/moveUsage">
|
||||||
|
<input type="hidden" name="revision" value={revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/><input type="hidden" name="position" value="9999" />
|
||||||
|
<label
|
||||||
|
><span class="sr-only">Ziel</span><select name="sectionId"
|
||||||
|
><option value="">Reservebank</option>{#each sections as target (target.id)}<option
|
||||||
|
value={target.id}
|
||||||
|
selected={target.id === sectionId}>{target.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<button class="text-button" type="submit" disabled={dirty}>Verschieben</button>
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/removeUsage"
|
||||||
|
onsubmit={(event) =>
|
||||||
|
!confirm('Verwendung aus der Sendung entfernen?') && event.preventDefault()}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/>
|
||||||
|
<button class="text-button danger-text" type="submit" disabled={dirty}>Entfernen</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="piece-dialog-primary-action">
|
||||||
|
{#if error}<span class="problem" role="alert">{error}</span>{/if}
|
||||||
|
<button class="primary-button" type="submit" form={formId}>Verwendung speichern</button>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</PieceEditorDialog>
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
import Database from 'better-sqlite3';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { readFileSync, readdirSync, mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import type { Cookies } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
const temporaryDirectories: string[] = [];
|
||||||
|
let directory: string;
|
||||||
|
let databasePath: string;
|
||||||
|
|
||||||
|
function testCookies(): Cookies {
|
||||||
|
const values = new Map<string, string>();
|
||||||
|
return {
|
||||||
|
get: (name: string) => values.get(name),
|
||||||
|
getAll: () => Array.from(values, ([name, value]) => ({ name, value })),
|
||||||
|
set: (name: string, value: string) => {
|
||||||
|
values.set(name, value);
|
||||||
|
},
|
||||||
|
delete: (name: string) => {
|
||||||
|
values.delete(name);
|
||||||
|
},
|
||||||
|
serialize: () => ''
|
||||||
|
} as unknown as Cookies;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenFromLatestMail(): string {
|
||||||
|
const outbox = path.join(directory, 'outbox');
|
||||||
|
const files = readdirSync(outbox).sort();
|
||||||
|
const message = JSON.parse(readFileSync(path.join(outbox, files.at(-1)!), 'utf8')) as {
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
const match = message.text.match(/[?&]token=([^\s]+)/);
|
||||||
|
if (!match) throw new Error('Testmail enthält keinen Token.');
|
||||||
|
return decodeURIComponent(match[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
directory = mkdtempSync(path.join(tmpdir(), 'sendewerk-auth-test-'));
|
||||||
|
temporaryDirectories.push(directory);
|
||||||
|
databasePath = path.join(directory, 'test.sqlite');
|
||||||
|
process.env.SENDEWERK_DB_PATH = databasePath;
|
||||||
|
process.env.SENDEWERK_UPLOAD_DIR = path.join(directory, 'uploads');
|
||||||
|
process.env.SENDEWERK_MAIL_OUTBOX_DIR = path.join(directory, 'outbox');
|
||||||
|
process.env.SENDEWERK_MAIL_TRANSPORT = 'local';
|
||||||
|
process.env.SENDEWERK_APP_ORIGIN = 'http://localhost:5173';
|
||||||
|
process.env.SENDEWERK_SETUP_TOKEN = 'a'.repeat(32);
|
||||||
|
execFileSync(process.execPath, ['scripts/migrate.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
const { closeDatabase } = await import('./database.js');
|
||||||
|
closeDatabase();
|
||||||
|
for (const name of [
|
||||||
|
'SENDEWERK_DB_PATH',
|
||||||
|
'SENDEWERK_UPLOAD_DIR',
|
||||||
|
'SENDEWERK_MAIL_OUTBOX_DIR',
|
||||||
|
'SENDEWERK_MAIL_TRANSPORT',
|
||||||
|
'SENDEWERK_MAIL_FROM',
|
||||||
|
'SENDEWERK_SMTP_HOST',
|
||||||
|
'SENDEWERK_APP_ORIGIN',
|
||||||
|
'SENDEWERK_SETUP_TOKEN'
|
||||||
|
]) {
|
||||||
|
delete process.env[name];
|
||||||
|
}
|
||||||
|
for (const temporaryDirectory of temporaryDirectories.splice(0)) {
|
||||||
|
rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('authentication', () => {
|
||||||
|
it('creates the first Barkeeper once and stores no plaintext secret', async () => {
|
||||||
|
const { createFirstAdmin } = await import('./auth.js');
|
||||||
|
const password = 'Ein-sehr-langes-Testpasswort';
|
||||||
|
const user = await createFirstAdmin({
|
||||||
|
setupToken: 'a'.repeat(32),
|
||||||
|
email: 'Bar@example.org',
|
||||||
|
displayName: 'Erster Barkeeper',
|
||||||
|
password
|
||||||
|
});
|
||||||
|
const database = new Database(databasePath, { readonly: true });
|
||||||
|
const row = database.prepare('SELECT * FROM users').get() as {
|
||||||
|
role: string;
|
||||||
|
email_normalized: string;
|
||||||
|
password_hash: string;
|
||||||
|
};
|
||||||
|
database.close();
|
||||||
|
|
||||||
|
expect(user.role).toBe('barkeeper');
|
||||||
|
expect(row.email_normalized).toBe('bar@example.org');
|
||||||
|
expect(row.password_hash).not.toContain(password);
|
||||||
|
await expect(
|
||||||
|
createFirstAdmin({
|
||||||
|
setupToken: 'a'.repeat(32),
|
||||||
|
email: 'second@example.org',
|
||||||
|
displayName: 'Zweiter Admin',
|
||||||
|
password
|
||||||
|
})
|
||||||
|
).rejects.toThrow('SETUP_CLOSED');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts an invitation only once and rejects an expired invitation', async () => {
|
||||||
|
const { acceptInvitation, createFirstAdmin, inviteUser } = await import('./auth.js');
|
||||||
|
const admin = await createFirstAdmin({
|
||||||
|
setupToken: 'a'.repeat(32),
|
||||||
|
email: 'admin@example.org',
|
||||||
|
displayName: 'Admin',
|
||||||
|
password: 'Admin-Passwort-1234'
|
||||||
|
});
|
||||||
|
await inviteUser(admin, 'crew@example.org', 'thekencrew');
|
||||||
|
const firstToken = tokenFromLatestMail();
|
||||||
|
const crew = await acceptInvitation({
|
||||||
|
token: firstToken,
|
||||||
|
displayName: 'Crew',
|
||||||
|
password: 'Crew-Passwort-1234'
|
||||||
|
});
|
||||||
|
expect(crew.role).toBe('thekencrew');
|
||||||
|
await expect(
|
||||||
|
acceptInvitation({
|
||||||
|
token: firstToken,
|
||||||
|
displayName: 'Crew',
|
||||||
|
password: 'Crew-Passwort-1234'
|
||||||
|
})
|
||||||
|
).rejects.toThrow('TOKEN_INVALID');
|
||||||
|
|
||||||
|
await inviteUser(admin, 'late@example.org', 'thekencrew');
|
||||||
|
const expiredToken = tokenFromLatestMail();
|
||||||
|
const database = new Database(databasePath);
|
||||||
|
database.prepare("UPDATE invitations SET expires_at_utc = '2000-01-01T00:00:00.000Z'").run();
|
||||||
|
database.close();
|
||||||
|
await expect(
|
||||||
|
acceptInvitation({
|
||||||
|
token: expiredToken,
|
||||||
|
displayName: 'Zu spät',
|
||||||
|
password: 'Crew-Passwort-1234'
|
||||||
|
})
|
||||||
|
).rejects.toThrow('TOKEN_INVALID');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('revokes active sessions immediately when a user is locked', async () => {
|
||||||
|
const { createFirstAdmin, createSession, getSessionUser, setUserLocked, SESSION_COOKIE } =
|
||||||
|
await import('./auth.js');
|
||||||
|
const admin = await createFirstAdmin({
|
||||||
|
setupToken: 'a'.repeat(32),
|
||||||
|
email: 'admin@example.org',
|
||||||
|
displayName: 'Admin',
|
||||||
|
password: 'Admin-Passwort-1234'
|
||||||
|
});
|
||||||
|
const database = new Database(databasePath);
|
||||||
|
const crewId = crypto.randomUUID();
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (id, email, email_normalized, display_name, password_hash, role,
|
||||||
|
password_changed_at_utc, created_at_utc, updated_at_utc)
|
||||||
|
SELECT ?, 'crew@example.org', 'crew@example.org', 'Crew', password_hash, 'thekencrew',
|
||||||
|
password_changed_at_utc, created_at_utc, updated_at_utc FROM users WHERE id = ?`
|
||||||
|
)
|
||||||
|
.run(crewId, admin.id);
|
||||||
|
database.close();
|
||||||
|
const cookies = testCookies();
|
||||||
|
createSession(crewId, cookies);
|
||||||
|
const token = cookies.get(SESSION_COOKIE);
|
||||||
|
expect(getSessionUser(token)?.id).toBe(crewId);
|
||||||
|
|
||||||
|
setUserLocked(admin, crewId, true);
|
||||||
|
expect(getSessionUser(token)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses password reset links once and invalidates prior sessions', async () => {
|
||||||
|
const {
|
||||||
|
authenticate,
|
||||||
|
createFirstAdmin,
|
||||||
|
createSession,
|
||||||
|
getSessionUser,
|
||||||
|
requestPasswordReset,
|
||||||
|
resetPassword,
|
||||||
|
SESSION_COOKIE
|
||||||
|
} = await import('./auth.js');
|
||||||
|
const admin = await createFirstAdmin({
|
||||||
|
setupToken: 'a'.repeat(32),
|
||||||
|
email: 'admin@example.org',
|
||||||
|
displayName: 'Admin',
|
||||||
|
password: 'Altes-Passwort-1234'
|
||||||
|
});
|
||||||
|
const cookies = testCookies();
|
||||||
|
createSession(admin.id, cookies);
|
||||||
|
const sessionToken = cookies.get(SESSION_COOKIE);
|
||||||
|
await requestPasswordReset(admin.email);
|
||||||
|
const expiredToken = tokenFromLatestMail();
|
||||||
|
const database = new Database(databasePath);
|
||||||
|
database
|
||||||
|
.prepare("UPDATE password_reset_tokens SET expires_at_utc = '2000-01-01T00:00:00.000Z'")
|
||||||
|
.run();
|
||||||
|
database.close();
|
||||||
|
await expect(resetPassword(expiredToken, 'Neues-Passwort-1234')).rejects.toThrow(
|
||||||
|
'TOKEN_INVALID'
|
||||||
|
);
|
||||||
|
await requestPasswordReset(admin.email);
|
||||||
|
const resetToken = tokenFromLatestMail();
|
||||||
|
await resetPassword(resetToken, 'Neues-Passwort-1234');
|
||||||
|
|
||||||
|
expect(getSessionUser(sessionToken)).toBeNull();
|
||||||
|
expect(await authenticate(admin.email, 'Altes-Passwort-1234')).toBeNull();
|
||||||
|
expect(await authenticate(admin.email, 'Neues-Passwort-1234')).not.toBeNull();
|
||||||
|
await expect(resetPassword(resetToken, 'Noch-ein-Passwort-1234')).rejects.toThrow(
|
||||||
|
'TOKEN_INVALID'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rate limits repeated failed login attempts without locking the account', async () => {
|
||||||
|
const { authenticate, createFirstAdmin, loginIsRateLimited, reserveLoginAttempt } =
|
||||||
|
await import('./auth.js');
|
||||||
|
await createFirstAdmin({
|
||||||
|
setupToken: 'a'.repeat(32),
|
||||||
|
email: 'admin@example.org',
|
||||||
|
displayName: 'Admin',
|
||||||
|
password: 'Admin-Passwort-1234'
|
||||||
|
});
|
||||||
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||||
|
expect(reserveLoginAttempt('admin@example.org', '127.0.0.1')).toBe(true);
|
||||||
|
expect(await authenticate('admin@example.org', 'falsch')).toBeNull();
|
||||||
|
}
|
||||||
|
expect(loginIsRateLimited('admin@example.org', '127.0.0.1')).toBe(true);
|
||||||
|
const database = new Database(databasePath, { readonly: true });
|
||||||
|
const user = database.prepare('SELECT locked_at_utc FROM users').get() as {
|
||||||
|
locked_at_utc: string | null;
|
||||||
|
};
|
||||||
|
database.close();
|
||||||
|
expect(user.locked_at_utc).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('denies administrative operations to Thekencrew', async () => {
|
||||||
|
const { requireBarkeeper } = await import('./auth.js');
|
||||||
|
expect(() =>
|
||||||
|
requireBarkeeper({
|
||||||
|
id: 'crew',
|
||||||
|
email: 'crew@example.org',
|
||||||
|
displayName: 'Crew',
|
||||||
|
role: 'thekencrew',
|
||||||
|
lockedAtUtc: null
|
||||||
|
})
|
||||||
|
).toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('never falls back to local delivery when SMTP was selected', async () => {
|
||||||
|
process.env.SENDEWERK_MAIL_TRANSPORT = 'smtp';
|
||||||
|
process.env.SENDEWERK_MAIL_FROM = '';
|
||||||
|
process.env.SENDEWERK_SMTP_HOST = '';
|
||||||
|
const { sendMail } = await import('./mail.js');
|
||||||
|
await expect(
|
||||||
|
sendMail({ to: 'test@example.org', subject: 'Test', text: 'Keine echte Nachricht' })
|
||||||
|
).rejects.toThrow('SMTP-Konfiguration');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,610 @@
|
|||||||
|
import { hash, verify } from '@node-rs/argon2';
|
||||||
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { Cookies } from '@sveltejs/kit';
|
||||||
|
import { getAuthConfig } from './config.js';
|
||||||
|
import { getDatabase } from './database.js';
|
||||||
|
import { sendMail } from './mail.js';
|
||||||
|
|
||||||
|
export const SESSION_COOKIE = 'sendewerk_session';
|
||||||
|
export const INVITATION_COOKIE = 'sendewerk_invitation';
|
||||||
|
export const RESET_COOKIE = 'sendewerk_password_reset';
|
||||||
|
const SESSION_DURATION_MS = 30 * 24 * 60 * 60 * 1000;
|
||||||
|
const LINK_DURATION_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const LOGIN_WINDOW_MS = 15 * 60 * 1000;
|
||||||
|
const EMAIL_ATTEMPT_LIMIT = 5;
|
||||||
|
const ADDRESS_ATTEMPT_LIMIT = 20;
|
||||||
|
const RESET_WINDOW_MS = 60 * 60 * 1000;
|
||||||
|
const RESET_EMAIL_LIMIT = 3;
|
||||||
|
const RESET_ADDRESS_LIMIT = 10;
|
||||||
|
const PASSWORD_OPTIONS = {
|
||||||
|
algorithm: 2,
|
||||||
|
memoryCost: 19_456,
|
||||||
|
timeCost: 2,
|
||||||
|
parallelism: 1,
|
||||||
|
outputLen: 32
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type Role = 'barkeeper' | 'thekencrew';
|
||||||
|
export type AuthUser = {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
displayName: string;
|
||||||
|
role: Role;
|
||||||
|
lockedAtUtc: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type UserRow = {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
display_name: string;
|
||||||
|
password_hash: string;
|
||||||
|
role: Role;
|
||||||
|
locked_at_utc: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type InvitationRow = {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
role: Role;
|
||||||
|
expires_at_utc: string;
|
||||||
|
accepted_at_utc: string | null;
|
||||||
|
revoked_at_utc: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
function toUser(row: UserRow): AuthUser {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
email: row.email,
|
||||||
|
displayName: row.display_name,
|
||||||
|
role: row.role,
|
||||||
|
lockedAtUtc: row.locked_at_utc
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeEmail(email: string): string {
|
||||||
|
return email.trim().toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validEmail(email: string): boolean {
|
||||||
|
return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validDisplayName(name: string): boolean {
|
||||||
|
return name.trim().length >= 2 && name.trim().length <= 80;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validPassword(password: string): boolean {
|
||||||
|
return password.length >= 12 && Buffer.byteLength(password, 'utf8') <= 256;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isRole(value: string): value is Role {
|
||||||
|
return value === 'barkeeper' || value === 'thekencrew';
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function hashPassword(password: string): Promise<string> {
|
||||||
|
return hash(password, PASSWORD_OPTIONS);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyPassword(passwordHash: string, password: string): Promise<boolean> {
|
||||||
|
return verify(passwordHash, password, PASSWORD_OPTIONS);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dummyPasswordHash = hashPassword(randomBytes(32).toString('hex'));
|
||||||
|
|
||||||
|
function createToken(): string {
|
||||||
|
return randomBytes(32).toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hashToken(token: string): string {
|
||||||
|
return createHash('sha256').update(token).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
function nowUtc(): string {
|
||||||
|
return new Date().toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function futureUtc(durationMs: number): string {
|
||||||
|
return new Date(Date.now() + durationMs).toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasUsers(): boolean {
|
||||||
|
const row = getDatabase().prepare('SELECT count(*) AS count FROM users').get() as {
|
||||||
|
count: number;
|
||||||
|
};
|
||||||
|
return row.count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setupIsConfigured(): boolean {
|
||||||
|
return getAuthConfig().setupToken.length >= 32;
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupTokenMatches(candidate: string): boolean {
|
||||||
|
const configured = getAuthConfig().setupToken;
|
||||||
|
if (configured.length < 32 || candidate.length !== configured.length) return false;
|
||||||
|
return timingSafeEqual(Buffer.from(candidate), Buffer.from(configured));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createFirstAdmin(input: {
|
||||||
|
setupToken: string;
|
||||||
|
email: string;
|
||||||
|
displayName: string;
|
||||||
|
password: string;
|
||||||
|
}): Promise<AuthUser> {
|
||||||
|
if (!setupTokenMatches(input.setupToken)) throw new Error('SETUP_TOKEN_INVALID');
|
||||||
|
const email = input.email.trim();
|
||||||
|
const emailNormalized = normalizeEmail(email);
|
||||||
|
const displayName = input.displayName.trim();
|
||||||
|
if (!validEmail(email) || !validDisplayName(displayName) || !validPassword(input.password)) {
|
||||||
|
throw new Error('VALIDATION');
|
||||||
|
}
|
||||||
|
const passwordHash = await hashPassword(input.password);
|
||||||
|
const database = getDatabase();
|
||||||
|
const create = database.transaction(() => {
|
||||||
|
const count = database.prepare('SELECT count(*) AS count FROM users').get() as {
|
||||||
|
count: number;
|
||||||
|
};
|
||||||
|
if (count.count !== 0) throw new Error('SETUP_CLOSED');
|
||||||
|
const id = randomUUID();
|
||||||
|
const timestamp = nowUtc();
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (
|
||||||
|
id, email, email_normalized, display_name, password_hash, role,
|
||||||
|
password_changed_at_utc, created_at_utc, updated_at_utc
|
||||||
|
) VALUES (?, ?, ?, ?, ?, 'barkeeper', ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(id, email, emailNormalized, displayName, passwordHash, timestamp, timestamp, timestamp);
|
||||||
|
return { id, email, displayName, role: 'barkeeper', lockedAtUtc: null } satisfies AuthUser;
|
||||||
|
});
|
||||||
|
return create();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sessionCookieOptions(expires?: Date) {
|
||||||
|
return {
|
||||||
|
path: '/',
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'lax' as const,
|
||||||
|
secure: getAuthConfig().secureCookies,
|
||||||
|
expires
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function linkCookieOptions() {
|
||||||
|
return {
|
||||||
|
path: '/',
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'strict' as const,
|
||||||
|
secure: getAuthConfig().secureCookies,
|
||||||
|
maxAge: 10 * 60
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function storeLinkToken(cookies: Cookies, name: string, token: string): void {
|
||||||
|
cookies.set(name, token, linkCookieOptions());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readLinkToken(cookies: Cookies, name: string): string {
|
||||||
|
return cookies.get(name) || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteLinkToken(cookies: Cookies, name: string): void {
|
||||||
|
cookies.delete(name, { ...linkCookieOptions(), maxAge: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createSession(userId: string, cookies: Cookies): void {
|
||||||
|
const token = createToken();
|
||||||
|
const expires = new Date(Date.now() + SESSION_DURATION_MS);
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
'INSERT INTO sessions (token_hash, user_id, created_at_utc, expires_at_utc) VALUES (?, ?, ?, ?)'
|
||||||
|
)
|
||||||
|
.run(hashToken(token), userId, nowUtc(), expires.toISOString());
|
||||||
|
cookies.set(SESSION_COOKIE, token, sessionCookieOptions(expires));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteSession(cookies: Cookies): void {
|
||||||
|
const token = cookies.get(SESSION_COOKIE);
|
||||||
|
if (token)
|
||||||
|
getDatabase().prepare('DELETE FROM sessions WHERE token_hash = ?').run(hashToken(token));
|
||||||
|
cookies.delete(SESSION_COOKIE, sessionCookieOptions());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSessionUser(token: string | undefined): AuthUser | null {
|
||||||
|
if (!token) return null;
|
||||||
|
const database = getDatabase();
|
||||||
|
const row = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.id, u.email, u.display_name, u.password_hash, u.role, u.locked_at_utc
|
||||||
|
FROM sessions s
|
||||||
|
JOIN users u ON u.id = s.user_id
|
||||||
|
WHERE s.token_hash = ? AND s.expires_at_utc > ? AND u.locked_at_utc IS NULL`
|
||||||
|
)
|
||||||
|
.get(hashToken(token), nowUtc()) as UserRow | undefined;
|
||||||
|
if (!row) return null;
|
||||||
|
return toUser(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
function rateKey(value: string): string {
|
||||||
|
return hashToken(value || 'unknown');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loginIsRateLimited(email: string, address: string): boolean {
|
||||||
|
const database = getDatabase();
|
||||||
|
const since = new Date(Date.now() - LOGIN_WINDOW_MS).toISOString();
|
||||||
|
database.prepare('DELETE FROM login_attempts WHERE attempted_at_utc < ?').run(since);
|
||||||
|
const emailCount = database
|
||||||
|
.prepare(
|
||||||
|
'SELECT count(*) AS count FROM login_attempts WHERE email_key = ? AND attempted_at_utc >= ?'
|
||||||
|
)
|
||||||
|
.get(rateKey(normalizeEmail(email)), since) as { count: number };
|
||||||
|
const addressCount = database
|
||||||
|
.prepare(
|
||||||
|
'SELECT count(*) AS count FROM login_attempts WHERE address_key = ? AND attempted_at_utc >= ?'
|
||||||
|
)
|
||||||
|
.get(rateKey(address), since) as { count: number };
|
||||||
|
return emailCount.count >= EMAIL_ATTEMPT_LIMIT || addressCount.count >= ADDRESS_ATTEMPT_LIMIT;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reserveLoginAttempt(email: string, address: string): boolean {
|
||||||
|
const database = getDatabase();
|
||||||
|
const reserve = database.transaction(() => {
|
||||||
|
if (loginIsRateLimited(email, address)) return false;
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
'INSERT INTO login_attempts (id, email_key, address_key, attempted_at_utc) VALUES (?, ?, ?, ?)'
|
||||||
|
)
|
||||||
|
.run(randomUUID(), rateKey(normalizeEmail(email)), rateKey(address), nowUtc());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return reserve();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function authenticate(email: string, password: string): Promise<AuthUser | null> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const normalized = normalizeEmail(email);
|
||||||
|
const row = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, email, display_name, password_hash, role, locked_at_utc
|
||||||
|
FROM users WHERE email_normalized = ?`
|
||||||
|
)
|
||||||
|
.get(normalized) as UserRow | undefined;
|
||||||
|
const matches = row
|
||||||
|
? await verifyPassword(row.password_hash, password)
|
||||||
|
: await verifyPassword(await dummyPasswordHash, password);
|
||||||
|
if (!row || !matches || row.locked_at_utc) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
database.prepare('DELETE FROM login_attempts WHERE email_key = ?').run(rateKey(normalized));
|
||||||
|
return toUser(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireUser(user: AuthUser | null): AuthUser {
|
||||||
|
if (!user) error(401, 'Anmeldung erforderlich');
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function requireBarkeeper(user: AuthUser | null): AuthUser {
|
||||||
|
const authenticated = requireUser(user);
|
||||||
|
if (authenticated.role !== 'barkeeper') error(403, 'Diese Aktion erfordert Barkeeper-Rechte.');
|
||||||
|
return authenticated;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireCurrentBarkeeper(actor: AuthUser): AuthUser {
|
||||||
|
const row = getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, email, display_name, password_hash, role, locked_at_utc
|
||||||
|
FROM users WHERE id = ? AND role = 'barkeeper' AND locked_at_utc IS NULL`
|
||||||
|
)
|
||||||
|
.get(actor.id) as UserRow | undefined;
|
||||||
|
if (!row) error(403, 'Diese Aktion erfordert aktive Barkeeper-Rechte.');
|
||||||
|
return toUser(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listUsers(): AuthUser[] {
|
||||||
|
const rows = getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, email, display_name, password_hash, role, locked_at_utc
|
||||||
|
FROM users ORDER BY display_name COLLATE NOCASE`
|
||||||
|
)
|
||||||
|
.all() as UserRow[];
|
||||||
|
return rows.map(toUser);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listOpenInvitations() {
|
||||||
|
return getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, email, role, expires_at_utc
|
||||||
|
FROM invitations
|
||||||
|
WHERE accepted_at_utc IS NULL AND revoked_at_utc IS NULL AND expires_at_utc > ?
|
||||||
|
ORDER BY created_at_utc DESC`
|
||||||
|
)
|
||||||
|
.all(nowUtc()) as Array<{ id: string; email: string; role: Role; expires_at_utc: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function inviteUser(
|
||||||
|
actor: AuthUser,
|
||||||
|
emailValue: string,
|
||||||
|
role: Role
|
||||||
|
): Promise<'local' | 'smtp'> {
|
||||||
|
actor = requireCurrentBarkeeper(actor);
|
||||||
|
const email = emailValue.trim();
|
||||||
|
const normalized = normalizeEmail(email);
|
||||||
|
if (!validEmail(email) || !isRole(role)) throw new Error('VALIDATION');
|
||||||
|
const database = getDatabase();
|
||||||
|
if (database.prepare('SELECT 1 FROM users WHERE email_normalized = ?').get(normalized)) {
|
||||||
|
throw new Error('USER_EXISTS');
|
||||||
|
}
|
||||||
|
const token = createToken();
|
||||||
|
const id = randomUUID();
|
||||||
|
const timestamp = nowUtc();
|
||||||
|
const expiresAt = futureUtc(LINK_DURATION_MS);
|
||||||
|
const store = database.transaction(() => {
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE invitations SET revoked_at_utc = ?
|
||||||
|
WHERE email_normalized = ? AND accepted_at_utc IS NULL AND revoked_at_utc IS NULL`
|
||||||
|
)
|
||||||
|
.run(timestamp, normalized);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO invitations (
|
||||||
|
id, email, email_normalized, role, token_hash, created_by_user_id,
|
||||||
|
created_at_utc, expires_at_utc
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(id, email, normalized, role, hashToken(token), actor.id, timestamp, expiresAt);
|
||||||
|
});
|
||||||
|
store();
|
||||||
|
const link = new URL(
|
||||||
|
`/einladung?token=${encodeURIComponent(token)}`,
|
||||||
|
getAuthConfig().origin
|
||||||
|
).toString();
|
||||||
|
try {
|
||||||
|
return await sendMail({
|
||||||
|
to: email,
|
||||||
|
subject: 'Einladung zu Sendewerk',
|
||||||
|
text: `Du wurdest zu Sendewerk eingeladen. Der Link ist 24 Stunden gültig und einmalig nutzbar:\n\n${link}`
|
||||||
|
});
|
||||||
|
} catch (mailError) {
|
||||||
|
database.prepare('UPDATE invitations SET revoked_at_utc = ? WHERE id = ?').run(nowUtc(), id);
|
||||||
|
throw mailError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getInvitation(token: string): InvitationRow | null {
|
||||||
|
if (!token || token.length > 100) return null;
|
||||||
|
return (
|
||||||
|
(getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, email, role, expires_at_utc, accepted_at_utc, revoked_at_utc
|
||||||
|
FROM invitations WHERE token_hash = ?`
|
||||||
|
)
|
||||||
|
.get(hashToken(token)) as InvitationRow | undefined) ?? null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function acceptInvitation(input: {
|
||||||
|
token: string;
|
||||||
|
displayName: string;
|
||||||
|
password: string;
|
||||||
|
}): Promise<AuthUser> {
|
||||||
|
const invitation = getInvitation(input.token);
|
||||||
|
const displayName = input.displayName.trim();
|
||||||
|
if (
|
||||||
|
!invitation ||
|
||||||
|
invitation.accepted_at_utc ||
|
||||||
|
invitation.revoked_at_utc ||
|
||||||
|
invitation.expires_at_utc <= nowUtc()
|
||||||
|
) {
|
||||||
|
throw new Error('TOKEN_INVALID');
|
||||||
|
}
|
||||||
|
if (!validDisplayName(displayName) || !validPassword(input.password))
|
||||||
|
throw new Error('VALIDATION');
|
||||||
|
const passwordHash = await hashPassword(input.password);
|
||||||
|
const database = getDatabase();
|
||||||
|
const accept = database.transaction(() => {
|
||||||
|
const current = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, email, role, expires_at_utc, accepted_at_utc, revoked_at_utc
|
||||||
|
FROM invitations WHERE id = ?`
|
||||||
|
)
|
||||||
|
.get(invitation.id) as InvitationRow;
|
||||||
|
if (current.accepted_at_utc || current.revoked_at_utc || current.expires_at_utc <= nowUtc()) {
|
||||||
|
throw new Error('TOKEN_INVALID');
|
||||||
|
}
|
||||||
|
const id = randomUUID();
|
||||||
|
const timestamp = nowUtc();
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO users (
|
||||||
|
id, email, email_normalized, display_name, password_hash, role,
|
||||||
|
password_changed_at_utc, created_at_utc, updated_at_utc
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
id,
|
||||||
|
current.email,
|
||||||
|
normalizeEmail(current.email),
|
||||||
|
displayName,
|
||||||
|
passwordHash,
|
||||||
|
current.role,
|
||||||
|
timestamp,
|
||||||
|
timestamp,
|
||||||
|
timestamp
|
||||||
|
);
|
||||||
|
database
|
||||||
|
.prepare('UPDATE invitations SET accepted_at_utc = ? WHERE id = ?')
|
||||||
|
.run(timestamp, current.id);
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
email: current.email,
|
||||||
|
displayName,
|
||||||
|
role: current.role,
|
||||||
|
lockedAtUtc: null
|
||||||
|
} satisfies AuthUser;
|
||||||
|
});
|
||||||
|
return accept();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function reservePasswordResetRequest(email: string, address: string): boolean {
|
||||||
|
const database = getDatabase();
|
||||||
|
const since = new Date(Date.now() - RESET_WINDOW_MS).toISOString();
|
||||||
|
const emailKey = rateKey(`reset-email:${normalizeEmail(email)}`);
|
||||||
|
const addressKey = rateKey(`reset-address:${address}`);
|
||||||
|
const reserve = database.transaction(() => {
|
||||||
|
database.prepare('DELETE FROM login_attempts WHERE attempted_at_utc < ?').run(since);
|
||||||
|
const emailCount = database
|
||||||
|
.prepare(
|
||||||
|
'SELECT count(*) AS count FROM login_attempts WHERE email_key = ? AND attempted_at_utc >= ?'
|
||||||
|
)
|
||||||
|
.get(emailKey, since) as { count: number };
|
||||||
|
const addressCount = database
|
||||||
|
.prepare(
|
||||||
|
'SELECT count(*) AS count FROM login_attempts WHERE address_key = ? AND attempted_at_utc >= ?'
|
||||||
|
)
|
||||||
|
.get(addressKey, since) as { count: number };
|
||||||
|
if (emailCount.count >= RESET_EMAIL_LIMIT || addressCount.count >= RESET_ADDRESS_LIMIT)
|
||||||
|
return false;
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
'INSERT INTO login_attempts (id, email_key, address_key, attempted_at_utc) VALUES (?, ?, ?, ?)'
|
||||||
|
)
|
||||||
|
.run(randomUUID(), emailKey, addressKey, nowUtc());
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return reserve();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requestPasswordReset(emailValue: string): Promise<void> {
|
||||||
|
const normalized = normalizeEmail(emailValue);
|
||||||
|
const database = getDatabase();
|
||||||
|
const row = database
|
||||||
|
.prepare('SELECT id, email FROM users WHERE email_normalized = ?')
|
||||||
|
.get(normalized) as { id: string; email: string } | undefined;
|
||||||
|
if (!row) return;
|
||||||
|
const token = createToken();
|
||||||
|
const id = randomUUID();
|
||||||
|
const timestamp = nowUtc();
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO password_reset_tokens
|
||||||
|
(id, user_id, token_hash, created_at_utc, expires_at_utc)
|
||||||
|
VALUES (?, ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(id, row.id, hashToken(token), timestamp, futureUtc(LINK_DURATION_MS));
|
||||||
|
const link = new URL(
|
||||||
|
`/passwort-zuruecksetzen?token=${encodeURIComponent(token)}`,
|
||||||
|
getAuthConfig().origin
|
||||||
|
).toString();
|
||||||
|
try {
|
||||||
|
await sendMail({
|
||||||
|
to: row.email,
|
||||||
|
subject: 'Sendewerk-Passwort zurücksetzen',
|
||||||
|
text: `Mit diesem 24 Stunden gültigen, einmaligen Link kannst du dein Passwort zurücksetzen:\n\n${link}`
|
||||||
|
});
|
||||||
|
} catch (mailError) {
|
||||||
|
database.prepare('DELETE FROM password_reset_tokens WHERE id = ?').run(id);
|
||||||
|
throw mailError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function passwordResetIsValid(token: string): boolean {
|
||||||
|
if (!token || token.length > 100) return false;
|
||||||
|
return Boolean(
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`SELECT 1 FROM password_reset_tokens
|
||||||
|
WHERE token_hash = ? AND consumed_at_utc IS NULL AND expires_at_utc > ?`
|
||||||
|
)
|
||||||
|
.get(hashToken(token), nowUtc())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function resetPassword(token: string, password: string): Promise<void> {
|
||||||
|
if (!passwordResetIsValid(token)) throw new Error('TOKEN_INVALID');
|
||||||
|
if (!validPassword(password)) throw new Error('VALIDATION');
|
||||||
|
const passwordHash = await hashPassword(password);
|
||||||
|
const database = getDatabase();
|
||||||
|
const reset = database.transaction(() => {
|
||||||
|
const row = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, user_id FROM password_reset_tokens
|
||||||
|
WHERE token_hash = ? AND consumed_at_utc IS NULL AND expires_at_utc > ?`
|
||||||
|
)
|
||||||
|
.get(hashToken(token), nowUtc()) as { id: string; user_id: string } | undefined;
|
||||||
|
if (!row) throw new Error('TOKEN_INVALID');
|
||||||
|
const timestamp = nowUtc();
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE users SET password_hash = ?, password_changed_at_utc = ?, updated_at_utc = ?
|
||||||
|
WHERE id = ?`
|
||||||
|
)
|
||||||
|
.run(passwordHash, timestamp, timestamp, row.user_id);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
'UPDATE password_reset_tokens SET consumed_at_utc = ? WHERE user_id = ? AND consumed_at_utc IS NULL'
|
||||||
|
)
|
||||||
|
.run(timestamp, row.user_id);
|
||||||
|
database.prepare('DELETE FROM sessions WHERE user_id = ?').run(row.user_id);
|
||||||
|
});
|
||||||
|
reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
function activeBarkeeperCount(): number {
|
||||||
|
const row = getDatabase()
|
||||||
|
.prepare(
|
||||||
|
"SELECT count(*) AS count FROM users WHERE role = 'barkeeper' AND locked_at_utc IS NULL"
|
||||||
|
)
|
||||||
|
.get() as { count: number };
|
||||||
|
return row.count;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setUserLocked(actor: AuthUser, userId: string, locked: boolean): void {
|
||||||
|
actor = requireCurrentBarkeeper(actor);
|
||||||
|
const database = getDatabase();
|
||||||
|
const row = database.prepare('SELECT role, locked_at_utc FROM users WHERE id = ?').get(userId) as
|
||||||
|
{ role: Role; locked_at_utc: string | null } | undefined;
|
||||||
|
if (!row) throw new Error('NOT_FOUND');
|
||||||
|
if (locked && actor.id === userId) throw new Error('SELF_LOCK');
|
||||||
|
if (locked && row.role === 'barkeeper' && !row.locked_at_utc && activeBarkeeperCount() <= 1) {
|
||||||
|
throw new Error('LAST_BARKEEPER');
|
||||||
|
}
|
||||||
|
const update = database.transaction(() => {
|
||||||
|
database
|
||||||
|
.prepare('UPDATE users SET locked_at_utc = ?, updated_at_utc = ? WHERE id = ?')
|
||||||
|
.run(locked ? nowUtc() : null, nowUtc(), userId);
|
||||||
|
if (locked) database.prepare('DELETE FROM sessions WHERE user_id = ?').run(userId);
|
||||||
|
});
|
||||||
|
update();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setUserRole(actor: AuthUser, userId: string, role: Role): void {
|
||||||
|
requireCurrentBarkeeper(actor);
|
||||||
|
if (!isRole(role)) throw new Error('VALIDATION');
|
||||||
|
const database = getDatabase();
|
||||||
|
const row = database.prepare('SELECT role, locked_at_utc FROM users WHERE id = ?').get(userId) as
|
||||||
|
{ role: Role; locked_at_utc: string | null } | undefined;
|
||||||
|
if (!row) throw new Error('NOT_FOUND');
|
||||||
|
if (
|
||||||
|
row.role === 'barkeeper' &&
|
||||||
|
role === 'thekencrew' &&
|
||||||
|
!row.locked_at_utc &&
|
||||||
|
activeBarkeeperCount() <= 1
|
||||||
|
) {
|
||||||
|
throw new Error('LAST_BARKEEPER');
|
||||||
|
}
|
||||||
|
database
|
||||||
|
.prepare('UPDATE users SET role = ?, updated_at_utc = ? WHERE id = ?')
|
||||||
|
.run(role, nowUtc(), userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function revokeInvitation(actor: AuthUser, invitationId: string): void {
|
||||||
|
requireCurrentBarkeeper(actor);
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE invitations SET revoked_at_utc = ?
|
||||||
|
WHERE id = ? AND accepted_at_utc IS NULL AND revoked_at_utc IS NULL`
|
||||||
|
)
|
||||||
|
.run(nowUtc(), invitationId);
|
||||||
|
}
|
||||||
@@ -7,6 +7,38 @@ function configuredPath(value: string | undefined, fallback: string): string {
|
|||||||
export function getServerPaths() {
|
export function getServerPaths() {
|
||||||
return {
|
return {
|
||||||
database: configuredPath(process.env.SENDEWERK_DB_PATH, '.data/sendewerk.sqlite'),
|
database: configuredPath(process.env.SENDEWERK_DB_PATH, '.data/sendewerk.sqlite'),
|
||||||
uploads: configuredPath(process.env.SENDEWERK_UPLOAD_DIR, '.data/uploads')
|
uploads: configuredPath(process.env.SENDEWERK_UPLOAD_DIR, '.data/uploads'),
|
||||||
|
mailOutbox: configuredPath(process.env.SENDEWERK_MAIL_OUTBOX_DIR, '.data/mail-outbox')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getAuthConfig() {
|
||||||
|
const configuredOrigin = process.env.SENDEWERK_APP_ORIGIN || process.env.CLOUDRON_APP_ORIGIN;
|
||||||
|
if (process.env.NODE_ENV === 'production' && !configuredOrigin) {
|
||||||
|
throw new Error('SENDEWERK_APP_ORIGIN muss im Produktionsbetrieb gesetzt sein.');
|
||||||
|
}
|
||||||
|
const origin = new URL(configuredOrigin || 'http://localhost:5173');
|
||||||
|
return {
|
||||||
|
origin,
|
||||||
|
setupToken: process.env.SENDEWERK_SETUP_TOKEN || '',
|
||||||
|
secureCookies: origin.protocol === 'https:'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getMailConfig() {
|
||||||
|
const transport = process.env.SENDEWERK_MAIL_TRANSPORT || 'local';
|
||||||
|
if (transport !== 'local' && transport !== 'smtp') {
|
||||||
|
throw new Error('SENDEWERK_MAIL_TRANSPORT muss local oder smtp sein.');
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
transport,
|
||||||
|
from:
|
||||||
|
process.env.SENDEWERK_MAIL_FROM ||
|
||||||
|
(transport === 'local' ? 'Sendewerk <sendewerk@localhost>' : ''),
|
||||||
|
host: process.env.SENDEWERK_SMTP_HOST || '',
|
||||||
|
port: Number(process.env.SENDEWERK_SMTP_PORT || '587'),
|
||||||
|
secure: process.env.SENDEWERK_SMTP_SECURE === 'true',
|
||||||
|
user: process.env.SENDEWERK_SMTP_USER || '',
|
||||||
|
password: process.env.SENDEWERK_SMTP_PASSWORD || ''
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
createPiece,
|
||||||
|
createTaxonomy,
|
||||||
|
deletePieceImage,
|
||||||
|
deleteTaxonomy,
|
||||||
|
duplicatePiece,
|
||||||
|
getMediaFile,
|
||||||
|
getPiece,
|
||||||
|
getTaxonomy,
|
||||||
|
listPieces,
|
||||||
|
loadPiecePresentationMetadata,
|
||||||
|
savePiece,
|
||||||
|
setPieceArchived,
|
||||||
|
uploadPieceImage,
|
||||||
|
type PieceInput
|
||||||
|
} from './content.js';
|
||||||
|
import { closeDatabase } from './database.js';
|
||||||
|
import { renderMarkdown } from './markdown.js';
|
||||||
|
|
||||||
|
let directory: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
directory = mkdtempSync(path.join(tmpdir(), 'sendewerk-content-test-'));
|
||||||
|
process.env.SENDEWERK_DB_PATH = path.join(directory, 'test.sqlite');
|
||||||
|
process.env.SENDEWERK_UPLOAD_DIR = path.join(directory, 'uploads');
|
||||||
|
execFileSync(process.execPath, ['scripts/migrate.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
execFileSync(process.execPath, ['scripts/seed.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
closeDatabase();
|
||||||
|
delete process.env.SENDEWERK_DB_PATH;
|
||||||
|
delete process.env.SENDEWERK_UPLOAD_DIR;
|
||||||
|
rmSync(directory, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function completeInput(overrides: Partial<PieceInput> = {}): PieceInput {
|
||||||
|
return {
|
||||||
|
title: 'Getestetes Piece',
|
||||||
|
summary: 'Eine persistente Kurzbeschreibung.',
|
||||||
|
formatId: 'format-talk',
|
||||||
|
status: 'ready',
|
||||||
|
durationSeconds: 420,
|
||||||
|
intro: '**Starker Einstieg**',
|
||||||
|
researchText: 'Private Recherche',
|
||||||
|
moderationNotes: '- Punkt eins',
|
||||||
|
transitionText: 'Weiter geht es.',
|
||||||
|
presentationText: '## Sichtbare Aussage',
|
||||||
|
presentationMode: 'text',
|
||||||
|
presentationSourcePosition: null,
|
||||||
|
presentationTitle: '',
|
||||||
|
presentationDescription: '',
|
||||||
|
presentationImageUrl: '',
|
||||||
|
presentationSiteName: '',
|
||||||
|
presentationProvider: '',
|
||||||
|
presentationProviderId: '',
|
||||||
|
presentationTitleManual: false,
|
||||||
|
presentationDescriptionManual: false,
|
||||||
|
presentationImageManual: false,
|
||||||
|
presentationMetadataFetchedAtUtc: null,
|
||||||
|
topicIds: ['topic-gaming', 'topic-internet'],
|
||||||
|
categoryIds: ['cat-jc', 'cat-reaction'],
|
||||||
|
sources: [
|
||||||
|
{ label: 'Dokumentation', url: 'https://example.com/dokumentation', timecodeSeconds: 75 }
|
||||||
|
],
|
||||||
|
...overrides
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('content management', () => {
|
||||||
|
it('persists complete pieces and rejects stale revisions atomically', () => {
|
||||||
|
const id = createPiece('talk');
|
||||||
|
const initial = getPiece(id)!;
|
||||||
|
const saved = savePiece(id, initial.revision, completeInput());
|
||||||
|
const piece = getPiece(id)!;
|
||||||
|
|
||||||
|
expect(saved.revision).toBe(2);
|
||||||
|
expect(piece).toMatchObject({
|
||||||
|
title: 'Getestetes Piece',
|
||||||
|
status: 'ready',
|
||||||
|
researchText: 'Private Recherche',
|
||||||
|
topicIds: ['topic-gaming', 'topic-internet'],
|
||||||
|
categoryIds: ['cat-jc', 'cat-reaction']
|
||||||
|
});
|
||||||
|
expect(piece.sources).toEqual([
|
||||||
|
{ label: 'Dokumentation', url: 'https://example.com/dokumentation', timecodeSeconds: 75 }
|
||||||
|
]);
|
||||||
|
expect(() =>
|
||||||
|
savePiece(id, initial.revision, completeInput({ title: 'Veralteter Titel', topicIds: [] }))
|
||||||
|
).toThrow('CONFLICT');
|
||||||
|
expect(getPiece(id)).toMatchObject({
|
||||||
|
title: 'Getestetes Piece',
|
||||||
|
topicIds: ['topic-gaming', 'topic-internet']
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stores fetched preview metadata and preserves manual corrections on reload', async () => {
|
||||||
|
const id = createPiece('find');
|
||||||
|
const initial = getPiece(id)!;
|
||||||
|
const saved = savePiece(
|
||||||
|
id,
|
||||||
|
initial.revision,
|
||||||
|
completeInput({
|
||||||
|
presentationMode: 'link',
|
||||||
|
presentationSourcePosition: 0,
|
||||||
|
presentationTitle: 'Manueller Titel',
|
||||||
|
presentationTitleManual: true
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const loaded = await loadPiecePresentationMetadata(id, saved.revision, async () => ({
|
||||||
|
title: 'Automatischer Titel',
|
||||||
|
description: 'Geladener Anreißer',
|
||||||
|
imageUrl: 'https://example.com/vorschau.jpg',
|
||||||
|
siteName: 'Example',
|
||||||
|
provider: '',
|
||||||
|
providerId: ''
|
||||||
|
}));
|
||||||
|
expect(getPiece(id)).toMatchObject({
|
||||||
|
revision: loaded.revision,
|
||||||
|
presentationTitle: 'Manueller Titel',
|
||||||
|
presentationDescription: 'Geladener Anreißer',
|
||||||
|
presentationImageUrl: 'https://example.com/vorschau.jpg',
|
||||||
|
presentationSiteName: 'Example'
|
||||||
|
});
|
||||||
|
|
||||||
|
await loadPiecePresentationMetadata(id, loaded.revision, async () => ({
|
||||||
|
title: 'Anderer automatischer Titel',
|
||||||
|
description: 'Aktualisierter Anreißer',
|
||||||
|
imageUrl: '',
|
||||||
|
siteName: 'Example',
|
||||||
|
provider: '',
|
||||||
|
providerId: ''
|
||||||
|
}));
|
||||||
|
expect(getPiece(id)).toMatchObject({
|
||||||
|
presentationTitle: 'Manueller Titel',
|
||||||
|
presentationDescription: 'Aktualisierter Anreißer'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('searches independent taxonomies and archives, restores and duplicates pieces', async () => {
|
||||||
|
createTaxonomy('topic', 'Technikgeschichte');
|
||||||
|
const topic = getTaxonomy().topics.find((entry) => entry.name === 'Technikgeschichte')!;
|
||||||
|
const sourceId = createPiece('find');
|
||||||
|
const source = getPiece(sourceId)!;
|
||||||
|
savePiece(
|
||||||
|
sourceId,
|
||||||
|
source.revision,
|
||||||
|
completeInput({
|
||||||
|
title: 'Seltene Hardware',
|
||||||
|
formatId: 'format-find',
|
||||||
|
topicIds: [topic.id],
|
||||||
|
categoryIds: ['cat-reaction']
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
listPieces({ statuses: ['ready'], query: 'dokumentation', topicId: topic.id })
|
||||||
|
).toHaveLength(1);
|
||||||
|
expect(listPieces({ statuses: ['ready'], query: '%' })).toHaveLength(0);
|
||||||
|
expect(() => deleteTaxonomy('topic', topic.id)).toThrow('TAXONOMY_IN_USE');
|
||||||
|
createTaxonomy('topic', 'Unbenutzt');
|
||||||
|
const unused = getTaxonomy().topics.find((entry) => entry.name === 'Unbenutzt')!;
|
||||||
|
deleteTaxonomy('topic', unused.id);
|
||||||
|
expect(getTaxonomy().topics.some((entry) => entry.id === unused.id)).toBe(false);
|
||||||
|
expect(() => deleteTaxonomy('format', 'format-find')).toThrow('TAXONOMY_IN_USE');
|
||||||
|
const duplicateId = await duplicatePiece(sourceId);
|
||||||
|
expect(getPiece(duplicateId)).toMatchObject({
|
||||||
|
title: 'Kopie von Seltene Hardware',
|
||||||
|
status: 'preparing',
|
||||||
|
topicIds: [topic.id]
|
||||||
|
});
|
||||||
|
const current = getPiece(sourceId)!;
|
||||||
|
setPieceArchived(sourceId, current.revision, true);
|
||||||
|
expect(listPieces({ statuses: ['ready'] }).some((piece) => piece.id === sourceId)).toBe(false);
|
||||||
|
const archived = listPieces({ statuses: ['archived'] }).find((piece) => piece.id === sourceId)!;
|
||||||
|
setPieceArchived(sourceId, archived.revision, false);
|
||||||
|
expect(getPiece(sourceId)?.status).toBe('ready');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sanitizes dangerous markdown while preserving useful formatting', () => {
|
||||||
|
const html = renderMarkdown(
|
||||||
|
'# Verbotene Ebene\n\n**sicher** <script>globalThis.compromised = true</script> [Link](javascript:alert(1))'
|
||||||
|
);
|
||||||
|
expect(html).toContain('<strong>sicher</strong>');
|
||||||
|
expect(html).not.toContain('<script');
|
||||||
|
expect(html).not.toContain('javascript:');
|
||||||
|
expect(html).not.toContain('<h1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts signed raster images, rejects disguised files and keeps storage private', async () => {
|
||||||
|
const id = createPiece();
|
||||||
|
const png = Buffer.from(
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
|
||||||
|
'base64'
|
||||||
|
);
|
||||||
|
await uploadPieceImage(
|
||||||
|
id,
|
||||||
|
1,
|
||||||
|
new File([png], '../bild.png', { type: 'text/html' }),
|
||||||
|
'Ein heller Pixel'
|
||||||
|
);
|
||||||
|
const piece = getPiece(id)!;
|
||||||
|
expect(piece.media).toHaveLength(1);
|
||||||
|
expect(piece.media[0]).toMatchObject({ mimeType: 'image/png', altText: 'Ein heller Pixel' });
|
||||||
|
const media = await getMediaFile(piece.media[0].id);
|
||||||
|
expect(media?.data.equals(png)).toBe(true);
|
||||||
|
expect(existsSync(path.join(directory, 'uploads', '../bild.png'))).toBe(false);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
uploadPieceImage(
|
||||||
|
id,
|
||||||
|
piece.revision,
|
||||||
|
new File(['<script>alert(1)</script>'], 'angriff.png', { type: 'image/png' }),
|
||||||
|
''
|
||||||
|
)
|
||||||
|
).rejects.toThrow('INVALID_IMAGE_TYPE');
|
||||||
|
await deletePieceImage(id, piece.media[0].id, piece.revision);
|
||||||
|
expect(getPiece(id)?.media).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,991 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { copyFile, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileTypeFromBuffer } from 'file-type';
|
||||||
|
import { getDatabase } from './database.js';
|
||||||
|
import { getServerPaths } from './config.js';
|
||||||
|
import {
|
||||||
|
detectVideoProvider,
|
||||||
|
fetchPresentationMetadata,
|
||||||
|
type PresentationMode
|
||||||
|
} from './presentation.js';
|
||||||
|
|
||||||
|
export const PIECE_STATUSES = ['inbox', 'preparing', 'ready', 'archived'] as const;
|
||||||
|
export type PieceStatus = (typeof PIECE_STATUSES)[number];
|
||||||
|
export type EditablePieceStatus = Exclude<PieceStatus, 'archived'>;
|
||||||
|
export type TaxonomyKind = 'category' | 'format' | 'topic';
|
||||||
|
|
||||||
|
export type PieceSourceInput = {
|
||||||
|
label: string;
|
||||||
|
url: string;
|
||||||
|
timecodeSeconds: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PieceInput = {
|
||||||
|
title: string;
|
||||||
|
summary: string;
|
||||||
|
formatId: string | null;
|
||||||
|
status: EditablePieceStatus;
|
||||||
|
durationSeconds: number;
|
||||||
|
intro: string;
|
||||||
|
researchText: string;
|
||||||
|
moderationNotes: string;
|
||||||
|
transitionText: string;
|
||||||
|
presentationText: string;
|
||||||
|
presentationMode: PresentationMode;
|
||||||
|
presentationSourcePosition: number | null;
|
||||||
|
presentationTitle: string;
|
||||||
|
presentationDescription: string;
|
||||||
|
presentationImageUrl: string;
|
||||||
|
presentationSiteName: string;
|
||||||
|
presentationProvider: string;
|
||||||
|
presentationProviderId: string;
|
||||||
|
presentationTitleManual: boolean;
|
||||||
|
presentationDescriptionManual: boolean;
|
||||||
|
presentationImageManual: boolean;
|
||||||
|
presentationMetadataFetchedAtUtc: string | null;
|
||||||
|
topicIds: string[];
|
||||||
|
categoryIds: string[];
|
||||||
|
sources: PieceSourceInput[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PieceListItem = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
summary: string;
|
||||||
|
status: PieceStatus;
|
||||||
|
revision: number;
|
||||||
|
durationSeconds: number;
|
||||||
|
formatId: string | null;
|
||||||
|
format: string;
|
||||||
|
categories: { id: string; name: string; color: string }[];
|
||||||
|
topics: { id: string; name: string }[];
|
||||||
|
sourceCount: number;
|
||||||
|
mediaId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PieceEditor = Omit<PieceInput, 'status'> & {
|
||||||
|
id: string;
|
||||||
|
status: PieceStatus;
|
||||||
|
revision: number;
|
||||||
|
createdAtUtc: string;
|
||||||
|
updatedAtUtc: string;
|
||||||
|
media: PieceMedia[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PieceMedia = {
|
||||||
|
id: string;
|
||||||
|
originalName: string;
|
||||||
|
mimeType: string;
|
||||||
|
byteSize: number;
|
||||||
|
altText: string;
|
||||||
|
position: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Taxonomy = {
|
||||||
|
categories: { id: string; name: string; color: string }[];
|
||||||
|
formats: { id: string; name: string }[];
|
||||||
|
topics: { id: string; name: string }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const pieceTemplates = [
|
||||||
|
{
|
||||||
|
id: 'blank',
|
||||||
|
name: 'Leer starten',
|
||||||
|
description: 'Ein freies Piece ohne Vorgaben.'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'talk',
|
||||||
|
name: 'Gespräch',
|
||||||
|
description: 'Leitfragen, Recherche und eine klare Überleitung.'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'find',
|
||||||
|
name: 'Reaction / Fundstück',
|
||||||
|
description: 'Quelle, Einordnung und präsentierbare Kernaussage.'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'interaction',
|
||||||
|
name: 'Interaktion',
|
||||||
|
description: 'Quiz, Publikumsfrage oder kleines Spiel.'
|
||||||
|
}
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type PieceTemplateId = (typeof pieceTemplates)[number]['id'];
|
||||||
|
|
||||||
|
const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;
|
||||||
|
const ALLOWED_IMAGES = new Map([
|
||||||
|
['image/jpeg', 'jpg'],
|
||||||
|
['image/png', 'png'],
|
||||||
|
['image/webp', 'webp'],
|
||||||
|
['image/gif', 'gif']
|
||||||
|
]);
|
||||||
|
|
||||||
|
function cleanText(value: unknown, max: number, field: string): string {
|
||||||
|
const text = String(value ?? '').trim();
|
||||||
|
if (text.length > max) throw new Error(`INVALID_${field.toUpperCase()}`);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function uniqueIds(values: string[]): string[] {
|
||||||
|
return [...new Set(values.filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
|
function validUrl(value: string): boolean {
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
return url.protocol === 'http:' || url.protocol === 'https:';
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireTaxonomyIds(table: 'formats' | 'topics' | 'section_categories', ids: string[]) {
|
||||||
|
if (!ids.length) return;
|
||||||
|
const placeholders = ids.map(() => '?').join(', ');
|
||||||
|
const count = getDatabase()
|
||||||
|
.prepare(`SELECT count(*) AS count FROM ${table} WHERE id IN (${placeholders})`)
|
||||||
|
.get(...ids) as { count: number };
|
||||||
|
if (count.count !== ids.length) throw new Error('INVALID_TAXONOMY');
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatePieceInput(input: PieceInput): PieceInput {
|
||||||
|
const title = cleanText(input.title, 200, 'title');
|
||||||
|
if (!title) throw new Error('INVALID_TITLE');
|
||||||
|
if (!['inbox', 'preparing', 'ready'].includes(input.status)) throw new Error('INVALID_STATUS');
|
||||||
|
if (
|
||||||
|
!Number.isInteger(input.durationSeconds) ||
|
||||||
|
input.durationSeconds < 0 ||
|
||||||
|
input.durationSeconds > 86_400
|
||||||
|
) {
|
||||||
|
throw new Error('INVALID_DURATION');
|
||||||
|
}
|
||||||
|
const topicIds = uniqueIds(input.topicIds);
|
||||||
|
const categoryIds = uniqueIds(input.categoryIds);
|
||||||
|
if (topicIds.length > 20 || categoryIds.length > 20) throw new Error('INVALID_TAXONOMY');
|
||||||
|
if (input.formatId) requireTaxonomyIds('formats', [input.formatId]);
|
||||||
|
requireTaxonomyIds('topics', topicIds);
|
||||||
|
requireTaxonomyIds('section_categories', categoryIds);
|
||||||
|
if (input.sources.length > 20) throw new Error('INVALID_SOURCES');
|
||||||
|
const sources = input.sources.map((source) => {
|
||||||
|
const label = cleanText(source.label, 200, 'source');
|
||||||
|
const url = cleanText(source.url, 2_000, 'source');
|
||||||
|
if (!label || !validUrl(url)) throw new Error('INVALID_SOURCES');
|
||||||
|
if (
|
||||||
|
source.timecodeSeconds !== null &&
|
||||||
|
(!Number.isInteger(source.timecodeSeconds) ||
|
||||||
|
source.timecodeSeconds < 0 ||
|
||||||
|
source.timecodeSeconds > 86_400)
|
||||||
|
) {
|
||||||
|
throw new Error('INVALID_SOURCES');
|
||||||
|
}
|
||||||
|
return { label, url, timecodeSeconds: source.timecodeSeconds };
|
||||||
|
});
|
||||||
|
if (!['text', 'link', 'video'].includes(input.presentationMode)) {
|
||||||
|
throw new Error('INVALID_PRESENTATION');
|
||||||
|
}
|
||||||
|
const sourcePosition = input.presentationSourcePosition;
|
||||||
|
if (
|
||||||
|
sourcePosition !== null &&
|
||||||
|
(!Number.isInteger(sourcePosition) || sourcePosition < 0 || sourcePosition >= sources.length)
|
||||||
|
) {
|
||||||
|
throw new Error('INVALID_PRESENTATION');
|
||||||
|
}
|
||||||
|
if (input.presentationMode !== 'text' && sourcePosition === null) {
|
||||||
|
throw new Error('INVALID_PRESENTATION');
|
||||||
|
}
|
||||||
|
const presentationImageUrl = cleanText(input.presentationImageUrl, 2_000, 'presentation_image');
|
||||||
|
if (presentationImageUrl && !validUrl(presentationImageUrl)) {
|
||||||
|
throw new Error('INVALID_PRESENTATION');
|
||||||
|
}
|
||||||
|
const detected =
|
||||||
|
sourcePosition === null ? null : detectVideoProvider(sources[sourcePosition].url);
|
||||||
|
return {
|
||||||
|
title,
|
||||||
|
summary: cleanText(input.summary, 2_000, 'summary'),
|
||||||
|
formatId: input.formatId || null,
|
||||||
|
status: input.status,
|
||||||
|
durationSeconds: input.durationSeconds,
|
||||||
|
intro: cleanText(input.intro, 50_000, 'intro'),
|
||||||
|
researchText: cleanText(input.researchText, 50_000, 'research'),
|
||||||
|
moderationNotes: cleanText(input.moderationNotes, 50_000, 'moderation'),
|
||||||
|
transitionText: cleanText(input.transitionText, 50_000, 'transition'),
|
||||||
|
presentationText: cleanText(input.presentationText, 50_000, 'presentation'),
|
||||||
|
presentationMode: input.presentationMode,
|
||||||
|
presentationSourcePosition: sourcePosition,
|
||||||
|
presentationTitle: cleanText(input.presentationTitle, 300, 'presentation_title'),
|
||||||
|
presentationDescription: cleanText(
|
||||||
|
input.presentationDescription,
|
||||||
|
1_000,
|
||||||
|
'presentation_description'
|
||||||
|
),
|
||||||
|
presentationImageUrl,
|
||||||
|
presentationSiteName: cleanText(input.presentationSiteName, 200, 'presentation_site'),
|
||||||
|
presentationProvider: detected?.provider ?? '',
|
||||||
|
presentationProviderId: detected?.id ?? '',
|
||||||
|
presentationTitleManual: Boolean(input.presentationTitleManual),
|
||||||
|
presentationDescriptionManual: Boolean(input.presentationDescriptionManual),
|
||||||
|
presentationImageManual: Boolean(input.presentationImageManual),
|
||||||
|
presentationMetadataFetchedAtUtc: input.presentationMetadataFetchedAtUtc || null,
|
||||||
|
topicIds,
|
||||||
|
categoryIds,
|
||||||
|
sources
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTaxonomy(): Taxonomy {
|
||||||
|
const database = getDatabase();
|
||||||
|
return {
|
||||||
|
categories: database
|
||||||
|
.prepare('SELECT id, name, color FROM section_categories ORDER BY sort_order, name')
|
||||||
|
.all() as Taxonomy['categories'],
|
||||||
|
formats: database
|
||||||
|
.prepare('SELECT id, name FROM formats ORDER BY name')
|
||||||
|
.all() as Taxonomy['formats'],
|
||||||
|
topics: database
|
||||||
|
.prepare('SELECT id, name FROM topics ORDER BY name')
|
||||||
|
.all() as Taxonomy['topics']
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
type PieceListRow = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
summary: string;
|
||||||
|
status: PieceStatus;
|
||||||
|
revision: number;
|
||||||
|
duration_seconds: number;
|
||||||
|
format_id: string | null;
|
||||||
|
format: string;
|
||||||
|
source_count: number;
|
||||||
|
media_id: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function listPieces(filters: {
|
||||||
|
statuses: PieceStatus[];
|
||||||
|
query?: string;
|
||||||
|
formatId?: string;
|
||||||
|
topicId?: string;
|
||||||
|
categoryId?: string;
|
||||||
|
}): PieceListItem[] {
|
||||||
|
if (!filters.statuses.length) return [];
|
||||||
|
const conditions = [`p.status IN (${filters.statuses.map(() => '?').join(', ')})`];
|
||||||
|
const parameters: unknown[] = [...filters.statuses];
|
||||||
|
const query = filters.query?.trim().toLowerCase();
|
||||||
|
if (query) {
|
||||||
|
const escapedQuery = query
|
||||||
|
.replaceAll('\\', '\\\\')
|
||||||
|
.replaceAll('%', '\\%')
|
||||||
|
.replaceAll('_', '\\_');
|
||||||
|
conditions.push(`(
|
||||||
|
lower(p.title) LIKE ? ESCAPE '\\' OR lower(p.summary) LIKE ? ESCAPE '\\' OR
|
||||||
|
EXISTS (SELECT 1 FROM piece_sources ps WHERE ps.piece_id = p.id AND (lower(ps.label) LIKE ? ESCAPE '\\' OR lower(ps.url) LIKE ? ESCAPE '\\')) OR
|
||||||
|
EXISTS (SELECT 1 FROM piece_topics pt JOIN topics t ON t.id = pt.topic_id WHERE pt.piece_id = p.id AND lower(t.name) LIKE ? ESCAPE '\\')
|
||||||
|
)`);
|
||||||
|
parameters.push(...Array(5).fill(`%${escapedQuery}%`));
|
||||||
|
}
|
||||||
|
if (filters.formatId) {
|
||||||
|
conditions.push('p.format_id = ?');
|
||||||
|
parameters.push(filters.formatId);
|
||||||
|
}
|
||||||
|
if (filters.topicId) {
|
||||||
|
conditions.push(
|
||||||
|
'EXISTS (SELECT 1 FROM piece_topics pt WHERE pt.piece_id = p.id AND pt.topic_id = ?)'
|
||||||
|
);
|
||||||
|
parameters.push(filters.topicId);
|
||||||
|
}
|
||||||
|
if (filters.categoryId) {
|
||||||
|
conditions.push(
|
||||||
|
'EXISTS (SELECT 1 FROM piece_category_suggestions pc WHERE pc.piece_id = p.id AND pc.category_id = ?)'
|
||||||
|
);
|
||||||
|
parameters.push(filters.categoryId);
|
||||||
|
}
|
||||||
|
const database = getDatabase();
|
||||||
|
const rows = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT p.id, p.title, p.summary, p.status, p.revision, p.duration_seconds,
|
||||||
|
p.format_id, COALESCE(f.name, 'Ohne Format') AS format,
|
||||||
|
(SELECT count(*) FROM piece_sources ps WHERE ps.piece_id = p.id) AS source_count,
|
||||||
|
(SELECT pm.id FROM piece_media pm WHERE pm.piece_id = p.id ORDER BY pm.position LIMIT 1) AS media_id
|
||||||
|
FROM pieces p LEFT JOIN formats f ON f.id = p.format_id
|
||||||
|
WHERE ${conditions.join(' AND ')}
|
||||||
|
ORDER BY CASE p.status WHEN 'ready' THEN 0 WHEN 'preparing' THEN 1 WHEN 'inbox' THEN 2 ELSE 3 END,
|
||||||
|
p.updated_at_utc DESC, p.title`
|
||||||
|
)
|
||||||
|
.all(...parameters) as PieceListRow[];
|
||||||
|
const categoryStatement = database.prepare(
|
||||||
|
`SELECT c.id, c.name, c.color FROM piece_category_suggestions pc
|
||||||
|
JOIN section_categories c ON c.id = pc.category_id
|
||||||
|
WHERE pc.piece_id = ? ORDER BY c.sort_order, c.name`
|
||||||
|
);
|
||||||
|
const topicStatement = database.prepare(
|
||||||
|
`SELECT t.id, t.name FROM piece_topics pt JOIN topics t ON t.id = pt.topic_id
|
||||||
|
WHERE pt.piece_id = ? ORDER BY t.name`
|
||||||
|
);
|
||||||
|
return rows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
summary: row.summary,
|
||||||
|
status: row.status,
|
||||||
|
revision: row.revision,
|
||||||
|
durationSeconds: row.duration_seconds,
|
||||||
|
formatId: row.format_id,
|
||||||
|
format: row.format,
|
||||||
|
categories: categoryStatement.all(row.id) as PieceListItem['categories'],
|
||||||
|
topics: topicStatement.all(row.id) as PieceListItem['topics'],
|
||||||
|
sourceCount: row.source_count,
|
||||||
|
mediaId: row.media_id
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
type PieceRow = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
summary: string;
|
||||||
|
format_id: string | null;
|
||||||
|
status: PieceStatus;
|
||||||
|
duration_seconds: number;
|
||||||
|
intro: string;
|
||||||
|
research_text: string;
|
||||||
|
moderation_notes: string;
|
||||||
|
transition_text: string;
|
||||||
|
presentation_text: string;
|
||||||
|
presentation_mode: PresentationMode;
|
||||||
|
presentation_source_position: number | null;
|
||||||
|
presentation_title: string;
|
||||||
|
presentation_description: string;
|
||||||
|
presentation_image_url: string;
|
||||||
|
presentation_site_name: string;
|
||||||
|
presentation_provider: string;
|
||||||
|
presentation_provider_id: string;
|
||||||
|
presentation_title_manual: number;
|
||||||
|
presentation_description_manual: number;
|
||||||
|
presentation_image_manual: number;
|
||||||
|
presentation_metadata_fetched_at_utc: string | null;
|
||||||
|
revision: number;
|
||||||
|
created_at_utc: string;
|
||||||
|
updated_at_utc: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function getPiece(id: string): PieceEditor | null {
|
||||||
|
const database = getDatabase();
|
||||||
|
const row = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, title, summary, format_id, status, duration_seconds, intro, research_text,
|
||||||
|
moderation_notes, transition_text, presentation_text, presentation_mode,
|
||||||
|
presentation_source_position, presentation_title, presentation_description,
|
||||||
|
presentation_image_url, presentation_site_name, presentation_provider,
|
||||||
|
presentation_provider_id, presentation_title_manual, presentation_description_manual,
|
||||||
|
presentation_image_manual, presentation_metadata_fetched_at_utc,
|
||||||
|
revision, created_at_utc, updated_at_utc
|
||||||
|
FROM pieces WHERE id = ?`
|
||||||
|
)
|
||||||
|
.get(id) as PieceRow | undefined;
|
||||||
|
if (!row) return null;
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
title: row.title,
|
||||||
|
summary: row.summary,
|
||||||
|
formatId: row.format_id,
|
||||||
|
status: row.status,
|
||||||
|
durationSeconds: row.duration_seconds,
|
||||||
|
intro: row.intro,
|
||||||
|
researchText: row.research_text,
|
||||||
|
moderationNotes: row.moderation_notes,
|
||||||
|
transitionText: row.transition_text,
|
||||||
|
presentationText: row.presentation_text,
|
||||||
|
presentationMode: row.presentation_mode,
|
||||||
|
presentationSourcePosition: row.presentation_source_position,
|
||||||
|
presentationTitle: row.presentation_title,
|
||||||
|
presentationDescription: row.presentation_description,
|
||||||
|
presentationImageUrl: row.presentation_image_url,
|
||||||
|
presentationSiteName: row.presentation_site_name,
|
||||||
|
presentationProvider: row.presentation_provider,
|
||||||
|
presentationProviderId: row.presentation_provider_id,
|
||||||
|
presentationTitleManual: row.presentation_title_manual === 1,
|
||||||
|
presentationDescriptionManual: row.presentation_description_manual === 1,
|
||||||
|
presentationImageManual: row.presentation_image_manual === 1,
|
||||||
|
presentationMetadataFetchedAtUtc: row.presentation_metadata_fetched_at_utc,
|
||||||
|
revision: row.revision,
|
||||||
|
createdAtUtc: row.created_at_utc,
|
||||||
|
updatedAtUtc: row.updated_at_utc,
|
||||||
|
topicIds: (
|
||||||
|
database.prepare('SELECT topic_id FROM piece_topics WHERE piece_id = ?').all(id) as {
|
||||||
|
topic_id: string;
|
||||||
|
}[]
|
||||||
|
).map((entry) => entry.topic_id),
|
||||||
|
categoryIds: (
|
||||||
|
database
|
||||||
|
.prepare('SELECT category_id FROM piece_category_suggestions WHERE piece_id = ?')
|
||||||
|
.all(id) as { category_id: string }[]
|
||||||
|
).map((entry) => entry.category_id),
|
||||||
|
sources: (
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
'SELECT label, url, timecode_seconds FROM piece_sources WHERE piece_id = ? ORDER BY position'
|
||||||
|
)
|
||||||
|
.all(id) as { label: string; url: string; timecode_seconds: number | null }[]
|
||||||
|
).map((source) => ({
|
||||||
|
label: source.label,
|
||||||
|
url: source.url,
|
||||||
|
timecodeSeconds: source.timecode_seconds
|
||||||
|
})),
|
||||||
|
media: (
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, original_name, mime_type, byte_size, alt_text, position
|
||||||
|
FROM piece_media WHERE piece_id = ? ORDER BY position`
|
||||||
|
)
|
||||||
|
.all(id) as {
|
||||||
|
id: string;
|
||||||
|
original_name: string;
|
||||||
|
mime_type: string;
|
||||||
|
byte_size: number;
|
||||||
|
alt_text: string;
|
||||||
|
position: number;
|
||||||
|
}[]
|
||||||
|
).map((media) => ({
|
||||||
|
id: media.id,
|
||||||
|
originalName: media.original_name,
|
||||||
|
mimeType: media.mime_type,
|
||||||
|
byteSize: media.byte_size,
|
||||||
|
altText: media.alt_text,
|
||||||
|
position: media.position
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceRelations(pieceId: string, input: PieceInput) {
|
||||||
|
const database = getDatabase();
|
||||||
|
database.prepare('DELETE FROM piece_topics WHERE piece_id = ?').run(pieceId);
|
||||||
|
const addTopic = database.prepare('INSERT INTO piece_topics (piece_id, topic_id) VALUES (?, ?)');
|
||||||
|
for (const id of input.topicIds) addTopic.run(pieceId, id);
|
||||||
|
database.prepare('DELETE FROM piece_category_suggestions WHERE piece_id = ?').run(pieceId);
|
||||||
|
const addCategory = database.prepare(
|
||||||
|
'INSERT INTO piece_category_suggestions (piece_id, category_id) VALUES (?, ?)'
|
||||||
|
);
|
||||||
|
for (const id of input.categoryIds) addCategory.run(pieceId, id);
|
||||||
|
database.prepare('DELETE FROM piece_sources WHERE piece_id = ?').run(pieceId);
|
||||||
|
const addSource = database.prepare(
|
||||||
|
`INSERT INTO piece_sources (id, piece_id, label, url, timecode_seconds, position)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)`
|
||||||
|
);
|
||||||
|
input.sources.forEach((source, position) =>
|
||||||
|
addSource.run(randomUUID(), pieceId, source.label, source.url, source.timecodeSeconds, position)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function savePiece(id: string, expectedRevision: number, rawInput: PieceInput) {
|
||||||
|
if (!Number.isInteger(expectedRevision) || expectedRevision < 1)
|
||||||
|
throw new Error('INVALID_REVISION');
|
||||||
|
const input = validatePieceInput(rawInput);
|
||||||
|
const database = getDatabase();
|
||||||
|
const updatedAtUtc = new Date().toISOString();
|
||||||
|
const save = database.transaction(() => {
|
||||||
|
const result = database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET title = ?, summary = ?, format_id = ?, status = ?, duration_seconds = ?,
|
||||||
|
intro = ?, research_text = ?, moderation_notes = ?, transition_text = ?, presentation_text = ?,
|
||||||
|
presentation_mode = ?, presentation_source_position = ?, presentation_title = ?,
|
||||||
|
presentation_description = ?, presentation_image_url = ?, presentation_site_name = ?,
|
||||||
|
presentation_provider = ?, presentation_provider_id = ?, presentation_title_manual = ?,
|
||||||
|
presentation_description_manual = ?, presentation_image_manual = ?,
|
||||||
|
presentation_metadata_fetched_at_utc = ?,
|
||||||
|
updated_at_utc = ?, revision = revision + 1, archived_from_status = NULL
|
||||||
|
WHERE id = ? AND revision = ? AND status != 'archived'`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
input.title,
|
||||||
|
input.summary,
|
||||||
|
input.formatId,
|
||||||
|
input.status,
|
||||||
|
input.durationSeconds,
|
||||||
|
input.intro,
|
||||||
|
input.researchText,
|
||||||
|
input.moderationNotes,
|
||||||
|
input.transitionText,
|
||||||
|
input.presentationText,
|
||||||
|
input.presentationMode,
|
||||||
|
input.presentationSourcePosition,
|
||||||
|
input.presentationTitle,
|
||||||
|
input.presentationDescription,
|
||||||
|
input.presentationImageUrl,
|
||||||
|
input.presentationSiteName,
|
||||||
|
input.presentationProvider,
|
||||||
|
input.presentationProviderId,
|
||||||
|
input.presentationTitleManual ? 1 : 0,
|
||||||
|
input.presentationDescriptionManual ? 1 : 0,
|
||||||
|
input.presentationImageManual ? 1 : 0,
|
||||||
|
input.presentationMetadataFetchedAtUtc,
|
||||||
|
updatedAtUtc,
|
||||||
|
id,
|
||||||
|
expectedRevision
|
||||||
|
);
|
||||||
|
if (result.changes !== 1) {
|
||||||
|
const exists = database.prepare('SELECT 1 FROM pieces WHERE id = ?').get(id);
|
||||||
|
throw new Error(exists ? 'CONFLICT' : 'NOT_FOUND');
|
||||||
|
}
|
||||||
|
replaceRelations(id, input);
|
||||||
|
});
|
||||||
|
save();
|
||||||
|
return { revision: expectedRevision + 1, updatedAtUtc };
|
||||||
|
}
|
||||||
|
|
||||||
|
function templateDefaults(template: PieceTemplateId): Partial<PieceInput> & { title: string } {
|
||||||
|
if (template === 'talk') {
|
||||||
|
return {
|
||||||
|
title: 'Unbenanntes Gespräch',
|
||||||
|
formatId: 'format-talk',
|
||||||
|
categoryIds: ['cat-jc'],
|
||||||
|
moderationNotes: '## Leitfragen\n\n- '
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (template === 'find') {
|
||||||
|
return {
|
||||||
|
title: 'Neues Fundstück',
|
||||||
|
formatId: 'format-find',
|
||||||
|
categoryIds: ['cat-reaction'],
|
||||||
|
presentationText: '## Kernaussage\n\n'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (template === 'interaction') {
|
||||||
|
return {
|
||||||
|
title: 'Neue Interaktion',
|
||||||
|
formatId: 'format-quiz',
|
||||||
|
categoryIds: ['cat-game'],
|
||||||
|
moderationNotes: '## Ablauf\n\n1. '
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { title: 'Neues Piece' };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPiece(template: PieceTemplateId = 'blank'): string {
|
||||||
|
if (!pieceTemplates.some((entry) => entry.id === template)) throw new Error('INVALID_TEMPLATE');
|
||||||
|
const defaults = templateDefaults(template);
|
||||||
|
const id = randomUUID();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const input = validatePieceInput({
|
||||||
|
title: defaults.title,
|
||||||
|
summary: '',
|
||||||
|
formatId: defaults.formatId ?? null,
|
||||||
|
status: 'preparing',
|
||||||
|
durationSeconds: 0,
|
||||||
|
intro: '',
|
||||||
|
researchText: '',
|
||||||
|
moderationNotes: defaults.moderationNotes ?? '',
|
||||||
|
transitionText: '',
|
||||||
|
presentationText: defaults.presentationText ?? '',
|
||||||
|
presentationMode: 'text',
|
||||||
|
presentationSourcePosition: null,
|
||||||
|
presentationTitle: '',
|
||||||
|
presentationDescription: '',
|
||||||
|
presentationImageUrl: '',
|
||||||
|
presentationSiteName: '',
|
||||||
|
presentationProvider: '',
|
||||||
|
presentationProviderId: '',
|
||||||
|
presentationTitleManual: false,
|
||||||
|
presentationDescriptionManual: false,
|
||||||
|
presentationImageManual: false,
|
||||||
|
presentationMetadataFetchedAtUtc: null,
|
||||||
|
topicIds: [],
|
||||||
|
categoryIds: defaults.categoryIds ?? [],
|
||||||
|
sources: []
|
||||||
|
});
|
||||||
|
const database = getDatabase();
|
||||||
|
database.transaction(() => {
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO pieces (id, title, summary, format_id, status, duration_seconds, intro,
|
||||||
|
research_text, moderation_notes, transition_text, presentation_text, created_at_utc,
|
||||||
|
updated_at_utc, revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
id,
|
||||||
|
input.title,
|
||||||
|
input.summary,
|
||||||
|
input.formatId,
|
||||||
|
input.status,
|
||||||
|
input.durationSeconds,
|
||||||
|
input.intro,
|
||||||
|
input.researchText,
|
||||||
|
input.moderationNotes,
|
||||||
|
input.transitionText,
|
||||||
|
input.presentationText,
|
||||||
|
now,
|
||||||
|
now
|
||||||
|
);
|
||||||
|
replaceRelations(id, input);
|
||||||
|
})();
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function captureInbox(titleValue: string, urlValue: string): string {
|
||||||
|
let title = cleanText(titleValue, 200, 'title');
|
||||||
|
const url = cleanText(urlValue, 2_000, 'source');
|
||||||
|
if (url && !validUrl(url)) throw new Error('INVALID_SOURCES');
|
||||||
|
if (!title && !url) throw new Error('INVALID_TITLE');
|
||||||
|
if (!title) title = new URL(url).hostname;
|
||||||
|
const id = createPiece('blank');
|
||||||
|
const piece = getPiece(id)!;
|
||||||
|
savePiece(id, piece.revision, {
|
||||||
|
...piece,
|
||||||
|
title,
|
||||||
|
status: 'inbox',
|
||||||
|
sources: url ? [{ label: 'Schnellaufnahme', url, timecodeSeconds: null }] : []
|
||||||
|
});
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setPieceArchived(id: string, expectedRevision: number, archived: boolean) {
|
||||||
|
const database = getDatabase();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const result = archived
|
||||||
|
? database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET archived_from_status = status, status = 'archived', revision = revision + 1,
|
||||||
|
updated_at_utc = ? WHERE id = ? AND revision = ? AND status != 'archived'`
|
||||||
|
)
|
||||||
|
.run(now, id, expectedRevision)
|
||||||
|
: database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET status = COALESCE(archived_from_status, 'preparing'), archived_from_status = NULL,
|
||||||
|
revision = revision + 1, updated_at_utc = ?
|
||||||
|
WHERE id = ? AND revision = ? AND status = 'archived'`
|
||||||
|
)
|
||||||
|
.run(now, id, expectedRevision);
|
||||||
|
if (result.changes !== 1) {
|
||||||
|
const exists = database.prepare('SELECT 1 FROM pieces WHERE id = ?').get(id);
|
||||||
|
throw new Error(exists ? 'CONFLICT' : 'NOT_FOUND');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function duplicatePiece(sourceId: string): Promise<string> {
|
||||||
|
const source = getPiece(sourceId);
|
||||||
|
if (!source) throw new Error('NOT_FOUND');
|
||||||
|
const id = randomUUID();
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const uploadDirectory = getServerPaths().uploads;
|
||||||
|
await mkdir(uploadDirectory, { recursive: true, mode: 0o700 });
|
||||||
|
const database = getDatabase();
|
||||||
|
const storedMedia = database
|
||||||
|
.prepare('SELECT * FROM piece_media WHERE piece_id = ? ORDER BY position')
|
||||||
|
.all(sourceId) as {
|
||||||
|
id: string;
|
||||||
|
storage_name: string;
|
||||||
|
original_name: string;
|
||||||
|
mime_type: string;
|
||||||
|
byte_size: number;
|
||||||
|
alt_text: string;
|
||||||
|
position: number;
|
||||||
|
}[];
|
||||||
|
const copied: { source: (typeof storedMedia)[number]; storageName: string }[] = [];
|
||||||
|
try {
|
||||||
|
for (const media of storedMedia) {
|
||||||
|
const extension = ALLOWED_IMAGES.get(media.mime_type)!;
|
||||||
|
const storageName = `${randomUUID()}.${extension}`;
|
||||||
|
await copyFile(
|
||||||
|
path.join(uploadDirectory, media.storage_name),
|
||||||
|
path.join(uploadDirectory, storageName)
|
||||||
|
);
|
||||||
|
copied.push({ source: media, storageName });
|
||||||
|
}
|
||||||
|
database.transaction(() => {
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO pieces (id, title, summary, format_id, status, duration_seconds, intro,
|
||||||
|
research_text, moderation_notes, transition_text, presentation_text, presentation_mode,
|
||||||
|
presentation_source_position, presentation_title, presentation_description,
|
||||||
|
presentation_image_url, presentation_site_name, presentation_provider,
|
||||||
|
presentation_provider_id, presentation_title_manual,
|
||||||
|
presentation_description_manual, presentation_image_manual,
|
||||||
|
presentation_metadata_fetched_at_utc, created_at_utc, updated_at_utc, revision)
|
||||||
|
VALUES (?, ?, ?, ?, 'preparing', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
id,
|
||||||
|
`Kopie von ${source.title}`.slice(0, 200),
|
||||||
|
source.summary,
|
||||||
|
source.formatId,
|
||||||
|
source.durationSeconds,
|
||||||
|
source.intro,
|
||||||
|
source.researchText,
|
||||||
|
source.moderationNotes,
|
||||||
|
source.transitionText,
|
||||||
|
source.presentationText,
|
||||||
|
source.presentationMode,
|
||||||
|
source.presentationSourcePosition,
|
||||||
|
source.presentationTitle,
|
||||||
|
source.presentationDescription,
|
||||||
|
source.presentationImageUrl,
|
||||||
|
source.presentationSiteName,
|
||||||
|
source.presentationProvider,
|
||||||
|
source.presentationProviderId,
|
||||||
|
source.presentationTitleManual ? 1 : 0,
|
||||||
|
source.presentationDescriptionManual ? 1 : 0,
|
||||||
|
source.presentationImageManual ? 1 : 0,
|
||||||
|
source.presentationMetadataFetchedAtUtc,
|
||||||
|
now,
|
||||||
|
now
|
||||||
|
);
|
||||||
|
replaceRelations(id, { ...source, status: 'preparing' });
|
||||||
|
const addMedia = database.prepare(
|
||||||
|
`INSERT INTO piece_media (id, piece_id, storage_name, original_name, mime_type,
|
||||||
|
byte_size, alt_text, position, created_at_utc) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
);
|
||||||
|
for (const media of copied) {
|
||||||
|
addMedia.run(
|
||||||
|
randomUUID(),
|
||||||
|
id,
|
||||||
|
media.storageName,
|
||||||
|
media.source.original_name,
|
||||||
|
media.source.mime_type,
|
||||||
|
media.source.byte_size,
|
||||||
|
media.source.alt_text,
|
||||||
|
media.source.position,
|
||||||
|
now
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return id;
|
||||||
|
} catch (error) {
|
||||||
|
await Promise.all(
|
||||||
|
copied.map((media) => unlink(path.join(uploadDirectory, media.storageName)).catch(() => {}))
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loadPiecePresentationMetadata(
|
||||||
|
id: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
metadataLoader = fetchPresentationMetadata
|
||||||
|
) {
|
||||||
|
if (!Number.isInteger(expectedRevision) || expectedRevision < 1) {
|
||||||
|
throw new Error('INVALID_REVISION');
|
||||||
|
}
|
||||||
|
const database = getDatabase();
|
||||||
|
const piece = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT p.revision, p.presentation_mode, p.presentation_source_position,
|
||||||
|
p.presentation_title_manual, p.presentation_description_manual,
|
||||||
|
p.presentation_image_manual, s.url
|
||||||
|
FROM pieces p LEFT JOIN piece_sources s ON s.piece_id = p.id
|
||||||
|
AND s.position = p.presentation_source_position
|
||||||
|
WHERE p.id = ? AND p.status != 'archived'`
|
||||||
|
)
|
||||||
|
.get(id) as
|
||||||
|
| {
|
||||||
|
revision: number;
|
||||||
|
presentation_mode: PresentationMode;
|
||||||
|
presentation_source_position: number | null;
|
||||||
|
presentation_title_manual: number;
|
||||||
|
presentation_description_manual: number;
|
||||||
|
presentation_image_manual: number;
|
||||||
|
url: string | null;
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
if (!piece) throw new Error('NOT_FOUND');
|
||||||
|
if (piece.revision !== expectedRevision) throw new Error('CONFLICT');
|
||||||
|
if (piece.presentation_mode === 'text' || !piece.url) throw new Error('INVALID_PRESENTATION');
|
||||||
|
const metadata = await metadataLoader(piece.url);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const result = database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET
|
||||||
|
presentation_title = CASE WHEN presentation_title_manual = 1 THEN presentation_title ELSE ? END,
|
||||||
|
presentation_description = CASE WHEN presentation_description_manual = 1 THEN presentation_description ELSE ? END,
|
||||||
|
presentation_image_url = CASE WHEN presentation_image_manual = 1 THEN presentation_image_url ELSE ? END,
|
||||||
|
presentation_site_name = ?, presentation_provider = ?, presentation_provider_id = ?,
|
||||||
|
presentation_metadata_fetched_at_utc = ?, updated_at_utc = ?, revision = revision + 1
|
||||||
|
WHERE id = ? AND revision = ? AND status != 'archived'`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
metadata.title,
|
||||||
|
metadata.description,
|
||||||
|
metadata.imageUrl,
|
||||||
|
metadata.siteName,
|
||||||
|
metadata.provider,
|
||||||
|
metadata.providerId,
|
||||||
|
now,
|
||||||
|
now,
|
||||||
|
id,
|
||||||
|
expectedRevision
|
||||||
|
);
|
||||||
|
if (result.changes !== 1) throw new Error('CONFLICT');
|
||||||
|
return { revision: expectedRevision + 1, updatedAtUtc: now };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function uploadPieceImage(
|
||||||
|
pieceId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
file: File,
|
||||||
|
altTextValue: string
|
||||||
|
) {
|
||||||
|
if (!file.size || file.size > MAX_UPLOAD_BYTES) throw new Error('INVALID_IMAGE_SIZE');
|
||||||
|
const buffer = Buffer.from(await file.arrayBuffer());
|
||||||
|
const detected = await fileTypeFromBuffer(buffer);
|
||||||
|
const extension = detected ? ALLOWED_IMAGES.get(detected.mime) : undefined;
|
||||||
|
if (!detected || !extension) throw new Error('INVALID_IMAGE_TYPE');
|
||||||
|
const altText = cleanText(altTextValue, 300, 'alt');
|
||||||
|
const storageName = `${randomUUID()}.${extension}`;
|
||||||
|
const uploadDirectory = getServerPaths().uploads;
|
||||||
|
await mkdir(uploadDirectory, { recursive: true, mode: 0o700 });
|
||||||
|
const filePath = path.join(uploadDirectory, storageName);
|
||||||
|
await writeFile(filePath, buffer, { flag: 'wx', mode: 0o600 });
|
||||||
|
const database = getDatabase();
|
||||||
|
try {
|
||||||
|
database.transaction(() => {
|
||||||
|
const updated = database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET revision = revision + 1, updated_at_utc = ?
|
||||||
|
WHERE id = ? AND revision = ? AND status != 'archived'`
|
||||||
|
)
|
||||||
|
.run(new Date().toISOString(), pieceId, expectedRevision);
|
||||||
|
if (updated.changes !== 1) throw new Error('CONFLICT');
|
||||||
|
const count = database
|
||||||
|
.prepare('SELECT count(*) AS count FROM piece_media WHERE piece_id = ?')
|
||||||
|
.get(pieceId) as { count: number };
|
||||||
|
if (count.count >= 8) throw new Error('TOO_MANY_IMAGES');
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO piece_media (id, piece_id, storage_name, original_name, mime_type,
|
||||||
|
byte_size, alt_text, position, created_at_utc) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
randomUUID(),
|
||||||
|
pieceId,
|
||||||
|
storageName,
|
||||||
|
path.basename(file.name).slice(0, 200) || `bild.${extension}`,
|
||||||
|
detected.mime,
|
||||||
|
buffer.byteLength,
|
||||||
|
altText,
|
||||||
|
count.count,
|
||||||
|
new Date().toISOString()
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
} catch (error) {
|
||||||
|
await unlink(filePath).catch(() => {});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePieceImage(pieceId: string, mediaId: string, expectedRevision: number) {
|
||||||
|
const database = getDatabase();
|
||||||
|
const media = database
|
||||||
|
.prepare('SELECT storage_name FROM piece_media WHERE id = ? AND piece_id = ?')
|
||||||
|
.get(mediaId, pieceId) as { storage_name: string } | undefined;
|
||||||
|
if (!media) throw new Error('NOT_FOUND');
|
||||||
|
const originalPath = path.join(getServerPaths().uploads, media.storage_name);
|
||||||
|
const quarantinePath = `${originalPath}.deleting-${randomUUID()}`;
|
||||||
|
await rename(originalPath, quarantinePath);
|
||||||
|
try {
|
||||||
|
database.transaction(() => {
|
||||||
|
const updated = database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET revision = revision + 1, updated_at_utc = ?
|
||||||
|
WHERE id = ? AND revision = ? AND status != 'archived'`
|
||||||
|
)
|
||||||
|
.run(new Date().toISOString(), pieceId, expectedRevision);
|
||||||
|
if (updated.changes !== 1) throw new Error('CONFLICT');
|
||||||
|
database.prepare('DELETE FROM piece_media WHERE id = ?').run(mediaId);
|
||||||
|
})();
|
||||||
|
} catch (error) {
|
||||||
|
await rename(quarantinePath, originalPath).catch((restoreError) => {
|
||||||
|
console.error(
|
||||||
|
'Bilddatei konnte nach fehlgeschlagener Löschung nicht wiederhergestellt werden.',
|
||||||
|
restoreError
|
||||||
|
);
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await unlink(quarantinePath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(
|
||||||
|
'Gelöschte Bilddatei konnte nicht aus dem Quarantänepfad entfernt werden.',
|
||||||
|
error
|
||||||
|
);
|
||||||
|
throw new Error('IMAGE_CLEANUP_FAILED', { cause: error });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMediaFile(id: string) {
|
||||||
|
const row = getDatabase()
|
||||||
|
.prepare('SELECT storage_name, mime_type, byte_size, alt_text FROM piece_media WHERE id = ?')
|
||||||
|
.get(id) as
|
||||||
|
{ storage_name: string; mime_type: string; byte_size: number; alt_text: string } | undefined;
|
||||||
|
if (!row) return null;
|
||||||
|
return {
|
||||||
|
data: await readFile(path.join(getServerPaths().uploads, row.storage_name)),
|
||||||
|
mimeType: row.mime_type,
|
||||||
|
byteSize: row.byte_size,
|
||||||
|
altText: row.alt_text
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTaxonomy(kind: TaxonomyKind, nameValue: string, colorValue?: string) {
|
||||||
|
const name = cleanText(nameValue, 80, 'taxonomy');
|
||||||
|
if (!name) throw new Error('INVALID_TAXONOMY');
|
||||||
|
const database = getDatabase();
|
||||||
|
const duplicate = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT 1 FROM ${kind === 'category' ? 'section_categories' : kind === 'format' ? 'formats' : 'topics'}
|
||||||
|
WHERE lower(name) = lower(?)`
|
||||||
|
)
|
||||||
|
.get(name);
|
||||||
|
if (duplicate) throw new Error('TAXONOMY_EXISTS');
|
||||||
|
const id = randomUUID();
|
||||||
|
if (kind === 'category') {
|
||||||
|
const color = String(colorValue ?? '');
|
||||||
|
if (!/^#[0-9a-fA-F]{6}$/.test(color)) throw new Error('INVALID_COLOR');
|
||||||
|
const order = database
|
||||||
|
.prepare('SELECT COALESCE(max(sort_order), -1) + 1 AS next FROM section_categories')
|
||||||
|
.get() as {
|
||||||
|
next: number;
|
||||||
|
};
|
||||||
|
database
|
||||||
|
.prepare('INSERT INTO section_categories (id, name, color, sort_order) VALUES (?, ?, ?, ?)')
|
||||||
|
.run(id, name, color, order.next);
|
||||||
|
} else {
|
||||||
|
const table = kind === 'format' ? 'formats' : 'topics';
|
||||||
|
database.prepare(`INSERT INTO ${table} (id, name) VALUES (?, ?)`).run(id, name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteTaxonomy(kind: TaxonomyKind, id: string) {
|
||||||
|
const table =
|
||||||
|
kind === 'category' ? 'section_categories' : kind === 'format' ? 'formats' : 'topics';
|
||||||
|
if (
|
||||||
|
['format-talk', 'format-find', 'format-quiz', 'cat-jc', 'cat-reaction', 'cat-game'].includes(id)
|
||||||
|
) {
|
||||||
|
throw new Error('TAXONOMY_IN_USE');
|
||||||
|
}
|
||||||
|
const database = getDatabase();
|
||||||
|
const usage =
|
||||||
|
kind === 'format'
|
||||||
|
? (
|
||||||
|
database.prepare('SELECT count(*) AS count FROM pieces WHERE format_id = ?').get(id) as {
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
).count
|
||||||
|
: kind === 'topic'
|
||||||
|
? (
|
||||||
|
database
|
||||||
|
.prepare('SELECT count(*) AS count FROM piece_topics WHERE topic_id = ?')
|
||||||
|
.get(id) as {
|
||||||
|
count: number;
|
||||||
|
}
|
||||||
|
).count
|
||||||
|
: (
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`SELECT
|
||||||
|
(SELECT count(*) FROM piece_category_suggestions WHERE category_id = ?) +
|
||||||
|
(SELECT count(*) FROM show_sections WHERE category_id = ?) AS count`
|
||||||
|
)
|
||||||
|
.get(id, id) as { count: number }
|
||||||
|
).count;
|
||||||
|
if (usage > 0) throw new Error('TAXONOMY_IN_USE');
|
||||||
|
const result = database.prepare(`DELETE FROM ${table} WHERE id = ?`).run(id);
|
||||||
|
if (result.changes !== 1) throw new Error('NOT_FOUND');
|
||||||
|
}
|
||||||
@@ -47,12 +47,28 @@ describe('database setup', () => {
|
|||||||
(SELECT count(*) FROM schema_migrations) AS migrations,
|
(SELECT count(*) FROM schema_migrations) AS migrations,
|
||||||
(SELECT count(*) FROM pieces) AS pieces,
|
(SELECT count(*) FROM pieces) AS pieces,
|
||||||
(SELECT count(*) FROM shows) AS shows,
|
(SELECT count(*) FROM shows) AS shows,
|
||||||
(SELECT count(*) FROM piece_usages) AS usages`
|
(SELECT count(*) FROM piece_usages) AS usages,
|
||||||
|
(SELECT count(*) FROM show_templates) AS templates,
|
||||||
|
(SELECT count(*) FROM show_sections WHERE is_reserve_bank = 1) AS reserve_banks`
|
||||||
)
|
)
|
||||||
.get() as { migrations: number; pieces: number; shows: number; usages: number };
|
.get() as {
|
||||||
|
migrations: number;
|
||||||
|
pieces: number;
|
||||||
|
shows: number;
|
||||||
|
usages: number;
|
||||||
|
templates: number;
|
||||||
|
reserve_banks: number;
|
||||||
|
};
|
||||||
database.close();
|
database.close();
|
||||||
|
|
||||||
expect(counts).toEqual({ migrations: 1, pieces: 4, shows: 1, usages: 3 });
|
expect(counts).toEqual({
|
||||||
|
migrations: 6,
|
||||||
|
pieces: 6,
|
||||||
|
shows: 2,
|
||||||
|
usages: 5,
|
||||||
|
templates: 2,
|
||||||
|
reserve_banks: 2
|
||||||
|
});
|
||||||
expect(databasePath).not.toBe(path.resolve('.data/sendewerk.sqlite'));
|
expect(databasePath).not.toBe(path.resolve('.data/sendewerk.sqlite'));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { closeDatabase, getDatabase } from './database.js';
|
||||||
|
import {
|
||||||
|
completeCurrent,
|
||||||
|
getLiveView,
|
||||||
|
getPresentationMedia,
|
||||||
|
getPresentationView,
|
||||||
|
goBack,
|
||||||
|
issuePresentationAccess,
|
||||||
|
moveOpenUsage,
|
||||||
|
presentUsage,
|
||||||
|
skipCurrent,
|
||||||
|
startOrResumeLive
|
||||||
|
} from './live.js';
|
||||||
|
|
||||||
|
let directory: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
directory = mkdtempSync(path.join(tmpdir(), 'sendewerk-live-test-'));
|
||||||
|
process.env.SENDEWERK_DB_PATH = path.join(directory, 'test.sqlite');
|
||||||
|
process.env.SENDEWERK_UPLOAD_DIR = path.join(directory, 'uploads');
|
||||||
|
execFileSync(process.execPath, ['scripts/migrate.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
execFileSync(process.execPath, ['scripts/seed.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
closeDatabase();
|
||||||
|
delete process.env.SENDEWERK_DB_PATH;
|
||||||
|
delete process.env.SENDEWERK_UPLOAD_DIR;
|
||||||
|
rmSync(directory, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('live mode', () => {
|
||||||
|
it('restores live state, records actual intervals and applies commands only once', () => {
|
||||||
|
const started = new Date('2026-10-22T18:00:00.000Z');
|
||||||
|
const initial = getLiveView('show-october', started);
|
||||||
|
expect(initial.current).toBeNull();
|
||||||
|
|
||||||
|
expect(startOrResumeLive('show-october', 'start-command', 0, started)).toEqual({
|
||||||
|
revision: 1,
|
||||||
|
duplicate: false
|
||||||
|
});
|
||||||
|
expect(startOrResumeLive('show-october', 'start-command', 0, started)).toEqual({
|
||||||
|
revision: 1,
|
||||||
|
duplicate: true
|
||||||
|
});
|
||||||
|
let live = getLiveView('show-october', new Date('2026-10-22T18:05:00.000Z'));
|
||||||
|
expect(live.current?.id).toBe('usage-console');
|
||||||
|
expect(live.current?.actualDurationSeconds).toBe(300);
|
||||||
|
expect(() =>
|
||||||
|
moveOpenUsage('show-october', 'usage-effects', live.show.revision, {
|
||||||
|
sectionId: 'section-stories',
|
||||||
|
position: 0
|
||||||
|
})
|
||||||
|
).toThrow('LIVE_ORDER_LOCKED');
|
||||||
|
|
||||||
|
completeCurrent('show-october', 'complete-console', 1, new Date('2026-10-22T18:05:00.000Z'));
|
||||||
|
completeCurrent('show-october', 'complete-console', 1, new Date('2026-10-22T18:05:00.000Z'));
|
||||||
|
live = getLiveView('show-october', new Date('2026-10-22T18:06:00.000Z'));
|
||||||
|
expect(live.current?.id).toBe('usage-effects');
|
||||||
|
expect(
|
||||||
|
live.sections
|
||||||
|
.flatMap((section) => section.usages)
|
||||||
|
.find((usage) => usage.id === 'usage-console')
|
||||||
|
).toMatchObject({ status: 'done', actualDurationSeconds: 300 });
|
||||||
|
expect(
|
||||||
|
getDatabase()
|
||||||
|
.prepare('SELECT count(*) AS count FROM live_usage_runs WHERE usage_id = ?')
|
||||||
|
.get('usage-console')
|
||||||
|
).toEqual({ count: 1 });
|
||||||
|
|
||||||
|
expect(() => skipCurrent('show-october', 'stale-command', 1)).toThrow('CONFLICT');
|
||||||
|
skipCurrent('show-october', 'skip-effects', 2, new Date('2026-10-22T18:06:00.000Z'));
|
||||||
|
live = getLiveView('show-october', new Date('2026-10-22T18:07:00.000Z'));
|
||||||
|
expect(live.current).toBeNull();
|
||||||
|
expect(live.completedCount).toBe(2);
|
||||||
|
|
||||||
|
goBack('show-october', 'back-effects', 3, new Date('2026-10-22T18:07:00.000Z'));
|
||||||
|
live = getLiveView('show-october', new Date('2026-10-22T18:08:00.000Z'));
|
||||||
|
expect(live.current).toMatchObject({ id: 'usage-effects', status: 'current' });
|
||||||
|
expect(live.current?.actualDurationSeconds).toBe(120);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('changes presentation only explicitly and exposes no private fields', async () => {
|
||||||
|
const uploads = process.env.SENDEWERK_UPLOAD_DIR!;
|
||||||
|
mkdirSync(uploads, { recursive: true });
|
||||||
|
writeFileSync(path.join(uploads, 'presentation.png'), Buffer.from('test-image'));
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO piece_media (id, piece_id, storage_name, original_name, mime_type,
|
||||||
|
byte_size, alt_text, position, created_at_utc) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(
|
||||||
|
'presentation-image',
|
||||||
|
'piece-console',
|
||||||
|
'presentation.png',
|
||||||
|
'private-original-name.png',
|
||||||
|
'image/png',
|
||||||
|
10,
|
||||||
|
'Konsole auf dem Tisch',
|
||||||
|
0,
|
||||||
|
'2026-10-22T18:00:00.000Z'
|
||||||
|
);
|
||||||
|
|
||||||
|
const token = issuePresentationAccess('show-october');
|
||||||
|
expect(getPresentationView(token)).toEqual({ revision: 0, content: null });
|
||||||
|
startOrResumeLive('show-october', 'start-output', 0);
|
||||||
|
expect(getPresentationView(token)).toEqual({ revision: 0, content: null });
|
||||||
|
|
||||||
|
presentUsage('show-october', 'usage-console', 'present-console', 1);
|
||||||
|
const output = getPresentationView(token)!;
|
||||||
|
expect(output.content).toMatchObject({
|
||||||
|
title: 'Die kleine Konsole mit dem großen Dreh',
|
||||||
|
images: [{ id: 'presentation-image', altText: 'Konsole auf dem Tisch' }]
|
||||||
|
});
|
||||||
|
const serialized = JSON.stringify(output);
|
||||||
|
expect(serialized).toContain('Weniger Leistung, mehr Idee.');
|
||||||
|
expect(serialized).not.toContain('Herstellerangaben');
|
||||||
|
expect(serialized).not.toContain('Moderationsstichpunkte');
|
||||||
|
expect(serialized).not.toContain('private-original-name');
|
||||||
|
expect(serialized).not.toContain('presentation.png');
|
||||||
|
|
||||||
|
const media = await getPresentationMedia(token, 'presentation-image');
|
||||||
|
expect(media?.data.toString()).toBe('test-image');
|
||||||
|
expect(await getPresentationMedia(token, 'unknown-image')).toBeNull();
|
||||||
|
|
||||||
|
const replacementToken = issuePresentationAccess('show-october');
|
||||||
|
expect(getPresentationView(token)).toBeNull();
|
||||||
|
expect(getPresentationView(replacementToken)?.content?.title).toBe(
|
||||||
|
'Die kleine Konsole mit dem großen Dreh'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('projects only snapshotted link and video data and changes players explicitly', () => {
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE piece_usages SET presentation_mode_snapshot = 'video',
|
||||||
|
presentation_source_label_snapshot = 'YouTube',
|
||||||
|
presentation_source_url_snapshot = 'https://youtu.be/dQw4w9WgXcQ',
|
||||||
|
presentation_source_timecode_snapshot = 75,
|
||||||
|
presentation_title_meta_snapshot = 'Videotitel',
|
||||||
|
presentation_site_name_snapshot = 'YouTube',
|
||||||
|
presentation_provider_snapshot = 'youtube',
|
||||||
|
presentation_provider_id_snapshot = 'dQw4w9WgXcQ'
|
||||||
|
WHERE id = 'usage-console'`
|
||||||
|
)
|
||||||
|
.run();
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE piece_usages SET presentation_mode_snapshot = 'link',
|
||||||
|
presentation_source_label_snapshot = 'Artikel',
|
||||||
|
presentation_source_url_snapshot = 'https://example.com/artikel',
|
||||||
|
presentation_title_meta_snapshot = 'Linktitel',
|
||||||
|
presentation_description_snapshot = 'Öffentlicher Anreißer',
|
||||||
|
presentation_site_name_snapshot = 'Example'
|
||||||
|
WHERE id = 'usage-effects'`
|
||||||
|
)
|
||||||
|
.run();
|
||||||
|
const token = issuePresentationAccess('show-october');
|
||||||
|
presentUsage('show-october', 'usage-console', 'present-video', 0);
|
||||||
|
expect(getPresentationView(token)?.content).toMatchObject({
|
||||||
|
mode: 'video',
|
||||||
|
previewTitle: 'Videotitel',
|
||||||
|
embedUrl: 'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?start=75',
|
||||||
|
source: { url: 'https://youtu.be/dQw4w9WgXcQ', timecodeSeconds: 75 }
|
||||||
|
});
|
||||||
|
|
||||||
|
presentUsage('show-october', 'usage-effects', 'present-link', 1);
|
||||||
|
const link = getPresentationView(token)!;
|
||||||
|
expect(link.content).toMatchObject({
|
||||||
|
mode: 'link',
|
||||||
|
previewTitle: 'Linktitel',
|
||||||
|
description: 'Öffentlicher Anreißer',
|
||||||
|
embedUrl: '',
|
||||||
|
source: { label: 'Artikel', url: 'https://example.com/artikel' }
|
||||||
|
});
|
||||||
|
const serialized = JSON.stringify(link);
|
||||||
|
expect(serialized).not.toContain('Herstellerangaben');
|
||||||
|
expect(serialized).not.toContain('Moderationsstichpunkte');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,623 @@
|
|||||||
|
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
||||||
|
import type Database from 'better-sqlite3';
|
||||||
|
import { getMediaFile } from './content.js';
|
||||||
|
import { getDatabase } from './database.js';
|
||||||
|
import { renderMarkdown } from './markdown.js';
|
||||||
|
import { buildEmbedUrl, fetchPresentationImage, type PresentationContent } from './presentation.js';
|
||||||
|
import {
|
||||||
|
getShow,
|
||||||
|
movePieceUsage,
|
||||||
|
type MovePieceUsageInput,
|
||||||
|
type PieceUsage,
|
||||||
|
type ShowSection
|
||||||
|
} from './shows.js';
|
||||||
|
|
||||||
|
type LiveStateRow = {
|
||||||
|
show_id: string;
|
||||||
|
revision: number;
|
||||||
|
current_usage_id: string | null;
|
||||||
|
started_at_utc: string | null;
|
||||||
|
ended_at_utc: string | null;
|
||||||
|
presentation_usage_id: string | null;
|
||||||
|
presentation_revision: number;
|
||||||
|
updated_at_utc: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OrderedUsageRow = {
|
||||||
|
id: string;
|
||||||
|
section_id: string;
|
||||||
|
section_name: string;
|
||||||
|
section_position: number;
|
||||||
|
position: number;
|
||||||
|
status: PieceUsage['status'];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LiveUsage = PieceUsage & {
|
||||||
|
sectionId: string;
|
||||||
|
sectionName: string;
|
||||||
|
actualDurationSeconds: number;
|
||||||
|
introHtml: string;
|
||||||
|
researchHtml: string;
|
||||||
|
moderationHtml: string;
|
||||||
|
transitionHtml: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LiveSection = Omit<ShowSection, 'usages'> & { usages: LiveUsage[] };
|
||||||
|
|
||||||
|
export type LiveView = {
|
||||||
|
show: {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
revision: number;
|
||||||
|
totalDurationSeconds: number;
|
||||||
|
};
|
||||||
|
liveRevision: number;
|
||||||
|
startedAtUtc: string | null;
|
||||||
|
updatedAtUtc: string;
|
||||||
|
presentationUsageId: string | null;
|
||||||
|
presentationRevision: number;
|
||||||
|
sections: LiveSection[];
|
||||||
|
reserve: LiveUsage[];
|
||||||
|
current: LiveUsage | null;
|
||||||
|
next: LiveUsage | null;
|
||||||
|
completedCount: number;
|
||||||
|
totalCount: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PresentationView = {
|
||||||
|
revision: number;
|
||||||
|
content: null | {
|
||||||
|
mode: PresentationContent['mode'];
|
||||||
|
title: string;
|
||||||
|
html: string;
|
||||||
|
source: PresentationContent['source'];
|
||||||
|
previewTitle: string;
|
||||||
|
description: string;
|
||||||
|
imageUrl: string;
|
||||||
|
siteName: string;
|
||||||
|
provider: PresentationContent['provider'];
|
||||||
|
providerId: string;
|
||||||
|
embedUrl: string;
|
||||||
|
sources: { label: string; url: string; timecodeSeconds: number | null }[];
|
||||||
|
images: { id: string; altText: string }[];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
function hashToken(token: string) {
|
||||||
|
return createHash('sha256').update(token).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
function nowIso(now?: Date) {
|
||||||
|
return (now ?? new Date()).toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireCommandId(commandId: string) {
|
||||||
|
if (!commandId || commandId.length > 200) throw new Error('INVALID_COMMAND');
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureLiveState(database: Database.Database, showId: string, now: string): LiveStateRow {
|
||||||
|
const show = database.prepare('SELECT 1 FROM shows WHERE id = ?').get(showId);
|
||||||
|
if (!show) throw new Error('NOT_FOUND');
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT OR IGNORE INTO show_live_states (show_id, updated_at_utc)
|
||||||
|
VALUES (?, ?)`
|
||||||
|
)
|
||||||
|
.run(showId, now);
|
||||||
|
return database
|
||||||
|
.prepare('SELECT * FROM show_live_states WHERE show_id = ?')
|
||||||
|
.get(showId) as LiveStateRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
function orderedUsages(database: Database.Database, showId: string): OrderedUsageRow[] {
|
||||||
|
return database
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.id, s.id AS section_id, s.name AS section_name,
|
||||||
|
s.position AS section_position, u.position, u.status
|
||||||
|
FROM piece_usages u JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
WHERE s.show_id = ? AND s.is_reserve_bank = 0
|
||||||
|
ORDER BY s.position, u.position`
|
||||||
|
)
|
||||||
|
.all(showId) as OrderedUsageRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function usageBelongsToShow(database: Database.Database, showId: string, usageId: string) {
|
||||||
|
const row = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT s.is_reserve_bank FROM piece_usages u
|
||||||
|
JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
WHERE u.id = ? AND s.show_id = ?`
|
||||||
|
)
|
||||||
|
.get(usageId, showId) as { is_reserve_bank: number } | undefined;
|
||||||
|
if (!row || row.is_reserve_bank) throw new Error('NOT_FOUND');
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeActiveRun(database: Database.Database, showId: string, now: string) {
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE live_usage_runs SET ended_at_utc = ?
|
||||||
|
WHERE show_id = ? AND ended_at_utc IS NULL`
|
||||||
|
)
|
||||||
|
.run(now, showId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function activateUsage(database: Database.Database, showId: string, usageId: string, now: string) {
|
||||||
|
usageBelongsToShow(database, showId, usageId);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE piece_usages SET status = 'open'
|
||||||
|
WHERE status = 'current' AND id != ? AND id IN (
|
||||||
|
SELECT u.id FROM piece_usages u JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
WHERE s.show_id = ?
|
||||||
|
)`
|
||||||
|
)
|
||||||
|
.run(usageId, showId);
|
||||||
|
database.prepare(`UPDATE piece_usages SET status = 'current' WHERE id = ?`).run(usageId);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO live_usage_runs (id, show_id, usage_id, started_at_utc)
|
||||||
|
VALUES (?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(randomUUID(), showId, usageId, now);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
'UPDATE show_live_states SET current_usage_id = ?, ended_at_utc = NULL WHERE show_id = ?'
|
||||||
|
)
|
||||||
|
.run(usageId, showId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function executeCommand(
|
||||||
|
showId: string,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
action: string,
|
||||||
|
operation: (database: Database.Database, state: LiveStateRow, now: string) => void,
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
requireCommandId(commandId);
|
||||||
|
const database = getDatabase();
|
||||||
|
return database.transaction(() => {
|
||||||
|
const duplicate = database
|
||||||
|
.prepare('SELECT result_revision FROM live_commands WHERE show_id = ? AND command_id = ?')
|
||||||
|
.get(showId, commandId) as { result_revision: number } | undefined;
|
||||||
|
if (duplicate) return { revision: duplicate.result_revision, duplicate: true };
|
||||||
|
const now = nowIso(nowValue);
|
||||||
|
const state = ensureLiveState(database, showId, now);
|
||||||
|
const show = database.prepare('SELECT status FROM shows WHERE id = ?').get(showId) as {
|
||||||
|
status: string;
|
||||||
|
};
|
||||||
|
if (show.status === 'completed') throw new Error('SHOW_COMPLETED');
|
||||||
|
if (state.revision !== expectedRevision) throw new Error('CONFLICT');
|
||||||
|
operation(database, state, now);
|
||||||
|
const updated = database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE show_live_states SET revision = revision + 1, updated_at_utc = ?
|
||||||
|
WHERE show_id = ? AND revision = ?`
|
||||||
|
)
|
||||||
|
.run(now, showId, expectedRevision);
|
||||||
|
if (updated.changes !== 1) throw new Error('CONFLICT');
|
||||||
|
const revision = expectedRevision + 1;
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO live_commands (show_id, command_id, action, result_revision, created_at_utc)
|
||||||
|
VALUES (?, ?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(showId, commandId, action, revision, now);
|
||||||
|
return { revision, duplicate: false };
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
function actualDurations(database: Database.Database, showId: string, now: string) {
|
||||||
|
const rows = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT usage_id, started_at_utc, ended_at_utc
|
||||||
|
FROM live_usage_runs WHERE show_id = ?`
|
||||||
|
)
|
||||||
|
.all(showId) as { usage_id: string; started_at_utc: string; ended_at_utc: string | null }[];
|
||||||
|
const durations = new Map<string, number>();
|
||||||
|
for (const row of rows) {
|
||||||
|
const seconds = Math.max(
|
||||||
|
0,
|
||||||
|
Math.floor(
|
||||||
|
(new Date(row.ended_at_utc ?? now).getTime() - new Date(row.started_at_utc).getTime()) /
|
||||||
|
1000
|
||||||
|
)
|
||||||
|
);
|
||||||
|
durations.set(row.usage_id, (durations.get(row.usage_id) ?? 0) + seconds);
|
||||||
|
}
|
||||||
|
return durations;
|
||||||
|
}
|
||||||
|
|
||||||
|
function liveUsage(
|
||||||
|
usage: PieceUsage,
|
||||||
|
sectionId: string,
|
||||||
|
sectionName: string,
|
||||||
|
actualSeconds: number
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
...usage,
|
||||||
|
sectionId,
|
||||||
|
sectionName,
|
||||||
|
actualDurationSeconds: actualSeconds,
|
||||||
|
introHtml: renderMarkdown(usage.intro),
|
||||||
|
researchHtml: renderMarkdown(usage.research),
|
||||||
|
moderationHtml: renderMarkdown(usage.moderation),
|
||||||
|
transitionHtml: renderMarkdown(usage.transition)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLiveView(showId: string, nowValue?: Date): LiveView {
|
||||||
|
const database = getDatabase();
|
||||||
|
const now = nowIso(nowValue);
|
||||||
|
const state = ensureLiveState(database, showId, now);
|
||||||
|
const show = getShow(showId);
|
||||||
|
if (!show) throw new Error('NOT_FOUND');
|
||||||
|
const durations = actualDurations(database, showId, now);
|
||||||
|
const sections = show.sections.map((section) => ({
|
||||||
|
...section,
|
||||||
|
usages: section.usages.map((usage) =>
|
||||||
|
liveUsage(usage, section.id, section.name, durations.get(usage.id) ?? 0)
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
const reserve = show.reserve.map((usage) =>
|
||||||
|
liveUsage(usage, '', 'Reservebank', durations.get(usage.id) ?? 0)
|
||||||
|
);
|
||||||
|
const usages = sections.flatMap((section) => section.usages);
|
||||||
|
const current = usages.find((usage) => usage.id === state.current_usage_id) ?? null;
|
||||||
|
const currentIndex = current ? usages.findIndex((usage) => usage.id === current.id) : -1;
|
||||||
|
const next =
|
||||||
|
usages.slice(currentIndex + 1).find((usage) => usage.status === 'open') ??
|
||||||
|
(current ? null : (usages.find((usage) => usage.status === 'open') ?? null));
|
||||||
|
return {
|
||||||
|
show: {
|
||||||
|
id: show.id,
|
||||||
|
title: show.title,
|
||||||
|
status: show.status,
|
||||||
|
revision: show.revision,
|
||||||
|
totalDurationSeconds: show.totalDurationSeconds
|
||||||
|
},
|
||||||
|
liveRevision: state.revision,
|
||||||
|
startedAtUtc: state.started_at_utc,
|
||||||
|
updatedAtUtc: state.updated_at_utc,
|
||||||
|
presentationUsageId: state.presentation_usage_id,
|
||||||
|
presentationRevision: state.presentation_revision,
|
||||||
|
sections,
|
||||||
|
reserve,
|
||||||
|
current,
|
||||||
|
next,
|
||||||
|
completedCount: usages.filter((usage) => usage.status === 'done' || usage.status === 'skipped')
|
||||||
|
.length,
|
||||||
|
totalCount: usages.length
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startOrResumeLive(
|
||||||
|
showId: string,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
return executeCommand(
|
||||||
|
showId,
|
||||||
|
commandId,
|
||||||
|
expectedRevision,
|
||||||
|
'start',
|
||||||
|
(database, state, now) => {
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE shows SET status = 'live', updated_at_utc = ?
|
||||||
|
WHERE id = ? AND status != 'completed'`
|
||||||
|
)
|
||||||
|
.run(now, showId);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE show_live_states SET started_at_utc = COALESCE(started_at_utc, ?), ended_at_utc = NULL
|
||||||
|
WHERE show_id = ?`
|
||||||
|
)
|
||||||
|
.run(now, showId);
|
||||||
|
const activeRun = database
|
||||||
|
.prepare('SELECT 1 FROM live_usage_runs WHERE show_id = ? AND ended_at_utc IS NULL')
|
||||||
|
.get(showId);
|
||||||
|
if (state.current_usage_id && activeRun) return;
|
||||||
|
const current = state.current_usage_id
|
||||||
|
? orderedUsages(database, showId).find((usage) => usage.id === state.current_usage_id)
|
||||||
|
: undefined;
|
||||||
|
const target =
|
||||||
|
current ?? orderedUsages(database, showId).find((usage) => usage.status === 'open');
|
||||||
|
if (target) activateUsage(database, showId, target.id, now);
|
||||||
|
},
|
||||||
|
nowValue
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function advanceCurrent(
|
||||||
|
showId: string,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
status: 'done' | 'skipped',
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
return executeCommand(
|
||||||
|
showId,
|
||||||
|
commandId,
|
||||||
|
expectedRevision,
|
||||||
|
status,
|
||||||
|
(database, state, now) => {
|
||||||
|
if (!state.current_usage_id) throw new Error('NO_CURRENT');
|
||||||
|
const ordered = orderedUsages(database, showId);
|
||||||
|
const currentIndex = ordered.findIndex((usage) => usage.id === state.current_usage_id);
|
||||||
|
if (currentIndex < 0) throw new Error('NOT_FOUND');
|
||||||
|
closeActiveRun(database, showId, now);
|
||||||
|
database
|
||||||
|
.prepare('UPDATE piece_usages SET status = ? WHERE id = ?')
|
||||||
|
.run(status, state.current_usage_id);
|
||||||
|
const next = ordered.slice(currentIndex + 1).find((usage) => usage.status === 'open');
|
||||||
|
if (next) activateUsage(database, showId, next.id, now);
|
||||||
|
else
|
||||||
|
database
|
||||||
|
.prepare('UPDATE show_live_states SET current_usage_id = NULL WHERE show_id = ?')
|
||||||
|
.run(showId);
|
||||||
|
},
|
||||||
|
nowValue
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function completeCurrent(
|
||||||
|
showId: string,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
return advanceCurrent(showId, commandId, expectedRevision, 'done', nowValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function skipCurrent(
|
||||||
|
showId: string,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
return advanceCurrent(showId, commandId, expectedRevision, 'skipped', nowValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function goBack(
|
||||||
|
showId: string,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
return executeCommand(
|
||||||
|
showId,
|
||||||
|
commandId,
|
||||||
|
expectedRevision,
|
||||||
|
'back',
|
||||||
|
(database, state, now) => {
|
||||||
|
const ordered = orderedUsages(database, showId);
|
||||||
|
const currentIndex = state.current_usage_id
|
||||||
|
? ordered.findIndex((usage) => usage.id === state.current_usage_id)
|
||||||
|
: ordered.length;
|
||||||
|
const previous = ordered
|
||||||
|
.slice(0, Math.max(0, currentIndex))
|
||||||
|
.reverse()
|
||||||
|
.find((usage) => usage.status === 'done' || usage.status === 'skipped');
|
||||||
|
if (!previous) throw new Error('NO_PREVIOUS');
|
||||||
|
if (state.current_usage_id) {
|
||||||
|
closeActiveRun(database, showId, now);
|
||||||
|
database
|
||||||
|
.prepare(`UPDATE piece_usages SET status = 'open' WHERE id = ?`)
|
||||||
|
.run(state.current_usage_id);
|
||||||
|
}
|
||||||
|
activateUsage(database, showId, previous.id, now);
|
||||||
|
},
|
||||||
|
nowValue
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function presentUsage(
|
||||||
|
showId: string,
|
||||||
|
usageId: string | null,
|
||||||
|
commandId: string,
|
||||||
|
expectedRevision: number,
|
||||||
|
nowValue?: Date
|
||||||
|
) {
|
||||||
|
return executeCommand(
|
||||||
|
showId,
|
||||||
|
commandId,
|
||||||
|
expectedRevision,
|
||||||
|
usageId ? 'present' : 'clear-presentation',
|
||||||
|
(database, _state, now) => {
|
||||||
|
if (usageId) usageBelongsToShow(database, showId, usageId);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`UPDATE show_live_states SET presentation_usage_id = ?,
|
||||||
|
presentation_revision = presentation_revision + 1, updated_at_utc = ?
|
||||||
|
WHERE show_id = ?`
|
||||||
|
)
|
||||||
|
.run(usageId, now, showId);
|
||||||
|
},
|
||||||
|
nowValue
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function moveOpenUsage(
|
||||||
|
showId: string,
|
||||||
|
usageId: string,
|
||||||
|
expectedShowRevision: number,
|
||||||
|
input: MovePieceUsageInput
|
||||||
|
) {
|
||||||
|
const database = getDatabase();
|
||||||
|
const usage = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.status FROM piece_usages u JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
WHERE u.id = ? AND s.show_id = ?`
|
||||||
|
)
|
||||||
|
.get(usageId, showId) as { status: PieceUsage['status'] } | undefined;
|
||||||
|
if (!usage) throw new Error('NOT_FOUND');
|
||||||
|
if (usage.status !== 'open') throw new Error('LIVE_ORDER_LOCKED');
|
||||||
|
if (input.sectionId) {
|
||||||
|
const target = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.id, u.status FROM piece_usages u JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
WHERE s.id = ? AND s.show_id = ? AND s.is_reserve_bank = 0 ORDER BY u.position`
|
||||||
|
)
|
||||||
|
.all(input.sectionId, showId) as { id: string; status: PieceUsage['status'] }[];
|
||||||
|
if (!target.length) {
|
||||||
|
const section = database
|
||||||
|
.prepare('SELECT 1 FROM show_sections WHERE id = ? AND show_id = ? AND is_reserve_bank = 0')
|
||||||
|
.get(input.sectionId, showId);
|
||||||
|
if (!section) throw new Error('NOT_FOUND');
|
||||||
|
}
|
||||||
|
const withoutMoved = target.filter((item) => item.id !== usageId);
|
||||||
|
const firstOpenPosition = withoutMoved.findIndex((item) => item.status === 'open');
|
||||||
|
const minimum = firstOpenPosition < 0 ? withoutMoved.length : firstOpenPosition;
|
||||||
|
if (input.position < minimum) throw new Error('LIVE_ORDER_LOCKED');
|
||||||
|
}
|
||||||
|
return movePieceUsage(showId, usageId, expectedShowRevision, input);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function issuePresentationAccess(showId: string) {
|
||||||
|
const database = getDatabase();
|
||||||
|
const now = nowIso();
|
||||||
|
ensureLiveState(database, showId, now);
|
||||||
|
const token = randomBytes(32).toString('base64url');
|
||||||
|
database.transaction(() => {
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
'UPDATE presentation_access_tokens SET revoked_at_utc = ? WHERE show_id = ? AND revoked_at_utc IS NULL'
|
||||||
|
)
|
||||||
|
.run(now, showId);
|
||||||
|
database
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO presentation_access_tokens (id, show_id, token_hash, created_at_utc)
|
||||||
|
VALUES (?, ?, ?, ?)`
|
||||||
|
)
|
||||||
|
.run(randomUUID(), showId, hashToken(token), now);
|
||||||
|
})();
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
function presentationShowId(database: Database.Database, token: string) {
|
||||||
|
if (!token || token.length > 200) return null;
|
||||||
|
const row = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT show_id FROM presentation_access_tokens
|
||||||
|
WHERE token_hash = ? AND revoked_at_utc IS NULL`
|
||||||
|
)
|
||||||
|
.get(hashToken(token)) as { show_id: string } | undefined;
|
||||||
|
return row?.show_id ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getPresentationView(token: string): PresentationView | null {
|
||||||
|
const database = getDatabase();
|
||||||
|
const showId = presentationShowId(database, token);
|
||||||
|
if (!showId) return null;
|
||||||
|
const state = ensureLiveState(database, showId, nowIso());
|
||||||
|
if (!state.presentation_usage_id) return { revision: state.presentation_revision, content: null };
|
||||||
|
const usage = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT u.title_snapshot, u.presentation_snapshot, u.original_piece_id,
|
||||||
|
u.presentation_mode_snapshot, u.presentation_source_label_snapshot,
|
||||||
|
u.presentation_source_url_snapshot, u.presentation_source_timecode_snapshot,
|
||||||
|
u.presentation_title_meta_snapshot, u.presentation_description_snapshot,
|
||||||
|
u.presentation_image_url_snapshot, u.presentation_site_name_snapshot,
|
||||||
|
u.presentation_provider_snapshot, u.presentation_provider_id_snapshot
|
||||||
|
FROM piece_usages u JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
WHERE u.id = ? AND s.show_id = ? AND s.is_reserve_bank = 0`
|
||||||
|
)
|
||||||
|
.get(state.presentation_usage_id, showId) as
|
||||||
|
| {
|
||||||
|
title_snapshot: string;
|
||||||
|
presentation_snapshot: string;
|
||||||
|
original_piece_id: string | null;
|
||||||
|
presentation_mode_snapshot: PresentationContent['mode'];
|
||||||
|
presentation_source_label_snapshot: string;
|
||||||
|
presentation_source_url_snapshot: string;
|
||||||
|
presentation_source_timecode_snapshot: number | null;
|
||||||
|
presentation_title_meta_snapshot: string;
|
||||||
|
presentation_description_snapshot: string;
|
||||||
|
presentation_image_url_snapshot: string;
|
||||||
|
presentation_site_name_snapshot: string;
|
||||||
|
presentation_provider_snapshot: PresentationContent['provider'];
|
||||||
|
presentation_provider_id_snapshot: string;
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
if (!usage) return { revision: state.presentation_revision, content: null };
|
||||||
|
const sources =
|
||||||
|
usage.presentation_mode_snapshot === 'text' && usage.original_piece_id
|
||||||
|
? (database
|
||||||
|
.prepare(
|
||||||
|
`SELECT label, url, timecode_seconds AS timecodeSeconds
|
||||||
|
FROM piece_sources WHERE piece_id = ? ORDER BY position`
|
||||||
|
)
|
||||||
|
.all(usage.original_piece_id) as {
|
||||||
|
label: string;
|
||||||
|
url: string;
|
||||||
|
timecodeSeconds: number | null;
|
||||||
|
}[])
|
||||||
|
: [];
|
||||||
|
const images =
|
||||||
|
usage.presentation_mode_snapshot === 'text' && usage.original_piece_id
|
||||||
|
? (database
|
||||||
|
.prepare(
|
||||||
|
`SELECT id, alt_text AS altText FROM piece_media
|
||||||
|
WHERE piece_id = ? ORDER BY position`
|
||||||
|
)
|
||||||
|
.all(usage.original_piece_id) as { id: string; altText: string }[])
|
||||||
|
: [];
|
||||||
|
return {
|
||||||
|
revision: state.presentation_revision,
|
||||||
|
content: {
|
||||||
|
mode: usage.presentation_mode_snapshot,
|
||||||
|
title: usage.title_snapshot,
|
||||||
|
html: renderMarkdown(usage.presentation_snapshot),
|
||||||
|
source: usage.presentation_source_url_snapshot
|
||||||
|
? {
|
||||||
|
label: usage.presentation_source_label_snapshot,
|
||||||
|
url: usage.presentation_source_url_snapshot,
|
||||||
|
timecodeSeconds: usage.presentation_source_timecode_snapshot
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
previewTitle: usage.presentation_title_meta_snapshot,
|
||||||
|
description: usage.presentation_description_snapshot,
|
||||||
|
imageUrl: usage.presentation_image_url_snapshot,
|
||||||
|
siteName: usage.presentation_site_name_snapshot,
|
||||||
|
provider: usage.presentation_provider_snapshot,
|
||||||
|
providerId: usage.presentation_provider_id_snapshot,
|
||||||
|
embedUrl: buildEmbedUrl(
|
||||||
|
usage.presentation_provider_snapshot,
|
||||||
|
usage.presentation_provider_id_snapshot,
|
||||||
|
usage.presentation_source_timecode_snapshot
|
||||||
|
),
|
||||||
|
sources,
|
||||||
|
images
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPresentationPreviewImage(token: string) {
|
||||||
|
const view = getPresentationView(token);
|
||||||
|
if (!view?.content?.imageUrl || view.content.mode === 'text') return null;
|
||||||
|
try {
|
||||||
|
return await fetchPresentationImage(view.content.imageUrl);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPresentationMedia(token: string, mediaId: string) {
|
||||||
|
const database = getDatabase();
|
||||||
|
const showId = presentationShowId(database, token);
|
||||||
|
if (!showId) return null;
|
||||||
|
const allowed = database
|
||||||
|
.prepare(
|
||||||
|
`SELECT 1 FROM show_live_states l
|
||||||
|
JOIN piece_usages u ON u.id = l.presentation_usage_id
|
||||||
|
JOIN show_sections s ON s.id = u.show_section_id
|
||||||
|
JOIN piece_media m ON m.piece_id = u.original_piece_id
|
||||||
|
WHERE l.show_id = ? AND s.show_id = ? AND m.id = ?`
|
||||||
|
)
|
||||||
|
.get(showId, showId, mediaId);
|
||||||
|
if (!allowed) return null;
|
||||||
|
return getMediaFile(mediaId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { mkdir, writeFile } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
import { getMailConfig, getServerPaths } from './config.js';
|
||||||
|
|
||||||
|
export type MailMessage = {
|
||||||
|
to: string;
|
||||||
|
subject: string;
|
||||||
|
text: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function sendMail(message: MailMessage): Promise<'local' | 'smtp'> {
|
||||||
|
const config = getMailConfig();
|
||||||
|
if (config.transport === 'local') {
|
||||||
|
const outbox = getServerPaths().mailOutbox;
|
||||||
|
await mkdir(outbox, { recursive: true, mode: 0o700 });
|
||||||
|
const filename = `${new Date().toISOString().replaceAll(':', '-')}-${randomUUID()}.json`;
|
||||||
|
await writeFile(
|
||||||
|
path.join(outbox, filename),
|
||||||
|
JSON.stringify({ from: config.from, ...message }, null, 2),
|
||||||
|
{ encoding: 'utf8', mode: 0o600 }
|
||||||
|
);
|
||||||
|
return 'local';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
!config.host ||
|
||||||
|
!config.from ||
|
||||||
|
!Number.isInteger(config.port) ||
|
||||||
|
config.port < 1 ||
|
||||||
|
config.port > 65_535 ||
|
||||||
|
Boolean(config.user) !== Boolean(config.password)
|
||||||
|
) {
|
||||||
|
throw new Error('Die SMTP-Konfiguration ist unvollständig.');
|
||||||
|
}
|
||||||
|
const transporter = nodemailer.createTransport({
|
||||||
|
host: config.host,
|
||||||
|
port: config.port,
|
||||||
|
secure: config.secure,
|
||||||
|
requireTLS: !config.secure,
|
||||||
|
connectionTimeout: 10_000,
|
||||||
|
greetingTimeout: 10_000,
|
||||||
|
socketTimeout: 20_000,
|
||||||
|
auth: config.user ? { user: config.user, pass: config.password } : undefined
|
||||||
|
});
|
||||||
|
await transporter.sendMail({ from: config.from, ...message });
|
||||||
|
return 'smtp';
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { marked } from 'marked';
|
||||||
|
import sanitizeHtml from 'sanitize-html';
|
||||||
|
|
||||||
|
export function renderMarkdown(markdown: string): string {
|
||||||
|
const rendered = marked.parse(markdown, {
|
||||||
|
async: false,
|
||||||
|
breaks: true,
|
||||||
|
gfm: true
|
||||||
|
}) as string;
|
||||||
|
return sanitizeHtml(rendered, {
|
||||||
|
allowedTags: [
|
||||||
|
'p',
|
||||||
|
'br',
|
||||||
|
'strong',
|
||||||
|
'em',
|
||||||
|
'del',
|
||||||
|
'blockquote',
|
||||||
|
'ul',
|
||||||
|
'ol',
|
||||||
|
'li',
|
||||||
|
'h2',
|
||||||
|
'h3',
|
||||||
|
'h4',
|
||||||
|
'code',
|
||||||
|
'pre',
|
||||||
|
'a',
|
||||||
|
'hr'
|
||||||
|
],
|
||||||
|
allowedAttributes: {
|
||||||
|
a: ['href', 'title', 'target', 'rel']
|
||||||
|
},
|
||||||
|
allowedSchemes: ['http', 'https', 'mailto'],
|
||||||
|
allowProtocolRelative: false,
|
||||||
|
enforceHtmlBoundary: true,
|
||||||
|
transformTags: {
|
||||||
|
a: (_tagName, attributes) => ({
|
||||||
|
tagName: 'a',
|
||||||
|
attribs: { ...attributes, target: '_blank', rel: 'noopener noreferrer' }
|
||||||
|
})
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
buildEmbedUrl,
|
||||||
|
detectVideoProvider,
|
||||||
|
extractMetadataFromHtml,
|
||||||
|
fetchPresentationMetadata
|
||||||
|
} from './presentation.js';
|
||||||
|
|
||||||
|
describe('presentation metadata and providers', () => {
|
||||||
|
it('recognizes supported YouTube URL forms and creates privacy-enhanced embeds with start time', () => {
|
||||||
|
for (const url of [
|
||||||
|
'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
|
||||||
|
'https://youtu.be/dQw4w9WgXcQ',
|
||||||
|
'https://www.youtube.com/shorts/dQw4w9WgXcQ',
|
||||||
|
'https://youtube.com/live/dQw4w9WgXcQ'
|
||||||
|
]) {
|
||||||
|
expect(detectVideoProvider(url)).toEqual({ provider: 'youtube', id: 'dQw4w9WgXcQ' });
|
||||||
|
}
|
||||||
|
expect(buildEmbedUrl('youtube', 'dQw4w9WgXcQ', 75)).toBe(
|
||||||
|
'https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?start=75'
|
||||||
|
);
|
||||||
|
expect(detectVideoProvider('https://evil.example/watch?v=dQw4w9WgXcQ')).toBeNull();
|
||||||
|
expect(detectVideoProvider('https://youtube.com/watch?v=invalid')).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recognizes canonical TikTok videos without inventing a start parameter', () => {
|
||||||
|
expect(
|
||||||
|
detectVideoProvider('https://www.tiktok.com/@scout2015/video/6718335390845095173')
|
||||||
|
).toEqual({ provider: 'tiktok', id: '6718335390845095173' });
|
||||||
|
expect(buildEmbedUrl('tiktok', '6718335390845095173', 90)).toBe(
|
||||||
|
'https://www.tiktok.com/player/v1/6718335390845095173?autoplay=0&controls=1'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts generic metadata from local HTML and tolerates a missing image', async () => {
|
||||||
|
const metadata = await extractMetadataFromHtml(
|
||||||
|
`<!doctype html><html><head>
|
||||||
|
<meta property="og:title" content="Lokale Vorschau">
|
||||||
|
<meta property="og:description" content="Ein kurzer Anreißer">
|
||||||
|
<meta property="og:site_name" content="Testseite">
|
||||||
|
</head></html>`,
|
||||||
|
'https://example.com/artikel'
|
||||||
|
);
|
||||||
|
expect(metadata).toMatchObject({
|
||||||
|
title: 'Lokale Vorschau',
|
||||||
|
description: 'Ein kurzer Anreißer',
|
||||||
|
imageUrl: '',
|
||||||
|
siteName: 'Testseite'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed and private metadata targets before a network request', async () => {
|
||||||
|
await expect(fetchPresentationMetadata('keine-url')).rejects.toThrow('FETCH_INVALID_URL');
|
||||||
|
await expect(fetchPresentationMetadata('http://127.0.0.1/private')).rejects.toThrow(
|
||||||
|
'FETCH_BLOCKED'
|
||||||
|
);
|
||||||
|
await expect(fetchPresentationMetadata('http://[::1]/private')).rejects.toThrow(
|
||||||
|
'FETCH_BLOCKED'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
import { lookup } from 'node:dns/promises';
|
||||||
|
import { isIP } from 'node:net';
|
||||||
|
import http from 'node:http';
|
||||||
|
import https from 'node:https';
|
||||||
|
import metascraper from 'metascraper';
|
||||||
|
import description from 'metascraper-description';
|
||||||
|
import image from 'metascraper-image';
|
||||||
|
import publisher from 'metascraper-publisher';
|
||||||
|
import title from 'metascraper-title';
|
||||||
|
|
||||||
|
export type PresentationMode = 'text' | 'link' | 'video';
|
||||||
|
export type VideoProvider = 'youtube' | 'tiktok';
|
||||||
|
|
||||||
|
export type PresentationMetadata = {
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
imageUrl: string;
|
||||||
|
siteName: string;
|
||||||
|
provider: VideoProvider | '';
|
||||||
|
providerId: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PresentationSource = {
|
||||||
|
label: string;
|
||||||
|
url: string;
|
||||||
|
timecodeSeconds: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PresentationContent = {
|
||||||
|
mode: PresentationMode;
|
||||||
|
title: string;
|
||||||
|
html: string;
|
||||||
|
source: PresentationSource | null;
|
||||||
|
previewTitle: string;
|
||||||
|
description: string;
|
||||||
|
imageUrl: string;
|
||||||
|
siteName: string;
|
||||||
|
provider: VideoProvider | '';
|
||||||
|
providerId: string;
|
||||||
|
embedUrl: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const scrape = metascraper([title(), description({ truncateLength: 500 }), image(), publisher()]);
|
||||||
|
const MAX_HTML_BYTES = 1024 * 1024;
|
||||||
|
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
||||||
|
const REQUEST_TIMEOUT_MS = 5_000;
|
||||||
|
const MAX_REDIRECTS = 3;
|
||||||
|
|
||||||
|
function isPrivateIpv4(address: string) {
|
||||||
|
const parts = address.split('.').map(Number);
|
||||||
|
return (
|
||||||
|
parts[0] === 0 ||
|
||||||
|
parts[0] === 10 ||
|
||||||
|
parts[0] === 127 ||
|
||||||
|
(parts[0] === 169 && parts[1] === 254) ||
|
||||||
|
(parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
|
||||||
|
(parts[0] === 192 && parts[1] === 168) ||
|
||||||
|
(parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) ||
|
||||||
|
parts[0] >= 224
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPrivateAddress(address: string) {
|
||||||
|
if (isIP(address) === 4) return isPrivateIpv4(address);
|
||||||
|
const normalized = address.toLowerCase().split('%')[0];
|
||||||
|
if (normalized === '::' || normalized === '::1') return true;
|
||||||
|
if (normalized.startsWith('fc') || normalized.startsWith('fd') || normalized.startsWith('fe8')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
normalized.startsWith('fe9') ||
|
||||||
|
normalized.startsWith('fea') ||
|
||||||
|
normalized.startsWith('feb')
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const mapped = normalized.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1];
|
||||||
|
return mapped ? isPrivateIpv4(mapped) : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publicAddress(url: URL) {
|
||||||
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
|
||||||
|
throw new Error('FETCH_BLOCKED');
|
||||||
|
}
|
||||||
|
if (url.port && url.port !== (url.protocol === 'https:' ? '443' : '80')) {
|
||||||
|
throw new Error('FETCH_BLOCKED');
|
||||||
|
}
|
||||||
|
const hostname = url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname;
|
||||||
|
if (hostname === 'localhost' || hostname.endsWith('.localhost')) {
|
||||||
|
throw new Error('FETCH_BLOCKED');
|
||||||
|
}
|
||||||
|
const addresses = isIP(hostname)
|
||||||
|
? [{ address: hostname, family: isIP(hostname) }]
|
||||||
|
: await lookup(hostname, { all: true, verbatim: true }).catch(() => {
|
||||||
|
throw new Error('FETCH_UNAVAILABLE');
|
||||||
|
});
|
||||||
|
if (!addresses.length || addresses.some((entry) => isPrivateAddress(entry.address))) {
|
||||||
|
throw new Error('FETCH_BLOCKED');
|
||||||
|
}
|
||||||
|
return addresses[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requestPublic(
|
||||||
|
input: string,
|
||||||
|
accept: string,
|
||||||
|
maximumBytes: number,
|
||||||
|
redirects = 0
|
||||||
|
): Promise<{ url: string; contentType: string; data: Buffer }> {
|
||||||
|
let url: URL;
|
||||||
|
try {
|
||||||
|
url = new URL(input);
|
||||||
|
} catch {
|
||||||
|
throw new Error('FETCH_INVALID_URL');
|
||||||
|
}
|
||||||
|
const target = await publicAddress(url);
|
||||||
|
const client = url.protocol === 'https:' ? https : http;
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const request = client.get(
|
||||||
|
url,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Accept: accept,
|
||||||
|
'User-Agent': 'Sendewerk/0.5.1 (+https://git.hnz.io/hnzio/sendewerk)'
|
||||||
|
},
|
||||||
|
lookup: (_hostname, _options, callback) =>
|
||||||
|
callback(null, target.address, target.family as 4 | 6)
|
||||||
|
},
|
||||||
|
(response) => {
|
||||||
|
const status = response.statusCode ?? 0;
|
||||||
|
if (status >= 300 && status < 400 && response.headers.location) {
|
||||||
|
response.resume();
|
||||||
|
if (redirects >= MAX_REDIRECTS) return reject(new Error('FETCH_REDIRECTS'));
|
||||||
|
const next = new URL(response.headers.location, url).href;
|
||||||
|
requestPublic(next, accept, maximumBytes, redirects + 1).then(resolve, reject);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (status < 200 || status >= 300) {
|
||||||
|
response.resume();
|
||||||
|
return reject(new Error('FETCH_UNAVAILABLE'));
|
||||||
|
}
|
||||||
|
const chunks: Buffer[] = [];
|
||||||
|
let size = 0;
|
||||||
|
response.on('data', (chunk: Buffer) => {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > maximumBytes) {
|
||||||
|
request.destroy(new Error('FETCH_TOO_LARGE'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
response.on('end', () =>
|
||||||
|
resolve({
|
||||||
|
url: url.href,
|
||||||
|
contentType: String(response.headers['content-type'] ?? ''),
|
||||||
|
data: Buffer.concat(chunks)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
request.setTimeout(REQUEST_TIMEOUT_MS, () => request.destroy(new Error('FETCH_TIMEOUT')));
|
||||||
|
request.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function detectVideoProvider(input: string): {
|
||||||
|
provider: VideoProvider;
|
||||||
|
id: string;
|
||||||
|
} | null {
|
||||||
|
let url: URL;
|
||||||
|
try {
|
||||||
|
url = new URL(input);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (url.protocol !== 'https:' || url.username || url.password || url.port) return null;
|
||||||
|
const host = url.hostname.toLowerCase();
|
||||||
|
let youtubeId = '';
|
||||||
|
if (host === 'youtu.be') youtubeId = url.pathname.split('/').filter(Boolean)[0] ?? '';
|
||||||
|
if (host === 'youtube.com' || host === 'www.youtube.com' || host === 'm.youtube.com') {
|
||||||
|
if (url.pathname === '/watch') youtubeId = url.searchParams.get('v') ?? '';
|
||||||
|
else if (/^\/(shorts|embed|live)\//.test(url.pathname)) {
|
||||||
|
youtubeId = url.pathname.split('/').filter(Boolean)[1] ?? '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (/^[A-Za-z0-9_-]{11}$/.test(youtubeId)) {
|
||||||
|
return { provider: 'youtube', id: youtubeId };
|
||||||
|
}
|
||||||
|
if (host === 'tiktok.com' || host === 'www.tiktok.com' || host === 'm.tiktok.com') {
|
||||||
|
const id = url.pathname.match(/\/video\/(\d+)/)?.[1] ?? '';
|
||||||
|
if (/^\d+$/.test(id)) return { provider: 'tiktok', id };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildEmbedUrl(
|
||||||
|
provider: VideoProvider | '',
|
||||||
|
providerId: string,
|
||||||
|
timecodeSeconds: number | null
|
||||||
|
) {
|
||||||
|
if (provider === 'youtube' && /^[A-Za-z0-9_-]{11}$/.test(providerId)) {
|
||||||
|
const url = new URL(`https://www.youtube-nocookie.com/embed/${providerId}`);
|
||||||
|
if (timecodeSeconds && timecodeSeconds > 0)
|
||||||
|
url.searchParams.set('start', String(timecodeSeconds));
|
||||||
|
return url.href;
|
||||||
|
}
|
||||||
|
if (provider === 'tiktok' && /^\d+$/.test(providerId)) {
|
||||||
|
const url = new URL(`https://www.tiktok.com/player/v1/${providerId}`);
|
||||||
|
url.searchParams.set('autoplay', '0');
|
||||||
|
url.searchParams.set('controls', '1');
|
||||||
|
return url.href;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function extractMetadataFromHtml(
|
||||||
|
html: string,
|
||||||
|
url: string
|
||||||
|
): Promise<PresentationMetadata> {
|
||||||
|
const metadata = await scrape({ html, url });
|
||||||
|
return {
|
||||||
|
title: String(metadata.title ?? '').slice(0, 300),
|
||||||
|
description: String(metadata.description ?? '').slice(0, 1_000),
|
||||||
|
imageUrl: String(metadata.image ?? '').slice(0, 2_000),
|
||||||
|
siteName: String(metadata.publisher ?? new URL(url).hostname).slice(0, 200),
|
||||||
|
provider: '',
|
||||||
|
providerId: ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function providerMetadata(url: string, provider: VideoProvider) {
|
||||||
|
const endpoint =
|
||||||
|
provider === 'youtube'
|
||||||
|
? `https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(url)}`
|
||||||
|
: `https://www.tiktok.com/oembed?url=${encodeURIComponent(url)}`;
|
||||||
|
const response = await requestPublic(endpoint, 'application/json', 256 * 1024);
|
||||||
|
if (!response.contentType.toLowerCase().includes('json')) throw new Error('FETCH_INVALID_TYPE');
|
||||||
|
const value = JSON.parse(response.data.toString('utf8')) as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
title: String(value.title ?? '').slice(0, 300),
|
||||||
|
description: '',
|
||||||
|
imageUrl: String(value.thumbnail_url ?? '').slice(0, 2_000),
|
||||||
|
siteName: String(value.provider_name ?? (provider === 'youtube' ? 'YouTube' : 'TikTok')).slice(
|
||||||
|
0,
|
||||||
|
200
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPresentationMetadata(url: string): Promise<PresentationMetadata> {
|
||||||
|
const video = detectVideoProvider(url);
|
||||||
|
if (video) {
|
||||||
|
const metadata = await providerMetadata(url, video.provider);
|
||||||
|
return { ...metadata, provider: video.provider, providerId: video.id };
|
||||||
|
}
|
||||||
|
const response = await requestPublic(url, 'text/html,application/xhtml+xml', MAX_HTML_BYTES);
|
||||||
|
const contentType = response.contentType.toLowerCase();
|
||||||
|
if (!contentType.includes('text/html') && !contentType.includes('application/xhtml+xml')) {
|
||||||
|
throw new Error('FETCH_INVALID_TYPE');
|
||||||
|
}
|
||||||
|
return extractMetadataFromHtml(response.data.toString('utf8'), response.url);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPresentationImage(url: string) {
|
||||||
|
const response = await requestPublic(
|
||||||
|
url,
|
||||||
|
'image/jpeg,image/png,image/webp,image/gif',
|
||||||
|
MAX_IMAGE_BYTES
|
||||||
|
);
|
||||||
|
const mimeType = response.contentType.split(';')[0].trim().toLowerCase();
|
||||||
|
if (!['image/jpeg', 'image/png', 'image/webp', 'image/gif'].includes(mimeType)) {
|
||||||
|
throw new Error('FETCH_INVALID_TYPE');
|
||||||
|
}
|
||||||
|
return { data: response.data, mimeType };
|
||||||
|
}
|
||||||
+50
-95
@@ -1,4 +1,5 @@
|
|||||||
import { getDatabase } from './database.js';
|
import { getDatabase } from './database.js';
|
||||||
|
import { getShow as getShowById, listShows } from './shows.js';
|
||||||
|
|
||||||
export type PreviewPiece = {
|
export type PreviewPiece = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -85,7 +86,7 @@ export function getPieces(): PreviewPiece[] {
|
|||||||
(SELECT count(*) FROM piece_sources ps WHERE ps.piece_id = p.id) AS source_count
|
(SELECT count(*) FROM piece_sources ps WHERE ps.piece_id = p.id) AS source_count
|
||||||
FROM pieces p
|
FROM pieces p
|
||||||
LEFT JOIN formats f ON f.id = p.format_id
|
LEFT JOIN formats f ON f.id = p.format_id
|
||||||
WHERE p.status != 'archived'
|
WHERE p.status IN ('preparing', 'ready')
|
||||||
ORDER BY CASE p.status WHEN 'ready' THEN 0 ELSE 1 END, p.title`
|
ORDER BY CASE p.status WHEN 'ready' THEN 0 ELSE 1 END, p.title`
|
||||||
)
|
)
|
||||||
.all() as PieceRow[];
|
.all() as PieceRow[];
|
||||||
@@ -104,109 +105,63 @@ export function getPieces(): PreviewPiece[] {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShowRow = {
|
export function getShow(showId?: string): PreviewShow {
|
||||||
id: string;
|
const latest = showId ? null : listShows().find((show) => show.startsAtUtc !== null);
|
||||||
title: string;
|
const show = getShowById(showId ?? latest?.id ?? '');
|
||||||
starts_at_utc: string;
|
|
||||||
twitch_title: string;
|
|
||||||
announcement_text: string;
|
|
||||||
status: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type SectionRow = {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
category: string | null;
|
|
||||||
category_color: string | null;
|
|
||||||
explicit_duration_seconds: number | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
type UsageRow = {
|
|
||||||
id: string;
|
|
||||||
show_section_id: string;
|
|
||||||
title_snapshot: string;
|
|
||||||
duration_seconds: number;
|
|
||||||
status: PreviewUsage['status'];
|
|
||||||
intro_snapshot: string;
|
|
||||||
moderation_snapshot: string;
|
|
||||||
transition_snapshot: string;
|
|
||||||
is_reserve: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function getShow(): PreviewShow {
|
|
||||||
const database = getDatabase();
|
|
||||||
const show = database
|
|
||||||
.prepare(
|
|
||||||
`SELECT id, title, starts_at_utc, twitch_title, announcement_text, status
|
|
||||||
FROM shows ORDER BY starts_at_utc DESC LIMIT 1`
|
|
||||||
)
|
|
||||||
.get() as ShowRow | undefined;
|
|
||||||
|
|
||||||
if (!show) throw new Error('No preview show found. Run npm run db:seed.');
|
if (!show) throw new Error('No preview show found. Run npm run db:seed.');
|
||||||
|
const sections: PreviewSection[] = show.sections.map((section) => ({
|
||||||
const sectionRows = database
|
id: section.id,
|
||||||
.prepare(
|
name: section.name,
|
||||||
`SELECT s.id, s.name, c.name AS category, c.color AS category_color,
|
category: section.category ?? 'Offen',
|
||||||
s.explicit_duration_seconds
|
categoryColor: section.categoryColor ?? '#8b8f98',
|
||||||
FROM show_sections s
|
durationSeconds: section.durationSeconds,
|
||||||
LEFT JOIN section_categories c ON c.id = s.category_id
|
usages: section.usages.map((usage) => ({
|
||||||
WHERE s.show_id = ? ORDER BY s.position`
|
id: usage.id,
|
||||||
)
|
title: usage.title,
|
||||||
.all(show.id) as SectionRow[];
|
durationSeconds: usage.durationSeconds,
|
||||||
const usageRows = database
|
status: usage.status,
|
||||||
.prepare(
|
intro: usage.intro,
|
||||||
`SELECT id, show_section_id, title_snapshot, duration_seconds, status,
|
moderation: usage.moderation,
|
||||||
intro_snapshot, moderation_snapshot, transition_snapshot, is_reserve
|
transition: usage.transition,
|
||||||
FROM piece_usages WHERE show_section_id IN (
|
isReserve: false
|
||||||
SELECT id FROM show_sections WHERE show_id = ?
|
}))
|
||||||
) ORDER BY position`
|
}));
|
||||||
)
|
const reserveHost = sections[Math.min(1, sections.length - 1)];
|
||||||
.all(show.id) as UsageRow[];
|
if (reserveHost) {
|
||||||
|
reserveHost.usages.push(
|
||||||
const sections = sectionRows.map((section) => {
|
...show.reserve.map((usage) => ({
|
||||||
const usages = usageRows
|
|
||||||
.filter((usage) => usage.show_section_id === section.id)
|
|
||||||
.map((usage) => ({
|
|
||||||
id: usage.id,
|
id: usage.id,
|
||||||
title: usage.title_snapshot,
|
title: usage.title,
|
||||||
durationSeconds: usage.duration_seconds,
|
durationSeconds: usage.durationSeconds,
|
||||||
status: usage.status,
|
status: usage.status,
|
||||||
intro: usage.intro_snapshot,
|
intro: usage.intro,
|
||||||
moderation: usage.moderation_snapshot,
|
moderation: usage.moderation,
|
||||||
transition: usage.transition_snapshot,
|
transition: usage.transition,
|
||||||
isReserve: usage.is_reserve === 1
|
isReserve: true
|
||||||
}));
|
}))
|
||||||
const plannedUsages = usages.filter((usage) => !usage.isReserve);
|
);
|
||||||
return {
|
}
|
||||||
id: section.id,
|
|
||||||
name: section.name,
|
|
||||||
category: section.category ?? 'Offen',
|
|
||||||
categoryColor: section.category_color ?? '#8b8f98',
|
|
||||||
durationSeconds:
|
|
||||||
section.explicit_duration_seconds ??
|
|
||||||
plannedUsages.reduce((total, usage) => total + usage.durationSeconds, 0),
|
|
||||||
usages
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: show.id,
|
id: show.id,
|
||||||
title: show.title,
|
title: show.title,
|
||||||
startsAtUtc: show.starts_at_utc,
|
startsAtUtc: show.startsAtUtc ?? '',
|
||||||
startsAtBerlin: new Intl.DateTimeFormat('de-DE', {
|
startsAtBerlin: show.startsAtUtc
|
||||||
timeZone: 'Europe/Berlin',
|
? new Intl.DateTimeFormat('de-DE', {
|
||||||
weekday: 'short',
|
timeZone: 'Europe/Berlin',
|
||||||
day: '2-digit',
|
weekday: 'short',
|
||||||
month: '2-digit',
|
day: '2-digit',
|
||||||
year: 'numeric',
|
month: '2-digit',
|
||||||
hour: '2-digit',
|
year: 'numeric',
|
||||||
minute: '2-digit'
|
hour: '2-digit',
|
||||||
}).format(new Date(show.starts_at_utc)),
|
minute: '2-digit'
|
||||||
twitchTitle: show.twitch_title,
|
}).format(new Date(show.startsAtUtc))
|
||||||
announcement: show.announcement_text,
|
: 'Termin offen',
|
||||||
|
twitchTitle: show.twitchTitle,
|
||||||
|
announcement: show.announcementText,
|
||||||
status: show.status,
|
status: show.status,
|
||||||
sections,
|
sections,
|
||||||
totalDurationSeconds: sections.reduce((total, section) => total + section.durationSeconds, 0)
|
totalDurationSeconds: show.totalDurationSeconds
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,521 @@
|
|||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import { getPiece } from './content.js';
|
||||||
|
import { closeDatabase, getDatabase } from './database.js';
|
||||||
|
import {
|
||||||
|
addPieceUsage,
|
||||||
|
addShowSection,
|
||||||
|
createShow,
|
||||||
|
duplicatePieceUsage,
|
||||||
|
getPieceUsageContexts,
|
||||||
|
getShow,
|
||||||
|
listShowTemplates,
|
||||||
|
movePieceUsage,
|
||||||
|
moveShowSection,
|
||||||
|
refreshPieceUsageFromOriginal,
|
||||||
|
removePieceUsage,
|
||||||
|
removeShowSection,
|
||||||
|
updatePieceUsage,
|
||||||
|
updateShowSection,
|
||||||
|
type PieceUsage
|
||||||
|
} from './shows.js';
|
||||||
|
|
||||||
|
let directory: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
directory = mkdtempSync(path.join(tmpdir(), 'sendewerk-shows-test-'));
|
||||||
|
process.env.SENDEWERK_DB_PATH = path.join(directory, 'test.sqlite');
|
||||||
|
process.env.SENDEWERK_UPLOAD_DIR = path.join(directory, 'uploads');
|
||||||
|
execFileSync(process.execPath, ['scripts/migrate.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
execFileSync(process.execPath, ['scripts/seed.mjs'], { cwd: process.cwd(), env: process.env });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
closeDatabase();
|
||||||
|
delete process.env.SENDEWERK_DB_PATH;
|
||||||
|
delete process.env.SENDEWERK_UPLOAD_DIR;
|
||||||
|
rmSync(directory, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
function editedUsage(usage: PieceUsage, overrides: Partial<PieceUsage> = {}) {
|
||||||
|
const edited = { ...usage, ...overrides };
|
||||||
|
return {
|
||||||
|
title: edited.title,
|
||||||
|
intro: edited.intro,
|
||||||
|
research: edited.research,
|
||||||
|
moderation: edited.moderation,
|
||||||
|
transition: edited.transition,
|
||||||
|
presentation: edited.presentation,
|
||||||
|
presentationMode: edited.presentationMode,
|
||||||
|
presentationSourceLabel: edited.presentationSourceLabel,
|
||||||
|
presentationSourceUrl: edited.presentationSourceUrl,
|
||||||
|
presentationSourceTimecodeSeconds: edited.presentationSourceTimecodeSeconds,
|
||||||
|
presentationTitle: edited.presentationTitle,
|
||||||
|
presentationDescription: edited.presentationDescription,
|
||||||
|
presentationImageUrl: edited.presentationImageUrl,
|
||||||
|
presentationSiteName: edited.presentationSiteName,
|
||||||
|
ownNotes: edited.ownNotes,
|
||||||
|
durationSeconds: edited.durationSeconds
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('show builder data layer', () => {
|
||||||
|
it('creates blank and templated shows with independent sections and reserve banks', () => {
|
||||||
|
const templatesBefore = listShowTemplates();
|
||||||
|
expect(
|
||||||
|
templatesBefore.find((template) => template.id === 'template-default')?.sections
|
||||||
|
).toHaveLength(5);
|
||||||
|
expect(templatesBefore.find((template) => template.id === 'template-games')?.name).toBe(
|
||||||
|
'Spieleabend'
|
||||||
|
);
|
||||||
|
|
||||||
|
const blank = createShow({ title: null, startsAtUtc: null, templateId: null });
|
||||||
|
expect(getShow(blank.id)).toMatchObject({
|
||||||
|
title: 'Neue Sendung',
|
||||||
|
startsAtUtc: null,
|
||||||
|
sections: [],
|
||||||
|
reserve: []
|
||||||
|
});
|
||||||
|
const reserveCount = getDatabase()
|
||||||
|
.prepare(
|
||||||
|
'SELECT count(*) AS count FROM show_sections WHERE show_id = ? AND is_reserve_bank = 1'
|
||||||
|
)
|
||||||
|
.get(blank.id) as { count: number };
|
||||||
|
expect(reserveCount.count).toBe(1);
|
||||||
|
|
||||||
|
const templated = createShow({
|
||||||
|
title: 'Vorlagenkopie',
|
||||||
|
startsAtUtc: '2027-01-08T19:00:00Z',
|
||||||
|
templateId: 'template-default'
|
||||||
|
});
|
||||||
|
const copy = getShow(templated.id)!;
|
||||||
|
expect(copy.sections.map((section) => section.name)).toEqual([
|
||||||
|
'Start',
|
||||||
|
'JC / Reaction',
|
||||||
|
'Spiel 1',
|
||||||
|
'JC',
|
||||||
|
'Spiel 2'
|
||||||
|
]);
|
||||||
|
updateShowSection(templated.id, copy.sections[0].id, copy.revision, {
|
||||||
|
name: 'Eigener Start',
|
||||||
|
categoryId: 'cat-jc',
|
||||||
|
explicitDurationSeconds: 420
|
||||||
|
});
|
||||||
|
expect(listShowTemplates()).toEqual(templatesBefore);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('snapshots a ready piece repeatedly and keeps usage edits independent from its original', () => {
|
||||||
|
const created = createShow({
|
||||||
|
title: 'Doppelte Verwendung',
|
||||||
|
startsAtUtc: null,
|
||||||
|
templateId: null
|
||||||
|
});
|
||||||
|
const section = addShowSection(created.id, created.revision, {
|
||||||
|
name: 'Fundstücke',
|
||||||
|
categoryId: 'cat-reaction',
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const first = addPieceUsage(created.id, section.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: section.id
|
||||||
|
});
|
||||||
|
const second = addPieceUsage(created.id, first.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: section.id
|
||||||
|
});
|
||||||
|
const usages = getShow(created.id)!.sections[0].usages;
|
||||||
|
const firstSaved = updatePieceUsage(
|
||||||
|
created.id,
|
||||||
|
first.id,
|
||||||
|
second.revision,
|
||||||
|
editedUsage(usages[0], {
|
||||||
|
title: 'Konsole als Auftakt',
|
||||||
|
durationSeconds: 300,
|
||||||
|
ownNotes: 'Kurbel zuerst zeigen',
|
||||||
|
research: 'Eigene Recherchekopie'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
updatePieceUsage(
|
||||||
|
created.id,
|
||||||
|
second.id,
|
||||||
|
firstSaved.revision,
|
||||||
|
editedUsage(usages[1], { title: 'Konsole als Rückblick', durationSeconds: 900 })
|
||||||
|
);
|
||||||
|
|
||||||
|
const show = getShow(created.id)!;
|
||||||
|
expect(show.sections[0].usages).toMatchObject([
|
||||||
|
{
|
||||||
|
title: 'Konsole als Auftakt',
|
||||||
|
durationSeconds: 300,
|
||||||
|
ownNotes: 'Kurbel zuerst zeigen',
|
||||||
|
research: 'Eigene Recherchekopie'
|
||||||
|
},
|
||||||
|
{ title: 'Konsole als Rückblick', durationSeconds: 900 }
|
||||||
|
]);
|
||||||
|
expect(getPiece('piece-console')).toMatchObject({
|
||||||
|
title: 'Die kleine Konsole mit dem großen Dreh',
|
||||||
|
durationSeconds: 480,
|
||||||
|
researchText:
|
||||||
|
'## Recherche\n\n- Herstellerangaben gegen unabhängige Tests prüfen\n- Fokus auf Bedienidee statt Leistungsdaten'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('derives sent history and current planning only from qualifying usages by original id', () => {
|
||||||
|
const completed = createShow({
|
||||||
|
title: 'Abgeschlossene Sendung',
|
||||||
|
startsAtUtc: '2027-01-10T19:00:00Z',
|
||||||
|
templateId: null
|
||||||
|
});
|
||||||
|
const completedSection = addShowSection(completed.id, completed.revision, {
|
||||||
|
name: 'Ablauf',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const done = addPieceUsage(completed.id, completedSection.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: completedSection.id
|
||||||
|
});
|
||||||
|
const skipped = addPieceUsage(completed.id, done.revision, {
|
||||||
|
pieceId: 'piece-effects',
|
||||||
|
sectionId: completedSection.id
|
||||||
|
});
|
||||||
|
const reserve = addPieceUsage(completed.id, skipped.revision, {
|
||||||
|
pieceId: 'piece-pixels',
|
||||||
|
sectionId: null
|
||||||
|
});
|
||||||
|
getDatabase()
|
||||||
|
.prepare("UPDATE piece_usages SET status = 'done' WHERE id IN (?, ?)")
|
||||||
|
.run(done.id, reserve.id);
|
||||||
|
getDatabase()
|
||||||
|
.prepare("UPDATE piece_usages SET status = 'skipped' WHERE id = ?")
|
||||||
|
.run(skipped.id);
|
||||||
|
getDatabase().prepare("UPDATE shows SET status = 'completed' WHERE id = ?").run(completed.id);
|
||||||
|
|
||||||
|
const active = createShow({ title: 'Aktuelle Planung', startsAtUtc: null, templateId: null });
|
||||||
|
const activeSection = addShowSection(active.id, active.revision, {
|
||||||
|
name: 'Plan',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const planned = addPieceUsage(active.id, activeSection.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: activeSection.id
|
||||||
|
});
|
||||||
|
const plannedReserve = addPieceUsage(active.id, planned.revision, {
|
||||||
|
pieceId: 'piece-effects',
|
||||||
|
sectionId: null
|
||||||
|
});
|
||||||
|
getDatabase().prepare("UPDATE piece_usages SET status = 'done' WHERE id = ?").run(planned.id);
|
||||||
|
|
||||||
|
let contexts = getPieceUsageContexts(
|
||||||
|
['piece-console', 'piece-effects', 'piece-pixels'],
|
||||||
|
active.id
|
||||||
|
);
|
||||||
|
expect(contexts['piece-console']).toMatchObject({
|
||||||
|
isPlannedInCurrentShow: true,
|
||||||
|
sentHistory: [
|
||||||
|
{
|
||||||
|
usageId: done.id,
|
||||||
|
showId: completed.id,
|
||||||
|
showTitle: 'Abgeschlossene Sendung',
|
||||||
|
usedAtUtc: '2027-01-10T19:00:00.000Z'
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
expect(contexts['piece-effects']).toEqual({
|
||||||
|
isPlannedInActiveShow: true,
|
||||||
|
isPlannedInCurrentShow: true,
|
||||||
|
sentHistory: []
|
||||||
|
});
|
||||||
|
expect(contexts['piece-pixels']).toEqual({
|
||||||
|
isPlannedInActiveShow: true,
|
||||||
|
isPlannedInCurrentShow: false,
|
||||||
|
sentHistory: []
|
||||||
|
});
|
||||||
|
|
||||||
|
removePieceUsage(active.id, plannedReserve.id, plannedReserve.revision);
|
||||||
|
contexts = getPieceUsageContexts(['piece-effects'], active.id);
|
||||||
|
expect(contexts['piece-effects'].isPlannedInCurrentShow).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('duplicates an adjusted usage directly after its source without live measurements', () => {
|
||||||
|
const created = createShow({
|
||||||
|
title: 'Einplanungsduplikat',
|
||||||
|
startsAtUtc: null,
|
||||||
|
templateId: null
|
||||||
|
});
|
||||||
|
const section = addShowSection(created.id, created.revision, {
|
||||||
|
name: 'Ablauf',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const usage = addPieceUsage(created.id, section.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: section.id
|
||||||
|
});
|
||||||
|
const source = getShow(created.id)!.sections[0].usages[0];
|
||||||
|
const adjusted = updatePieceUsage(
|
||||||
|
created.id,
|
||||||
|
usage.id,
|
||||||
|
usage.revision,
|
||||||
|
editedUsage(source, {
|
||||||
|
title: 'Angepasste Einplanung',
|
||||||
|
durationSeconds: 777,
|
||||||
|
intro: 'Eigene Einleitung',
|
||||||
|
research: 'Eigene Recherche',
|
||||||
|
moderation: 'Eigene Moderation',
|
||||||
|
transition: 'Eigene Überleitung',
|
||||||
|
presentation: 'Eigene Präsentation',
|
||||||
|
ownNotes: 'Eigene Notizen'
|
||||||
|
})
|
||||||
|
);
|
||||||
|
getDatabase().prepare("UPDATE piece_usages SET status = 'done' WHERE id = ?").run(usage.id);
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO live_usage_runs (id, show_id, usage_id, started_at_utc, ended_at_utc)
|
||||||
|
VALUES ('source-run', ?, ?, '2027-01-01T10:00:00.000Z', '2027-01-01T10:10:00.000Z')`
|
||||||
|
)
|
||||||
|
.run(created.id, usage.id);
|
||||||
|
const pieceCountBefore = (
|
||||||
|
getDatabase().prepare('SELECT count(*) AS count FROM pieces').get() as { count: number }
|
||||||
|
).count;
|
||||||
|
|
||||||
|
const duplicate = duplicatePieceUsage(created.id, usage.id, adjusted.revision);
|
||||||
|
const usages = getShow(created.id)!.sections[0].usages;
|
||||||
|
expect(usages.map((item) => item.id)).toEqual([usage.id, duplicate.id]);
|
||||||
|
expect(usages[1]).toMatchObject({
|
||||||
|
originalPieceId: 'piece-console',
|
||||||
|
status: 'open',
|
||||||
|
durationSeconds: 777,
|
||||||
|
title: 'Angepasste Einplanung',
|
||||||
|
intro: 'Eigene Einleitung',
|
||||||
|
research: 'Eigene Recherche',
|
||||||
|
moderation: 'Eigene Moderation',
|
||||||
|
transition: 'Eigene Überleitung',
|
||||||
|
presentation: 'Eigene Präsentation',
|
||||||
|
ownNotes: 'Eigene Notizen'
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
getDatabase()
|
||||||
|
.prepare('SELECT count(*) AS count FROM live_usage_runs WHERE usage_id = ?')
|
||||||
|
.get(duplicate.id)
|
||||||
|
).toEqual({ count: 0 });
|
||||||
|
expect(
|
||||||
|
(getDatabase().prepare('SELECT count(*) AS count FROM pieces').get() as { count: number })
|
||||||
|
.count
|
||||||
|
).toBe(pieceCountBefore);
|
||||||
|
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET title = 'Aktuelles Original', duration_seconds = 420,
|
||||||
|
intro = 'Neue Einleitung', research_text = 'Neue Recherche',
|
||||||
|
moderation_notes = 'Neue Moderation', transition_text = 'Neue Überleitung',
|
||||||
|
presentation_text = 'Neue Präsentation' WHERE id = 'piece-console'`
|
||||||
|
)
|
||||||
|
.run();
|
||||||
|
const refreshed = refreshPieceUsageFromOriginal(created.id, usage.id, duplicate.revision);
|
||||||
|
const refreshedUsages = getShow(created.id)!.sections[0].usages;
|
||||||
|
expect(refreshedUsages[0]).toMatchObject({
|
||||||
|
title: 'Aktuelles Original',
|
||||||
|
durationSeconds: 420,
|
||||||
|
intro: 'Neue Einleitung',
|
||||||
|
research: 'Neue Recherche',
|
||||||
|
moderation: 'Neue Moderation',
|
||||||
|
transition: 'Neue Überleitung',
|
||||||
|
presentation: 'Neue Präsentation',
|
||||||
|
ownNotes: 'Eigene Notizen',
|
||||||
|
status: 'done'
|
||||||
|
});
|
||||||
|
expect(refreshedUsages[1]).toMatchObject({
|
||||||
|
title: 'Angepasste Einplanung',
|
||||||
|
durationSeconds: 777,
|
||||||
|
status: 'open'
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
getDatabase()
|
||||||
|
.prepare('SELECT count(*) AS count FROM live_usage_runs WHERE usage_id = ?')
|
||||||
|
.get(usage.id)
|
||||||
|
).toEqual({ count: 1 });
|
||||||
|
expect(() => duplicatePieceUsage(created.id, usage.id, adjusted.revision)).toThrow('CONFLICT');
|
||||||
|
expect(getShow(created.id)?.revision).toBe(refreshed.revision);
|
||||||
|
getDatabase()
|
||||||
|
.prepare('UPDATE piece_usages SET original_piece_id = NULL WHERE id = ?')
|
||||||
|
.run(duplicate.id);
|
||||||
|
expect(() =>
|
||||||
|
refreshPieceUsageFromOriginal(created.id, duplicate.id, refreshed.revision)
|
||||||
|
).toThrow('ORIGINAL_NOT_FOUND');
|
||||||
|
expect(getShow(created.id)?.revision).toBe(refreshed.revision);
|
||||||
|
expect(getShow(created.id)!.sections[0].usages).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('snapshots presentation settings until an explicit refresh and copies them on duplication', () => {
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE piece_sources SET label = 'YouTube', url = ?, timecode_seconds = 75
|
||||||
|
WHERE piece_id = 'piece-console' AND position = 0`
|
||||||
|
)
|
||||||
|
.run('https://youtu.be/dQw4w9WgXcQ');
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET presentation_mode = 'video', presentation_source_position = 0,
|
||||||
|
presentation_title = 'Gespeicherte Vorschau', presentation_description = 'Erster Stand',
|
||||||
|
presentation_site_name = 'YouTube', presentation_provider = 'youtube',
|
||||||
|
presentation_provider_id = 'dQw4w9WgXcQ' WHERE id = 'piece-console'`
|
||||||
|
)
|
||||||
|
.run();
|
||||||
|
const show = createShow({ title: 'Snapshot-Test', startsAtUtc: null, templateId: null });
|
||||||
|
const section = addShowSection(show.id, show.revision, {
|
||||||
|
name: 'Videos',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const added = addPieceUsage(show.id, section.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: section.id
|
||||||
|
});
|
||||||
|
let usage = getShow(show.id)!.sections[0].usages[0];
|
||||||
|
expect(usage).toMatchObject({
|
||||||
|
presentationMode: 'video',
|
||||||
|
presentationSourceUrl: 'https://youtu.be/dQw4w9WgXcQ',
|
||||||
|
presentationSourceTimecodeSeconds: 75,
|
||||||
|
presentationTitle: 'Gespeicherte Vorschau'
|
||||||
|
});
|
||||||
|
|
||||||
|
getDatabase()
|
||||||
|
.prepare(
|
||||||
|
`UPDATE pieces SET presentation_title = 'Neuer Originaltitel' WHERE id = 'piece-console'`
|
||||||
|
)
|
||||||
|
.run();
|
||||||
|
expect(getShow(show.id)!.sections[0].usages[0].presentationTitle).toBe('Gespeicherte Vorschau');
|
||||||
|
const refreshed = refreshPieceUsageFromOriginal(show.id, usage.id, added.revision);
|
||||||
|
usage = getShow(show.id)!.sections[0].usages[0];
|
||||||
|
expect(usage.presentationTitle).toBe('Neuer Originaltitel');
|
||||||
|
duplicatePieceUsage(show.id, usage.id, refreshed.revision);
|
||||||
|
expect(getShow(show.id)!.sections[0].usages[1]).toMatchObject({
|
||||||
|
presentationMode: 'video',
|
||||||
|
presentationSourceUrl: 'https://youtu.be/dQw4w9WgXcQ',
|
||||||
|
presentationTitle: 'Neuer Originaltitel',
|
||||||
|
status: 'open'
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('persists normalized section and usage reordering, moving and removal', () => {
|
||||||
|
const created = createShow({ title: 'Sortierung', startsAtUtc: null, templateId: null });
|
||||||
|
const firstSection = addShowSection(created.id, created.revision, {
|
||||||
|
name: 'Erster Block',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const secondSection = addShowSection(created.id, firstSection.revision, {
|
||||||
|
name: 'Zweiter Block',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
const firstUsage = addPieceUsage(created.id, secondSection.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: firstSection.id
|
||||||
|
});
|
||||||
|
const secondUsage = addPieceUsage(created.id, firstUsage.revision, {
|
||||||
|
pieceId: 'piece-effects',
|
||||||
|
sectionId: firstSection.id
|
||||||
|
});
|
||||||
|
const thirdUsage = addPieceUsage(created.id, secondUsage.revision, {
|
||||||
|
pieceId: 'piece-pixels',
|
||||||
|
sectionId: firstSection.id
|
||||||
|
});
|
||||||
|
const reordered = movePieceUsage(created.id, thirdUsage.id, thirdUsage.revision, {
|
||||||
|
sectionId: firstSection.id,
|
||||||
|
position: 0
|
||||||
|
});
|
||||||
|
const reserved = movePieceUsage(created.id, firstUsage.id, reordered.revision, {
|
||||||
|
sectionId: null,
|
||||||
|
position: 0
|
||||||
|
});
|
||||||
|
const plannedAgain = movePieceUsage(created.id, firstUsage.id, reserved.revision, {
|
||||||
|
sectionId: secondSection.id,
|
||||||
|
position: 0
|
||||||
|
});
|
||||||
|
const removedUsage = removePieceUsage(created.id, secondUsage.id, plannedAgain.revision);
|
||||||
|
const movedSection = moveShowSection(created.id, secondSection.id, 0, removedUsage.revision);
|
||||||
|
removeShowSection(created.id, firstSection.id, movedSection.revision);
|
||||||
|
|
||||||
|
const show = getShow(created.id)!;
|
||||||
|
expect(show.sections.map((section) => [section.name, section.position])).toEqual([
|
||||||
|
['Zweiter Block', 0]
|
||||||
|
]);
|
||||||
|
expect(show.sections[0].usages.map((usage) => [usage.id, usage.position])).toEqual([
|
||||||
|
[firstUsage.id, 0]
|
||||||
|
]);
|
||||||
|
expect(show.reserve).toEqual([]);
|
||||||
|
expect(getDatabase().pragma('foreign_key_check')).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses explicit section durations once and excludes the show-wide reserve', () => {
|
||||||
|
const created = createShow({ title: 'Dauer', startsAtUtc: null, templateId: null });
|
||||||
|
const section = addShowSection(created.id, created.revision, {
|
||||||
|
name: 'Fester Block',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: 600
|
||||||
|
});
|
||||||
|
const planned = addPieceUsage(created.id, section.revision, {
|
||||||
|
pieceId: 'piece-effects',
|
||||||
|
sectionId: section.id
|
||||||
|
});
|
||||||
|
addPieceUsage(created.id, planned.revision, {
|
||||||
|
pieceId: 'piece-pixels',
|
||||||
|
sectionId: null
|
||||||
|
});
|
||||||
|
|
||||||
|
const explicit = getShow(created.id)!;
|
||||||
|
expect(explicit.sections[0].durationSeconds).toBe(600);
|
||||||
|
expect(explicit.totalDurationSeconds).toBe(600);
|
||||||
|
expect(explicit.reserve[0].durationSeconds).toBe(540);
|
||||||
|
|
||||||
|
updateShowSection(created.id, section.id, explicit.revision, {
|
||||||
|
name: 'Summierter Block',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
expect(getShow(created.id)).toMatchObject({
|
||||||
|
totalDurationSeconds: 720,
|
||||||
|
sections: [{ durationSeconds: 720 }]
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rolls stale and invalid aggregate mutations back and rejects completed shows', () => {
|
||||||
|
const created = createShow({ title: 'Konflikt', startsAtUtc: null, templateId: null });
|
||||||
|
const saved = addShowSection(created.id, created.revision, {
|
||||||
|
name: 'Gültig',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
});
|
||||||
|
expect(() =>
|
||||||
|
addShowSection(created.id, created.revision, {
|
||||||
|
name: 'Veraltet',
|
||||||
|
categoryId: null,
|
||||||
|
explicitDurationSeconds: null
|
||||||
|
})
|
||||||
|
).toThrow('CONFLICT');
|
||||||
|
expect(getShow(created.id)).toMatchObject({
|
||||||
|
revision: saved.revision,
|
||||||
|
sections: [{ name: 'Gültig' }]
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(() => removeShowSection(created.id, 'missing', saved.revision)).toThrow('NOT_FOUND');
|
||||||
|
expect(getShow(created.id)?.revision).toBe(saved.revision);
|
||||||
|
getDatabase().prepare("UPDATE shows SET status = 'completed' WHERE id = ?").run(created.id);
|
||||||
|
expect(() =>
|
||||||
|
addPieceUsage(created.id, saved.revision, {
|
||||||
|
pieceId: 'piece-console',
|
||||||
|
sectionId: saved.id
|
||||||
|
})
|
||||||
|
).toThrow('SHOW_COMPLETED');
|
||||||
|
expect(getShow(created.id)).toMatchObject({
|
||||||
|
revision: saved.revision,
|
||||||
|
sections: [{ usages: [] }]
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
|||||||
|
import type { LayoutServerLoad } from './$types';
|
||||||
|
|
||||||
|
export const load: LayoutServerLoad = ({ locals, url }) => ({
|
||||||
|
user: url.pathname.startsWith('/heinzlive/') ? null : locals.user,
|
||||||
|
presentationMode: url.pathname.startsWith('/heinzlive/')
|
||||||
|
});
|
||||||
+80
-44
@@ -5,14 +5,17 @@
|
|||||||
import NavIcon from '#lib/components/NavIcon.svelte';
|
import NavIcon from '#lib/components/NavIcon.svelte';
|
||||||
import ThemeToggle from '#lib/components/ThemeToggle.svelte';
|
import ThemeToggle from '#lib/components/ThemeToggle.svelte';
|
||||||
|
|
||||||
let { children } = $props();
|
let { children, data } = $props();
|
||||||
const navigation = [
|
const primaryNavigation = [
|
||||||
{ href: '/eingang', label: 'Eingang', icon: 'inbox' },
|
{ href: '/eingang', label: 'Eingang', icon: 'inbox' },
|
||||||
{ href: '/fundus', label: 'Fundus', icon: 'library' },
|
{ href: '/fundus', label: 'Fundus', icon: 'library' },
|
||||||
{ href: '/sendungen', label: 'Sendungen', icon: 'shows' },
|
{ href: '/sendungen', label: 'Sendungen', icon: 'shows' },
|
||||||
{ href: '/archiv', label: 'Archiv', icon: 'archive' },
|
{ href: '/archiv', label: 'Archiv', icon: 'archive' }
|
||||||
{ href: '/verwaltung', label: 'Verwaltung', icon: 'settings' }
|
|
||||||
] as const;
|
] as const;
|
||||||
|
const administration = { href: '/verwaltung', label: 'Verwaltung', icon: 'settings' } as const;
|
||||||
|
const mobileNavigation = $derived(
|
||||||
|
data.user?.role === 'barkeeper' ? [...primaryNavigation, administration] : primaryNavigation
|
||||||
|
);
|
||||||
|
|
||||||
function isActive(href: string) {
|
function isActive(href: string) {
|
||||||
return (
|
return (
|
||||||
@@ -28,15 +31,68 @@
|
|||||||
/>
|
/>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<div class="app-shell">
|
{#if data.presentationMode}
|
||||||
<aside class="sidebar">
|
{@render children()}
|
||||||
<a class="brand" href={resolve('/fundus')} aria-label="Sendewerk Startseite">
|
{:else if data.user}
|
||||||
<span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
<div class="app-shell">
|
||||||
<span>Sendewerk</span>
|
<aside class="sidebar">
|
||||||
</a>
|
<a class="brand" href={resolve('/fundus')} aria-label="Sendewerk Startseite">
|
||||||
|
<span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
||||||
|
<span>Sendewerk</span>
|
||||||
|
</a>
|
||||||
|
|
||||||
<nav class="main-navigation" aria-label="Hauptnavigation">
|
<nav class="main-navigation" aria-label="Hauptnavigation">
|
||||||
{#each navigation as item (item.href)}
|
{#each primaryNavigation as item (item.href)}
|
||||||
|
<a
|
||||||
|
href={resolve(item.href)}
|
||||||
|
class:active={isActive(item.href)}
|
||||||
|
aria-current={isActive(item.href) ? 'page' : undefined}
|
||||||
|
>
|
||||||
|
<NavIcon name={item.icon} />
|
||||||
|
<span>{item.label}</span>
|
||||||
|
</a>
|
||||||
|
{/each}
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="sidebar-footer">
|
||||||
|
{#if data.user.role === 'barkeeper'}
|
||||||
|
<nav class="utility-navigation" aria-label="Verwaltung">
|
||||||
|
<a
|
||||||
|
href={resolve(administration.href)}
|
||||||
|
class:active={isActive(administration.href)}
|
||||||
|
aria-current={isActive(administration.href) ? 'page' : undefined}
|
||||||
|
>
|
||||||
|
<NavIcon name={administration.icon} />
|
||||||
|
<span>{administration.label}</span>
|
||||||
|
</a>
|
||||||
|
</nav>
|
||||||
|
{/if}
|
||||||
|
<div class="account-summary">
|
||||||
|
<span>{data.user.displayName}</span>
|
||||||
|
<small>{data.user.role === 'barkeeper' ? 'Barkeeper' : 'Thekencrew'}</small>
|
||||||
|
</div>
|
||||||
|
<form method="POST" action="/logout">
|
||||||
|
<button class="logout-button" type="submit">Abmelden</button>
|
||||||
|
</form>
|
||||||
|
<ThemeToggle />
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<header class="mobile-header">
|
||||||
|
<a class="brand" href={resolve('/fundus')} aria-label="Sendewerk Startseite">
|
||||||
|
<span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
||||||
|
<span>Sendewerk</span>
|
||||||
|
</a>
|
||||||
|
<form method="POST" action="/logout">
|
||||||
|
<button class="mobile-logout" type="submit" aria-label="Abmelden">↗</button>
|
||||||
|
</form>
|
||||||
|
<ThemeToggle />
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main id="main-content">{@render children()}</main>
|
||||||
|
|
||||||
|
<nav class="mobile-navigation" aria-label="Hauptnavigation">
|
||||||
|
{#each mobileNavigation as item (item.href)}
|
||||||
<a
|
<a
|
||||||
href={resolve(item.href)}
|
href={resolve(item.href)}
|
||||||
class:active={isActive(item.href)}
|
class:active={isActive(item.href)}
|
||||||
@@ -47,36 +103,16 @@
|
|||||||
</a>
|
</a>
|
||||||
{/each}
|
{/each}
|
||||||
</nav>
|
</nav>
|
||||||
|
</div>
|
||||||
<div class="sidebar-footer">
|
{:else}
|
||||||
<ThemeToggle />
|
<div class="auth-shell">
|
||||||
<div class="stage-indicator">
|
<header class="auth-header">
|
||||||
<span></span>
|
<a class="brand" href={resolve('/login')} aria-label="Sendewerk Anmeldung">
|
||||||
<div><strong>Etappe 1</strong><small>Lokaler Entwurf</small></div>
|
<span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
||||||
</div>
|
<span>Sendewerk</span>
|
||||||
</div>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<header class="mobile-header">
|
|
||||||
<a class="brand" href={resolve('/fundus')} aria-label="Sendewerk Startseite">
|
|
||||||
<span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></span>
|
|
||||||
<span>Sendewerk</span>
|
|
||||||
</a>
|
|
||||||
<ThemeToggle />
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<main id="main-content">{@render children()}</main>
|
|
||||||
|
|
||||||
<nav class="mobile-navigation" aria-label="Hauptnavigation">
|
|
||||||
{#each navigation as item (item.href)}
|
|
||||||
<a
|
|
||||||
href={resolve(item.href)}
|
|
||||||
class:active={isActive(item.href)}
|
|
||||||
aria-current={isActive(item.href) ? 'page' : undefined}
|
|
||||||
>
|
|
||||||
<NavIcon name={item.icon} />
|
|
||||||
<span>{item.label}</span>
|
|
||||||
</a>
|
</a>
|
||||||
{/each}
|
<ThemeToggle />
|
||||||
</nav>
|
</header>
|
||||||
</div>
|
<main class="auth-main">{@render children()}</main>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { redirect } from '@sveltejs/kit';
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import { hasUsers } from '#lib/server/auth.js';
|
||||||
|
|
||||||
export function load() {
|
export function load({ locals }) {
|
||||||
redirect(307, '/fundus');
|
if (!hasUsers()) redirect(307, '/setup');
|
||||||
|
redirect(307, locals.user ? '/fundus' : '/login');
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { fail } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { listPieces, setPieceArchived } from '#lib/server/content.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
return { pieces: listPieces({ statuses: ['archived'] }) };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
restore: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
setPieceArchived(String(data.get('pieceId') || ''), Number(data.get('revision')), false);
|
||||||
|
return { success: 'Piece wurde in seinen vorherigen Bereich zurückgelegt.' };
|
||||||
|
} catch {
|
||||||
|
return fail(409, { error: 'Das Piece wurde inzwischen geändert. Bitte Seite neu laden.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -1,20 +1,35 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
<svelte:head><title>Archiv | Sendewerk</title></svelte:head>
|
<svelte:head><title>Archiv | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
<div class="page-wrap narrow-page">
|
<div class="page-wrap narrow-page">
|
||||||
<header class="page-heading">
|
<header class="page-heading">
|
||||||
<p class="eyebrow">Bewahrte Sendungen</p>
|
|
||||||
<h1>Archiv</h1>
|
<h1>Archiv</h1>
|
||||||
<p class="page-intro">
|
<p class="page-intro">Abgelegte Pieces; abgeschlossene Sendungen folgen in Etappe 6.</p>
|
||||||
Abgeschlossene Abläufe bleiben hier in ihrem damaligen Stand nachvollziehbar.
|
|
||||||
</p>
|
|
||||||
</header>
|
</header>
|
||||||
<section class="quiet-panel planned-panel">
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
<div class="planned-icon" aria-hidden="true">□</div>
|
{#if form?.success}<div class="form-message success" role="status">{form.success}</div>{/if}
|
||||||
<p class="eyebrow">Geplant für Etappe 6</p>
|
{#if data.pieces.length}<div class="archive-list">
|
||||||
<h2>Historie braucht klare Regeln.</h2>
|
{#each data.pieces as piece (piece.id)}<article>
|
||||||
<p>
|
<div>
|
||||||
Stabile Snapshots, Verwendungshistorie und bewusste Archivierung werden gemeinsam
|
<h2>{piece.title}</h2>
|
||||||
implementiert, statt jetzt nur eine leere Liste vorzutäuschen.
|
<p>{piece.summary || 'Keine Kurzbeschreibung.'}</p>
|
||||||
</p>
|
</div>
|
||||||
</section>
|
<form method="POST" action="?/restore">
|
||||||
|
<input type="hidden" name="pieceId" value={piece.id} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="revision"
|
||||||
|
value={piece.revision}
|
||||||
|
/><button class="secondary-button" type="submit">Wiederherstellen</button>
|
||||||
|
</form>
|
||||||
|
</article>{/each}
|
||||||
|
</div>
|
||||||
|
{:else}<section class="quiet-panel planned-panel">
|
||||||
|
<div class="planned-icon" aria-hidden="true">□</div>
|
||||||
|
<h2>Keine Pieces archiviert</h2>
|
||||||
|
<p>Archivierte Inhalte lassen sich hier später wiederherstellen.</p>
|
||||||
|
</section>{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { fail } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { captureInbox, listPieces } from '#lib/server/content.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
return { pieces: listPieces({ statuses: ['inbox'] }) };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
capture: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
const id = captureInbox(String(data.get('title') || ''), String(data.get('url') || ''));
|
||||||
|
return { captured: true, capturedId: id };
|
||||||
|
} catch (cause) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
return fail(400, {
|
||||||
|
title: String(data.get('title') || ''),
|
||||||
|
url: String(data.get('url') || ''),
|
||||||
|
error:
|
||||||
|
code === 'INVALID_SOURCES'
|
||||||
|
? 'Bitte eine vollständige HTTP- oder HTTPS-Adresse eingeben.'
|
||||||
|
: 'Ein Titel ist erforderlich.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -1,21 +1,63 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
<svelte:head><title>Eingang | Sendewerk</title></svelte:head>
|
<svelte:head><title>Eingang | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
<div class="page-wrap narrow-page">
|
<div class="page-wrap narrow-page">
|
||||||
<header class="page-heading">
|
<header class="page-heading">
|
||||||
<p class="eyebrow">Sammelstelle</p>
|
|
||||||
<h1>Eingang</h1>
|
<h1>Eingang</h1>
|
||||||
<p class="page-intro">
|
<p class="page-intro">Gedanken und Fundstücke schnell festhalten und später ausarbeiten.</p>
|
||||||
Neue Gedanken und spätere RSS-Fundstücke landen hier, bevor sie in den Fundus übernommen
|
|
||||||
werden.
|
|
||||||
</p>
|
|
||||||
</header>
|
</header>
|
||||||
<section class="quiet-panel planned-panel">
|
<section class="quiet-panel capture-panel">
|
||||||
<div class="planned-icon" aria-hidden="true">+</div>
|
<div>
|
||||||
<p class="eyebrow">Geplant für Etappe 3 und 7</p>
|
<p class="eyebrow">Schnellaufnahme</p>
|
||||||
<h2>Noch ist der Tresen leer.</h2>
|
<h2>Was soll nicht verloren gehen?</h2>
|
||||||
<p>
|
</div>
|
||||||
Schnellaufnahme, Feed-Vorschau und bewusste Übernahme werden erst mit den dazugehörigen
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
Speicher- und Sicherheitsregeln umgesetzt.
|
{#if form?.captured}<div class="form-message success" role="status">
|
||||||
</p>
|
Im Eingang gespeichert.
|
||||||
|
<a href={resolve('/fundus/[id]', { id: form.capturedId })}>Jetzt ausarbeiten</a>
|
||||||
|
</div>{/if}
|
||||||
|
<form method="POST" action="?/capture" class="capture-form">
|
||||||
|
<label
|
||||||
|
>Gedanke <span>optional bei URL</span><input
|
||||||
|
name="title"
|
||||||
|
maxlength="200"
|
||||||
|
value={form?.title ?? ''}
|
||||||
|
placeholder="Kurze Idee festhalten"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Link <span>optional</span><input
|
||||||
|
name="url"
|
||||||
|
type="url"
|
||||||
|
maxlength="2000"
|
||||||
|
value={form?.url ?? ''}
|
||||||
|
placeholder="https://…"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Im Eingang ablegen</button>
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
|
{#if data.pieces.length}
|
||||||
|
<section class="inbox-list">
|
||||||
|
<h2>{data.pieces.length} {data.pieces.length === 1 ? 'offener Inhalt' : 'offene Inhalte'}</h2>
|
||||||
|
{#each data.pieces as piece (piece.id)}<a
|
||||||
|
class="inbox-item"
|
||||||
|
href={resolve('/fundus/[id]', { id: piece.id })}
|
||||||
|
><span
|
||||||
|
><strong>{piece.title}</strong><small
|
||||||
|
>{piece.sourceCount ? `${piece.sourceCount} Quelle` : 'Gedanke ohne Link'}</small
|
||||||
|
></span
|
||||||
|
><span>Ausarbeiten →</span></a
|
||||||
|
>{/each}
|
||||||
|
</section>
|
||||||
|
{:else}<section class="quiet-panel planned-panel">
|
||||||
|
<div class="planned-icon" aria-hidden="true">+</div>
|
||||||
|
<h2>Eingang ist leer</h2>
|
||||||
|
<p>Neue Gedanken und Links können oben direkt aufgenommen werden.</p>
|
||||||
|
</section>{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import {
|
||||||
|
acceptInvitation,
|
||||||
|
createSession,
|
||||||
|
deleteLinkToken,
|
||||||
|
getInvitation,
|
||||||
|
INVITATION_COOKIE,
|
||||||
|
readLinkToken,
|
||||||
|
storeLinkToken,
|
||||||
|
validDisplayName,
|
||||||
|
validPassword
|
||||||
|
} from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ url, cookies }) => {
|
||||||
|
const queryToken = url.searchParams.get('token');
|
||||||
|
if (queryToken) {
|
||||||
|
if (queryToken.length <= 100) storeLinkToken(cookies, INVITATION_COOKIE, queryToken);
|
||||||
|
else deleteLinkToken(cookies, INVITATION_COOKIE);
|
||||||
|
redirect(303, '/einladung');
|
||||||
|
}
|
||||||
|
const token = readLinkToken(cookies, INVITATION_COOKIE);
|
||||||
|
const invitation = getInvitation(token);
|
||||||
|
const valid = Boolean(
|
||||||
|
invitation &&
|
||||||
|
!invitation.accepted_at_utc &&
|
||||||
|
!invitation.revoked_at_utc &&
|
||||||
|
invitation.expires_at_utc > new Date().toISOString()
|
||||||
|
);
|
||||||
|
return { valid, email: valid ? invitation?.email : null };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
default: async ({ request, cookies }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
const token = readLinkToken(cookies, INVITATION_COOKIE);
|
||||||
|
const displayName = String(data.get('displayName') || '').trim();
|
||||||
|
const password = String(data.get('password') || '');
|
||||||
|
if (!validDisplayName(displayName) || !validPassword(password)) {
|
||||||
|
return fail(400, {
|
||||||
|
displayName,
|
||||||
|
error: 'Bitte Namen und ein Passwort mit mindestens 12 Zeichen prüfen.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const user = await acceptInvitation({ token, displayName, password });
|
||||||
|
deleteLinkToken(cookies, INVITATION_COOKIE);
|
||||||
|
createSession(user.id, cookies);
|
||||||
|
} catch {
|
||||||
|
return fail(400, {
|
||||||
|
displayName,
|
||||||
|
error: 'Die Einladung ist ungültig, abgelaufen oder bereits verwendet.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
redirect(303, '/fundus');
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>Einladung annehmen | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<section class="auth-card">
|
||||||
|
<p class="eyebrow">Einladung</p>
|
||||||
|
<h1>Sendewerk-Konto aktivieren</h1>
|
||||||
|
{#if !data.valid && !form?.error}
|
||||||
|
<div class="form-message error" role="alert">
|
||||||
|
Die Einladung ist ungültig, abgelaufen oder bereits verwendet.
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<p>Die Einladung gilt für <strong>{data.email}</strong>.</p>
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
<form class="auth-form" method="POST">
|
||||||
|
<label
|
||||||
|
>Name<input
|
||||||
|
name="displayName"
|
||||||
|
required
|
||||||
|
maxlength="80"
|
||||||
|
value={form?.displayName ?? ''}
|
||||||
|
autocomplete="name"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Passwort<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minlength="12"
|
||||||
|
maxlength="256"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Konto aktivieren</button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
@@ -1,5 +1,87 @@
|
|||||||
import { getPieces } from '#lib/server/previews.js';
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import {
|
||||||
|
createPiece,
|
||||||
|
duplicatePiece,
|
||||||
|
getTaxonomy,
|
||||||
|
listPieces,
|
||||||
|
pieceTemplates,
|
||||||
|
setPieceArchived,
|
||||||
|
type PieceTemplateId
|
||||||
|
} from '#lib/server/content.js';
|
||||||
|
import { getPieceUsageContexts } from '#lib/server/shows.js';
|
||||||
|
|
||||||
export function load() {
|
export const load: PageServerLoad = ({ locals, url }) => {
|
||||||
return { pieces: getPieces() };
|
requireUser(locals.user);
|
||||||
|
const filters = {
|
||||||
|
query: url.searchParams.get('q') ?? '',
|
||||||
|
formatId: url.searchParams.get('format') ?? '',
|
||||||
|
topicId: url.searchParams.get('topic') ?? '',
|
||||||
|
categoryId: url.searchParams.get('category') ?? '',
|
||||||
|
status: url.searchParams.get('status') ?? '',
|
||||||
|
includeUsed: url.searchParams.get('includeUsed') === '1',
|
||||||
|
includePlanned: url.searchParams.get('includePlanned') === '1'
|
||||||
|
};
|
||||||
|
const pieces = listPieces({
|
||||||
|
statuses:
|
||||||
|
filters.status === 'ready'
|
||||||
|
? ['ready']
|
||||||
|
: filters.status === 'preparing'
|
||||||
|
? ['preparing']
|
||||||
|
: ['preparing', 'ready'],
|
||||||
|
query: filters.query,
|
||||||
|
formatId: filters.formatId,
|
||||||
|
topicId: filters.topicId,
|
||||||
|
categoryId: filters.categoryId
|
||||||
|
});
|
||||||
|
const usageContexts = getPieceUsageContexts(pieces.map((piece) => piece.id));
|
||||||
|
return {
|
||||||
|
pieces: pieces.map((piece) => ({ ...piece, ...usageContexts[piece.id] })),
|
||||||
|
taxonomy: getTaxonomy(),
|
||||||
|
templates: pieceTemplates,
|
||||||
|
filters
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
function actionError(cause: unknown) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'CONFLICT') return 'Das Piece wurde inzwischen geändert. Bitte Seite neu laden.';
|
||||||
|
if (code === 'NOT_FOUND') return 'Das Piece wurde nicht gefunden.';
|
||||||
|
return 'Die Aktion konnte nicht ausgeführt werden.';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
create: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = createPiece(String(data.get('template') || 'blank') as PieceTemplateId);
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'create', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
redirect(303, `/fundus/${id}`);
|
||||||
|
},
|
||||||
|
duplicate: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = await duplicatePiece(String(data.get('pieceId') || ''));
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'duplicate', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
redirect(303, `/fundus/${id}`);
|
||||||
|
},
|
||||||
|
archive: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
setPieceArchived(String(data.get('pieceId') || ''), Number(data.get('revision')), true);
|
||||||
|
return { intent: 'archive', success: 'Piece archiviert.' };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(409, { intent: 'archive', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
+184
-62
@@ -1,19 +1,48 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import PreviewNotice from '#lib/components/PreviewNotice.svelte';
|
import { goto, replaceState } from '$app/navigation';
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import { page } from '$app/state';
|
||||||
|
import { onMount, untrack } from 'svelte';
|
||||||
|
import PieceUsageHistory from '#lib/components/PieceUsageHistory.svelte';
|
||||||
import { formatClock } from '#lib/format.js';
|
import { formatClock } from '#lib/format.js';
|
||||||
import type { PageData } from './$types';
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
let { data }: { data: PageData } = $props();
|
let { data, form }: PageProps = $props();
|
||||||
let query = $state('');
|
let showUsedPieces = $state(untrack(() => data.filters.includeUsed));
|
||||||
let filter = $state<'all' | 'ready' | 'preparing'>('all');
|
let showPlannedPieces = $state(untrack(() => data.filters.includePlanned));
|
||||||
let filteredPieces = $derived(
|
let visiblePieces = $derived(
|
||||||
data.pieces.filter((piece) => {
|
data.pieces.filter(
|
||||||
const text =
|
(piece) =>
|
||||||
`${piece.title} ${piece.summary} ${piece.format} ${piece.topics.join(' ')}`.toLowerCase();
|
(showUsedPieces || piece.sentHistory.length === 0) &&
|
||||||
return text.includes(query.toLowerCase()) && (filter === 'all' || piece.status === filter);
|
(showPlannedPieces || !piece.isPlannedInActiveShow)
|
||||||
})
|
)
|
||||||
);
|
);
|
||||||
|
onMount(() => {
|
||||||
|
const syncFiltersFromHistory = () => {
|
||||||
|
const search = new URL(window.location.href).searchParams;
|
||||||
|
showUsedPieces = search.get('includeUsed') === '1';
|
||||||
|
showPlannedPieces = search.get('includePlanned') === '1';
|
||||||
|
};
|
||||||
|
window.addEventListener('popstate', syncFiltersFromHistory);
|
||||||
|
return () => window.removeEventListener('popstate', syncFiltersFromHistory);
|
||||||
|
});
|
||||||
|
|
||||||
|
function setSourceFilter(name: 'includeUsed' | 'includePlanned', checked: boolean) {
|
||||||
|
if (name === 'includeUsed') showUsedPieces = checked;
|
||||||
|
else showPlannedPieces = checked;
|
||||||
|
const url = new URL(page.url.href);
|
||||||
|
if (checked) url.searchParams.set(name, '1');
|
||||||
|
else url.searchParams.delete(name);
|
||||||
|
// This URL is cloned from the current page; only same-route filter parameters change.
|
||||||
|
// eslint-disable-next-line svelte/no-navigation-without-resolve
|
||||||
|
replaceState(url, page.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resetFilters() {
|
||||||
|
await goto(resolve('/fundus'), { invalidateAll: true });
|
||||||
|
showUsedPieces = false;
|
||||||
|
showPlannedPieces = false;
|
||||||
|
}
|
||||||
const statusLabel = {
|
const statusLabel = {
|
||||||
ready: 'Sendefertig',
|
ready: 'Sendefertig',
|
||||||
preparing: 'In Vorbereitung',
|
preparing: 'In Vorbereitung',
|
||||||
@@ -27,75 +56,168 @@
|
|||||||
<div class="page-wrap">
|
<div class="page-wrap">
|
||||||
<header class="page-heading split-heading">
|
<header class="page-heading split-heading">
|
||||||
<div>
|
<div>
|
||||||
<p class="eyebrow">Redaktioneller Fundus</p>
|
<h1>Fundus</h1>
|
||||||
<h1>Gute Stücke, sofort griffbereit.</h1>
|
<p class="page-intro">Vorbereitete Inhalte für kommende Sendungen.</p>
|
||||||
<p class="page-intro">
|
|
||||||
Vorbereitete Ideen, Gespräche und Fundstücke für die nächste Sendung.
|
|
||||||
</p>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="heading-stat" aria-label={`${data.pieces.length} Inhalte im Beispieldatensatz`}>
|
<div class="heading-stat" aria-label={`${visiblePieces.length} gefundene Inhalte`}>
|
||||||
<strong>{data.pieces.length}</strong><span>Inhalte</span>
|
<strong>{visiblePieces.length}</strong><span>Inhalte</span>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
{#if form?.success}<div class="form-message success" role="status">{form.success}</div>{/if}
|
||||||
|
|
||||||
<PreviewNotice area="Fundus" />
|
<details class="template-picker">
|
||||||
|
<summary>Neues Piece anlegen</summary>
|
||||||
<section class="library-toolbar" aria-label="Fundus durchsuchen und filtern">
|
<div class="template-grid">
|
||||||
<label class="search-field">
|
{#each data.templates as template (template.id)}
|
||||||
<span aria-hidden="true">⌕</span>
|
<form method="POST" action="?/create">
|
||||||
<span class="sr-only">Fundus durchsuchen</span>
|
<input type="hidden" name="template" value={template.id} />
|
||||||
<input bind:value={query} type="search" placeholder="Titel, Thema oder Format suchen" />
|
<button type="submit"
|
||||||
</label>
|
><strong>{template.name}</strong><span>{template.description}</span></button
|
||||||
<div class="filter-tabs" aria-label="Status filtern">
|
>
|
||||||
<button class:active={filter === 'all'} type="button" onclick={() => (filter = 'all')}
|
</form>
|
||||||
>Alle</button
|
{/each}
|
||||||
>
|
|
||||||
<button class:active={filter === 'ready'} type="button" onclick={() => (filter = 'ready')}
|
|
||||||
>Sendefertig</button
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
class:active={filter === 'preparing'}
|
|
||||||
type="button"
|
|
||||||
onclick={() => (filter = 'preparing')}>In Arbeit</button
|
|
||||||
>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</details>
|
||||||
|
|
||||||
{#if filteredPieces.length > 0}
|
<form
|
||||||
|
id="library-filters"
|
||||||
|
class="library-filters"
|
||||||
|
method="GET"
|
||||||
|
aria-label="Fundus durchsuchen und filtern"
|
||||||
|
>
|
||||||
|
<label class="search-field"
|
||||||
|
><span aria-hidden="true">⌕</span><span class="sr-only">Fundus durchsuchen</span><input
|
||||||
|
name="q"
|
||||||
|
type="search"
|
||||||
|
value={data.filters.query}
|
||||||
|
placeholder="Titel, Quelle oder Thema suchen"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
><span>Status</span><select name="status"
|
||||||
|
><option value="">Alle</option><option
|
||||||
|
value="ready"
|
||||||
|
selected={data.filters.status === 'ready'}>Sendefertig</option
|
||||||
|
><option value="preparing" selected={data.filters.status === 'preparing'}>In Arbeit</option
|
||||||
|
></select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
><span>Format</span><select name="format"
|
||||||
|
><option value="">Alle</option>{#each data.taxonomy.formats as item (item.id)}<option
|
||||||
|
value={item.id}
|
||||||
|
selected={data.filters.formatId === item.id}>{item.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
><span>Thema</span><select name="topic"
|
||||||
|
><option value="">Alle</option>{#each data.taxonomy.topics as item (item.id)}<option
|
||||||
|
value={item.id}
|
||||||
|
selected={data.filters.topicId === item.id}>{item.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
><span>Abschnitt</span><select name="category"
|
||||||
|
><option value="">Alle</option>{#each data.taxonomy.categories as item (item.id)}<option
|
||||||
|
value={item.id}
|
||||||
|
selected={data.filters.categoryId === item.id}>{item.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<button class="secondary-button" type="submit">Anwenden</button>
|
||||||
|
<button class="text-button" type="button" onclick={resetFilters}>Zurücksetzen</button>
|
||||||
|
</form>
|
||||||
|
<div class="library-filter-options" aria-label="Fundusauswahl erweitern">
|
||||||
|
<label class="filter-checkbox">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name="includeUsed"
|
||||||
|
value="1"
|
||||||
|
form="library-filters"
|
||||||
|
checked={showUsedPieces}
|
||||||
|
onchange={(event) => setSourceFilter('includeUsed', event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
<span>Auch verwendete Inhalte zeigen</span>
|
||||||
|
</label>
|
||||||
|
<label class="filter-checkbox">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name="includePlanned"
|
||||||
|
value="1"
|
||||||
|
form="library-filters"
|
||||||
|
checked={showPlannedPieces}
|
||||||
|
onchange={(event) => setSourceFilter('includePlanned', event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
<span>Auch eingeplante Inhalte zeigen</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if visiblePieces.length}
|
||||||
<div class="piece-grid">
|
<div class="piece-grid">
|
||||||
{#each filteredPieces as piece (piece.id)}
|
{#each visiblePieces as piece (piece.id)}
|
||||||
<article class="piece-card" style={`--category: ${piece.categoryColor}`}>
|
<article
|
||||||
<div class="piece-card-topline">
|
class="piece-card"
|
||||||
<span class="category-label"><i></i>{piece.category}</span>
|
style={`--category: ${piece.categories[0]?.color ?? '#8b8f98'}`}
|
||||||
|
>
|
||||||
|
{#if piece.mediaId}<img
|
||||||
|
class="piece-thumbnail"
|
||||||
|
src={`/media/${piece.mediaId}`}
|
||||||
|
alt=""
|
||||||
|
/>{:else}<span class="piece-thumbnail piece-thumbnail-placeholder" aria-hidden="true"
|
||||||
|
>S</span
|
||||||
|
>{/if}
|
||||||
|
<div class="piece-primary">
|
||||||
|
<h2><a href={resolve('/fundus/[id]', { id: piece.id })}>{piece.title}</a></h2>
|
||||||
|
<p>{piece.summary || 'Noch keine Kurzbeschreibung.'}</p>
|
||||||
|
<PieceUsageHistory history={piece.sentHistory} />
|
||||||
|
</div>
|
||||||
|
<div class="piece-classification">
|
||||||
|
<span class="category-label"
|
||||||
|
><i></i>{piece.categories.map((item) => item.name).join(', ') || 'Offen'}</span
|
||||||
|
>
|
||||||
|
<div class="piece-tags">
|
||||||
|
<span>{piece.format}</span>{#each piece.topics as topic (topic.id)}<span
|
||||||
|
>{topic.name}</span
|
||||||
|
>{/each}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="piece-state">
|
||||||
<span class:ready={piece.status === 'ready'} class="status-label"
|
<span class:ready={piece.status === 'ready'} class="status-label"
|
||||||
>{statusLabel[piece.status]}</span
|
>{statusLabel[piece.status]}</span
|
||||||
|
><span class="piece-facts"
|
||||||
|
><span><b>{formatClock(piece.durationSeconds)}</b> geplant</span><span
|
||||||
|
>{piece.sourceCount} {piece.sourceCount === 1 ? 'Quelle' : 'Quellen'}</span
|
||||||
|
></span
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
<h2>{piece.title}</h2>
|
<div class="piece-actions">
|
||||||
<p>{piece.summary}</p>
|
<a class="text-link" href={resolve('/fundus/[id]', { id: piece.id })}>Bearbeiten</a>
|
||||||
<div class="piece-tags">
|
<form method="POST" action="?/duplicate">
|
||||||
<span>{piece.format}</span>
|
<input type="hidden" name="pieceId" value={piece.id} /><button
|
||||||
{#each piece.topics as topic (topic)}<span>{topic}</span>{/each}
|
class="text-button"
|
||||||
|
type="submit">Duplizieren</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action="?/archive">
|
||||||
|
<input type="hidden" name="pieceId" value={piece.id} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="revision"
|
||||||
|
value={piece.revision}
|
||||||
|
/><button class="text-button danger-text" type="submit">Archivieren</button>
|
||||||
|
</form>
|
||||||
</div>
|
</div>
|
||||||
<footer>
|
|
||||||
<span><b>{formatClock(piece.durationSeconds)}</b> geplant</span>
|
|
||||||
<span>{piece.sourceCount} {piece.sourceCount === 1 ? 'Quelle' : 'Quellen'}</span>
|
|
||||||
</footer>
|
|
||||||
</article>
|
</article>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
<div class="empty-state">
|
<div class="empty-state">
|
||||||
<span aria-hidden="true">⌕</span>
|
<span aria-hidden="true">⌕</span>
|
||||||
<h2>Kein passendes Stück</h2>
|
<h2>Kein passendes Piece</h2>
|
||||||
<p>Suche oder Filter zurücksetzen, um wieder alle Beispieldaten zu sehen.</p>
|
<p>Andere Filter wählen oder ein neues Piece anlegen.</p>
|
||||||
<button
|
<a class="secondary-button" href={resolve('/fundus')}>Filter zurücksetzen</a>
|
||||||
type="button"
|
|
||||||
onclick={() => {
|
|
||||||
query = '';
|
|
||||||
filter = 'all';
|
|
||||||
}}>Filter zurücksetzen</button
|
|
||||||
>
|
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import { error, fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import {
|
||||||
|
deletePieceImage,
|
||||||
|
duplicatePiece,
|
||||||
|
getPiece,
|
||||||
|
getTaxonomy,
|
||||||
|
loadPiecePresentationMetadata,
|
||||||
|
savePiece,
|
||||||
|
setPieceArchived,
|
||||||
|
uploadPieceImage,
|
||||||
|
type EditablePieceStatus,
|
||||||
|
type PieceInput,
|
||||||
|
type PieceSourceInput
|
||||||
|
} from '#lib/server/content.js';
|
||||||
|
import { renderMarkdown } from '#lib/server/markdown.js';
|
||||||
|
|
||||||
|
function renderedFields(
|
||||||
|
piece: Pick<
|
||||||
|
PieceInput,
|
||||||
|
'intro' | 'researchText' | 'moderationNotes' | 'transitionText' | 'presentationText'
|
||||||
|
>
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
intro: renderMarkdown(piece.intro),
|
||||||
|
research: renderMarkdown(piece.researchText),
|
||||||
|
moderation: renderMarkdown(piece.moderationNotes),
|
||||||
|
transition: renderMarkdown(piece.transitionText),
|
||||||
|
presentation: renderMarkdown(piece.presentationText)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function text(data: FormData, name: string) {
|
||||||
|
return String(data.get(name) || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function durationInSeconds(data: FormData) {
|
||||||
|
return Math.round(Number(data.get('durationMinutes')) * 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pieceInput(data: FormData): PieceInput {
|
||||||
|
const labels = data.getAll('sourceLabel').map(String);
|
||||||
|
const urls = data.getAll('sourceUrl').map(String);
|
||||||
|
const timecodes = data.getAll('sourceTimecode').map(String);
|
||||||
|
const sources: PieceSourceInput[] = [];
|
||||||
|
for (let index = 0; index < Math.max(labels.length, urls.length, timecodes.length); index += 1) {
|
||||||
|
const label = labels[index]?.trim() ?? '';
|
||||||
|
const url = urls[index]?.trim() ?? '';
|
||||||
|
const timecode = timecodes[index]?.trim() ?? '';
|
||||||
|
if (!label && !url && !timecode) continue;
|
||||||
|
sources.push({
|
||||||
|
label,
|
||||||
|
url,
|
||||||
|
timecodeSeconds: timecode ? Number(timecode) : null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: text(data, 'title'),
|
||||||
|
summary: text(data, 'summary'),
|
||||||
|
formatId: text(data, 'formatId') || null,
|
||||||
|
status: text(data, 'status') as EditablePieceStatus,
|
||||||
|
durationSeconds: durationInSeconds(data),
|
||||||
|
intro: text(data, 'intro'),
|
||||||
|
researchText: text(data, 'researchText'),
|
||||||
|
moderationNotes: text(data, 'moderationNotes'),
|
||||||
|
transitionText: text(data, 'transitionText'),
|
||||||
|
presentationText: text(data, 'presentationText'),
|
||||||
|
presentationMode: text(data, 'presentationMode') as PieceInput['presentationMode'],
|
||||||
|
presentationSourcePosition: text(data, 'presentationSourcePosition')
|
||||||
|
? Number(data.get('presentationSourcePosition'))
|
||||||
|
: null,
|
||||||
|
presentationTitle: text(data, 'presentationTitle'),
|
||||||
|
presentationDescription: text(data, 'presentationDescription'),
|
||||||
|
presentationImageUrl: text(data, 'presentationImageUrl'),
|
||||||
|
presentationSiteName: text(data, 'presentationSiteName'),
|
||||||
|
presentationProvider: text(data, 'presentationProvider'),
|
||||||
|
presentationProviderId: text(data, 'presentationProviderId'),
|
||||||
|
presentationTitleManual: text(data, 'presentationTitleManual') === '1',
|
||||||
|
presentationDescriptionManual: text(data, 'presentationDescriptionManual') === '1',
|
||||||
|
presentationImageManual: text(data, 'presentationImageManual') === '1',
|
||||||
|
presentationMetadataFetchedAtUtc: text(data, 'presentationMetadataFetchedAtUtc') || null,
|
||||||
|
topicIds: data.getAll('topicIds').map(String),
|
||||||
|
categoryIds: data.getAll('categoryIds').map(String),
|
||||||
|
sources
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveError(cause: unknown) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'CONFLICT')
|
||||||
|
return {
|
||||||
|
status: 409,
|
||||||
|
error: 'Eine neuere Änderung liegt vor. Deine Eingaben wurden nicht überschrieben.',
|
||||||
|
conflict: true
|
||||||
|
};
|
||||||
|
if (code === 'INVALID_TITLE') return { status: 400, error: 'Bitte einen Titel eingeben.' };
|
||||||
|
if (code === 'INVALID_DURATION')
|
||||||
|
return { status: 400, error: 'Die Dauer muss zwischen 0 und 1.440 Minuten liegen.' };
|
||||||
|
if (code === 'INVALID_SOURCES')
|
||||||
|
return {
|
||||||
|
status: 400,
|
||||||
|
error: 'Quellen benötigen einen Namen und eine vollständige HTTP- oder HTTPS-Adresse.'
|
||||||
|
};
|
||||||
|
if (code === 'INVALID_PRESENTATION')
|
||||||
|
return {
|
||||||
|
status: 400,
|
||||||
|
error: 'Für Linkvorschau und Video muss eine vorhandene gültige Quelle ausgewählt sein.'
|
||||||
|
};
|
||||||
|
if (code.startsWith('INVALID_'))
|
||||||
|
return { status: 400, error: 'Mindestens ein Feld ist ungültig oder zu lang.' };
|
||||||
|
return {
|
||||||
|
status: 500,
|
||||||
|
error: 'Speichern fehlgeschlagen. Deine Eingaben bleiben im Formular erhalten.'
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals, params }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const piece = getPiece(params.id);
|
||||||
|
if (!piece) error(404, 'Piece nicht gefunden');
|
||||||
|
if (piece.status === 'archived') redirect(303, '/archiv');
|
||||||
|
return { piece, taxonomy: getTaxonomy(), rendered: renderedFields(piece) };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
save: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const input = pieceInput(data);
|
||||||
|
try {
|
||||||
|
const saved = savePiece(params.id, Number(data.get('revision')), input);
|
||||||
|
return { intent: 'save', saved: true, ...saved, rendered: renderedFields(input) };
|
||||||
|
} catch (cause) {
|
||||||
|
const problem = saveError(cause);
|
||||||
|
return fail(problem.status, { intent: 'save', ...problem });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
loadPreview: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
await loadPiecePresentationMetadata(params.id, Number(data.get('revision')));
|
||||||
|
} catch (cause) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'FETCH_BLOCKED') {
|
||||||
|
return fail(400, {
|
||||||
|
intent: 'loadPreview',
|
||||||
|
error: 'Interne oder private Netzwerkziele dürfen nicht abgerufen werden.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (code.startsWith('FETCH_')) {
|
||||||
|
return fail(400, {
|
||||||
|
intent: 'loadPreview',
|
||||||
|
error:
|
||||||
|
'Die Vorschau konnte nicht sicher geladen werden. Die manuellen Angaben bleiben erhalten.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const problem = saveError(cause);
|
||||||
|
return fail(problem.status, { intent: 'loadPreview', ...problem });
|
||||||
|
}
|
||||||
|
redirect(303, `/fundus/${params.id}`);
|
||||||
|
},
|
||||||
|
upload: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const image = data.get('image');
|
||||||
|
if (!(image instanceof File))
|
||||||
|
return fail(400, { intent: 'upload', error: 'Bitte ein Bild auswählen.' });
|
||||||
|
try {
|
||||||
|
await uploadPieceImage(params.id, Number(data.get('revision')), image, text(data, 'altText'));
|
||||||
|
} catch (cause) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'CONFLICT')
|
||||||
|
return fail(409, {
|
||||||
|
intent: 'upload',
|
||||||
|
error: 'Das Piece wurde inzwischen geändert. Bitte neu laden.'
|
||||||
|
});
|
||||||
|
if (code === 'INVALID_IMAGE_SIZE')
|
||||||
|
return fail(400, {
|
||||||
|
intent: 'upload',
|
||||||
|
error: 'Das Bild darf höchstens 5 MB groß und nicht leer sein.'
|
||||||
|
});
|
||||||
|
if (code === 'INVALID_IMAGE_TYPE')
|
||||||
|
return fail(400, { intent: 'upload', error: 'Erlaubt sind JPEG, PNG, WebP und GIF.' });
|
||||||
|
return fail(400, { intent: 'upload', error: 'Bild konnte nicht gespeichert werden.' });
|
||||||
|
}
|
||||||
|
redirect(303, `/fundus/${params.id}`);
|
||||||
|
},
|
||||||
|
deleteImage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
await deletePieceImage(params.id, text(data, 'mediaId'), Number(data.get('revision')));
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(409, { intent: 'deleteImage', error: saveError(cause).error });
|
||||||
|
}
|
||||||
|
redirect(303, `/fundus/${params.id}`);
|
||||||
|
},
|
||||||
|
duplicate: async ({ locals, params }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = await duplicatePiece(params.id);
|
||||||
|
} catch {
|
||||||
|
return fail(400, { intent: 'duplicate', error: 'Das Piece konnte nicht dupliziert werden.' });
|
||||||
|
}
|
||||||
|
redirect(303, `/fundus/${id}`);
|
||||||
|
},
|
||||||
|
archive: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
setPieceArchived(params.id, Number(data.get('revision')), true);
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(409, { intent: 'archive', error: saveError(cause).error });
|
||||||
|
}
|
||||||
|
redirect(303, '/archiv');
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,602 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { enhance, type SubmitFunction } from '$app/forms';
|
||||||
|
import { beforeNavigate, goto } from '$app/navigation';
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import { onDestroy, onMount, untrack } from 'svelte';
|
||||||
|
import MarkdownEditorField from '#lib/components/MarkdownEditorField.svelte';
|
||||||
|
import PieceEditorDialog from '#lib/components/PieceEditorDialog.svelte';
|
||||||
|
import PresentationDisplay from '#lib/components/PresentationDisplay.svelte';
|
||||||
|
import type { PresentationContent } from '#lib/server/presentation.js';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
let draft = $state(untrack(() => ({ ...data.piece })));
|
||||||
|
let durationMinutes = $state(untrack(() => Number((data.piece.durationSeconds / 60).toFixed(2))));
|
||||||
|
let revision = $state(untrack(() => data.piece.revision));
|
||||||
|
let sources = $state(untrack(() => data.piece.sources.map((source) => ({ ...source }))));
|
||||||
|
let rendered = $state(untrack(() => ({ ...data.rendered })));
|
||||||
|
let activeSection = $state<'script' | 'research' | 'presentation'>('script');
|
||||||
|
let saveState = $state<'idle' | 'dirty' | 'saving' | 'saved' | 'error' | 'conflict'>('idle');
|
||||||
|
let saveMessage = $state('Alle Änderungen gespeichert');
|
||||||
|
let sourceImageUnavailable = $state(false);
|
||||||
|
let editorDialog: { showModal: () => void; close: () => void };
|
||||||
|
let editorForm: HTMLFormElement;
|
||||||
|
let previewForm: HTMLFormElement;
|
||||||
|
let saveButton: HTMLButtonElement;
|
||||||
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
let generation = 0;
|
||||||
|
let saving = $state(false);
|
||||||
|
let actionsBlocked = $derived(
|
||||||
|
saveState === 'dirty' ||
|
||||||
|
saveState === 'saving' ||
|
||||||
|
saveState === 'error' ||
|
||||||
|
saveState === 'conflict'
|
||||||
|
);
|
||||||
|
let featuredSource = $derived(
|
||||||
|
draft.presentationSourcePosition === null
|
||||||
|
? (sources[0] ?? null)
|
||||||
|
: (sources[draft.presentationSourcePosition] ?? sources[0] ?? null)
|
||||||
|
);
|
||||||
|
let sourcePreviewImage = $derived(
|
||||||
|
draft.presentationImageUrl
|
||||||
|
? resolve('/fundus/[id]/praesentation/preview-image', { id: data.piece.id })
|
||||||
|
: ''
|
||||||
|
);
|
||||||
|
let previewContent = $derived<PresentationContent>({
|
||||||
|
mode: draft.presentationMode,
|
||||||
|
title: draft.title,
|
||||||
|
html: rendered.presentation,
|
||||||
|
source: featuredSource
|
||||||
|
? {
|
||||||
|
label: featuredSource.label || featuredSource.url,
|
||||||
|
url: featuredSource.url,
|
||||||
|
timecodeSeconds: featuredSource.timecodeSeconds
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
previewTitle: draft.presentationTitle,
|
||||||
|
description: draft.presentationDescription,
|
||||||
|
imageUrl: draft.presentationImageUrl,
|
||||||
|
siteName: draft.presentationSiteName,
|
||||||
|
provider: draft.presentationProvider as PresentationContent['provider'],
|
||||||
|
providerId: draft.presentationProviderId,
|
||||||
|
embedUrl:
|
||||||
|
draft.presentationProvider === 'youtube' && draft.presentationProviderId
|
||||||
|
? `https://www.youtube-nocookie.com/embed/${draft.presentationProviderId}${featuredSource?.timecodeSeconds ? `?start=${featuredSource.timecodeSeconds}` : ''}`
|
||||||
|
: draft.presentationProvider === 'tiktok' && draft.presentationProviderId
|
||||||
|
? `https://www.tiktok.com/player/v1/${draft.presentationProviderId}`
|
||||||
|
: ''
|
||||||
|
});
|
||||||
|
let pendingHref: string | null = null;
|
||||||
|
let allowNavigation = false;
|
||||||
|
|
||||||
|
const statusLabels = {
|
||||||
|
inbox: 'Eingang',
|
||||||
|
preparing: 'In Vorbereitung',
|
||||||
|
ready: 'Sendefertig'
|
||||||
|
};
|
||||||
|
|
||||||
|
onMount(() => editorDialog.showModal());
|
||||||
|
onDestroy(() => clearTimeout(timer));
|
||||||
|
beforeNavigate((navigation) => {
|
||||||
|
if (allowNavigation) return;
|
||||||
|
if (saveState === 'error' || saveState === 'conflict') {
|
||||||
|
if (!confirm('Ungespeicherte Änderungen verwerfen und Seite verlassen?')) navigation.cancel();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (saveState !== 'dirty' && saveState !== 'saving') return;
|
||||||
|
navigation.cancel();
|
||||||
|
if (navigation.willUnload) return;
|
||||||
|
pendingHref = navigation.to?.url.href ?? null;
|
||||||
|
if (!saving) submitSave();
|
||||||
|
});
|
||||||
|
|
||||||
|
function scheduleSave(event?: Event) {
|
||||||
|
const control = event?.target;
|
||||||
|
if (event?.type === 'change' && !(control instanceof HTMLSelectElement)) return;
|
||||||
|
if (
|
||||||
|
control instanceof HTMLInputElement &&
|
||||||
|
control.name === 'presentationMode' &&
|
||||||
|
control.value !== 'text' &&
|
||||||
|
draft.presentationSourcePosition === null
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
generation += 1;
|
||||||
|
saveState = 'dirty';
|
||||||
|
saveMessage = 'Ungespeicherte Änderungen';
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(submitSave, 900);
|
||||||
|
}
|
||||||
|
|
||||||
|
function submitSave() {
|
||||||
|
if (saving) return;
|
||||||
|
editorForm.requestSubmit(saveButton);
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestClose() {
|
||||||
|
const target = resolve('/fundus');
|
||||||
|
if (saveState === 'error' || saveState === 'conflict') {
|
||||||
|
if (!confirm('Ungespeicherte Änderungen verwerfen und Editor schließen?')) return;
|
||||||
|
allowNavigation = true;
|
||||||
|
void goto(target);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (saveState === 'dirty' || saveState === 'saving') {
|
||||||
|
pendingHref = new URL(target, window.location.href).href;
|
||||||
|
if (!saving) submitSave();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
allowNavigation = true;
|
||||||
|
void goto(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addSource() {
|
||||||
|
sources.push({ label: '', url: '', timecodeSeconds: null });
|
||||||
|
scheduleSave();
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeSource(index: number) {
|
||||||
|
sources.splice(index, 1);
|
||||||
|
if (draft.presentationSourcePosition === index) draft.presentationSourcePosition = null;
|
||||||
|
else if (
|
||||||
|
draft.presentationSourcePosition !== null &&
|
||||||
|
draft.presentationSourcePosition > index
|
||||||
|
) {
|
||||||
|
draft.presentationSourcePosition -= 1;
|
||||||
|
}
|
||||||
|
scheduleSave();
|
||||||
|
}
|
||||||
|
|
||||||
|
function presentationSourceChanged() {
|
||||||
|
draft.presentationMetadataFetchedAtUtc = null;
|
||||||
|
draft.presentationProvider = '';
|
||||||
|
draft.presentationProviderId = '';
|
||||||
|
sourceImageUnavailable = false;
|
||||||
|
if (!draft.presentationTitleManual) draft.presentationTitle = '';
|
||||||
|
if (!draft.presentationDescriptionManual) draft.presentationDescription = '';
|
||||||
|
if (!draft.presentationImageManual) draft.presentationImageUrl = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const enhanceSave: SubmitFunction = () => {
|
||||||
|
const submittedGeneration = generation;
|
||||||
|
saving = true;
|
||||||
|
saveState = 'saving';
|
||||||
|
saveMessage = 'Speichert …';
|
||||||
|
return async ({ result }) => {
|
||||||
|
saving = false;
|
||||||
|
if (result.type === 'success') {
|
||||||
|
const response = result.data as { revision: number; rendered: typeof rendered };
|
||||||
|
revision = response.revision;
|
||||||
|
rendered = response.rendered;
|
||||||
|
if (generation === submittedGeneration) {
|
||||||
|
saveState = 'saved';
|
||||||
|
saveMessage = 'Gespeichert';
|
||||||
|
if (pendingHref) {
|
||||||
|
const target = pendingHref;
|
||||||
|
pendingHref = null;
|
||||||
|
allowNavigation = true;
|
||||||
|
// The target comes from SvelteKit's own NavigationTarget, never from user input.
|
||||||
|
// eslint-disable-next-line svelte/no-navigation-without-resolve
|
||||||
|
await goto(new URL(target), { invalidateAll: true });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
saveState = 'dirty';
|
||||||
|
saveMessage = 'Weitere Änderungen warten';
|
||||||
|
timer = setTimeout(submitSave, 250);
|
||||||
|
}
|
||||||
|
} else if (result.type === 'failure') {
|
||||||
|
const response = result.data as { error?: string; conflict?: boolean };
|
||||||
|
saveState = response.conflict ? 'conflict' : 'error';
|
||||||
|
saveMessage = response.error ?? 'Speichern fehlgeschlagen.';
|
||||||
|
} else {
|
||||||
|
saveState = 'error';
|
||||||
|
saveMessage = 'Speichern fehlgeschlagen.';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>{draft.title} | Fundus | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<div class="piece-editor-route">
|
||||||
|
{#if form?.error}<div class="form-message error route-editor-error" role="alert">
|
||||||
|
{form.error}
|
||||||
|
</div>{/if}
|
||||||
|
<PieceEditorDialog
|
||||||
|
bind:this={editorDialog}
|
||||||
|
bind:activeSection
|
||||||
|
labelledby="piece-editor-title"
|
||||||
|
onrequestclose={requestClose}
|
||||||
|
>
|
||||||
|
{#snippet header()}
|
||||||
|
<p class="eyebrow">Fundus-Original</p>
|
||||||
|
<label class="piece-dialog-title">
|
||||||
|
<span class="sr-only">Titel</span>
|
||||||
|
<textarea
|
||||||
|
form="piece-editor-form"
|
||||||
|
name="title"
|
||||||
|
required
|
||||||
|
rows="1"
|
||||||
|
maxlength="200"
|
||||||
|
aria-label="Titel"
|
||||||
|
bind:value={draft.title}
|
||||||
|
oninput={scheduleSave}></textarea>
|
||||||
|
</label>
|
||||||
|
<h1 class="sr-only" id="piece-editor-title">{draft.title}</h1>
|
||||||
|
<small>Original im Fundus · Änderungen wirken nicht rückwirkend auf Einplanungen.</small>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<form
|
||||||
|
bind:this={editorForm}
|
||||||
|
id="piece-editor-form"
|
||||||
|
use:enhance={enhanceSave}
|
||||||
|
method="POST"
|
||||||
|
action="?/save"
|
||||||
|
class="piece-dialog-form"
|
||||||
|
oninput={scheduleSave}
|
||||||
|
onchange={scheduleSave}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={revision} />
|
||||||
|
|
||||||
|
<section class="piece-editor-panel" hidden={activeSection !== 'script'}>
|
||||||
|
<div class="piece-panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Für die Moderation</p>
|
||||||
|
<h2>Sendungstext</h2>
|
||||||
|
</div>
|
||||||
|
<small>Die drei Teile bleiben getrennt gespeichert.</small>
|
||||||
|
</div>
|
||||||
|
<div class="piece-writing-stack">
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="intro"
|
||||||
|
label="Einleitung"
|
||||||
|
placeholder="Wie beginnt dieses Thema in der Sendung?"
|
||||||
|
bind:value={draft.intro}
|
||||||
|
/>
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="moderationNotes"
|
||||||
|
label="Moderationsstichpunkte"
|
||||||
|
placeholder="Argumente, Fragen und Ablaufpunkte"
|
||||||
|
rows={10}
|
||||||
|
bind:value={draft.moderationNotes}
|
||||||
|
/>
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="transitionText"
|
||||||
|
label="Überleitung"
|
||||||
|
placeholder="Wie geht es zum nächsten Thema weiter?"
|
||||||
|
bind:value={draft.transitionText}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<details class="piece-meta-details">
|
||||||
|
<summary>
|
||||||
|
<span>Status, Dauer und Einordnung</span>
|
||||||
|
<small
|
||||||
|
>{statusLabels[draft.status as keyof typeof statusLabels]} · {durationMinutes || 0} Min.</small
|
||||||
|
>
|
||||||
|
</summary>
|
||||||
|
<div class="piece-meta-grid">
|
||||||
|
<label
|
||||||
|
>Status<select name="status" bind:value={draft.status}
|
||||||
|
><option value="inbox">Eingang</option><option value="preparing"
|
||||||
|
>In Vorbereitung</option
|
||||||
|
><option value="ready">Sendefertig</option></select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Dauer in Minuten<input
|
||||||
|
name="durationMinutes"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
max="1440"
|
||||||
|
step="any"
|
||||||
|
bind:value={durationMinutes}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Format<select name="formatId" bind:value={draft.formatId}
|
||||||
|
><option value={null}>Ohne Format</option
|
||||||
|
>{#each data.taxonomy.formats as item (item.id)}<option value={item.id}
|
||||||
|
>{item.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label class="wide-field"
|
||||||
|
>Kurzbeschreibung<textarea
|
||||||
|
name="summary"
|
||||||
|
rows="3"
|
||||||
|
maxlength="2000"
|
||||||
|
bind:value={draft.summary}></textarea></label
|
||||||
|
>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Themen</legend>
|
||||||
|
<div class="choice-grid">
|
||||||
|
{#each data.taxonomy.topics as item (item.id)}<label
|
||||||
|
><input
|
||||||
|
type="checkbox"
|
||||||
|
name="topicIds"
|
||||||
|
value={item.id}
|
||||||
|
bind:group={draft.topicIds}
|
||||||
|
/>{item.name}</label
|
||||||
|
>{/each}
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
<fieldset>
|
||||||
|
<legend>Vorgeschlagene Abschnittskategorien</legend>
|
||||||
|
<div class="choice-grid">
|
||||||
|
{#each data.taxonomy.categories as item (item.id)}<label
|
||||||
|
><input
|
||||||
|
type="checkbox"
|
||||||
|
name="categoryIds"
|
||||||
|
value={item.id}
|
||||||
|
bind:group={draft.categoryIds}
|
||||||
|
/><i style={`--choice-color:${item.color}`}></i>{item.name}</label
|
||||||
|
>{/each}
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="piece-editor-panel" hidden={activeSection !== 'research'}>
|
||||||
|
<div class="piece-panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Nicht öffentlich</p>
|
||||||
|
<h2>Recherche & Quellen</h2>
|
||||||
|
</div>
|
||||||
|
<small>Recherche und Material bleiben innerhalb der Redaktion.</small>
|
||||||
|
</div>
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="researchText"
|
||||||
|
label="Private Recherche"
|
||||||
|
placeholder="Hintergrund, Prüfung und offene Fragen"
|
||||||
|
rows={10}
|
||||||
|
privateField
|
||||||
|
bind:value={draft.researchText}
|
||||||
|
/>
|
||||||
|
<section class="piece-source-editor">
|
||||||
|
<div class="piece-subsection-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Fundstellen</p>
|
||||||
|
<h3>Quellen</h3>
|
||||||
|
</div>
|
||||||
|
<button class="secondary-button" type="button" onclick={addSource}
|
||||||
|
>Quelle hinzufügen</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{#if sources.length}<div class="source-list">
|
||||||
|
{#each sources as source, index (index)}<div class="source-row">
|
||||||
|
<label
|
||||||
|
>Name<input
|
||||||
|
name="sourceLabel"
|
||||||
|
maxlength="200"
|
||||||
|
bind:value={source.label}
|
||||||
|
/></label
|
||||||
|
><label
|
||||||
|
>URL<input
|
||||||
|
name="sourceUrl"
|
||||||
|
type="url"
|
||||||
|
maxlength="2000"
|
||||||
|
bind:value={source.url}
|
||||||
|
/></label
|
||||||
|
><label
|
||||||
|
>Zeitmarke in Sekunden<input
|
||||||
|
name="sourceTimecode"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
max="86400"
|
||||||
|
bind:value={source.timecodeSeconds}
|
||||||
|
/></label
|
||||||
|
><button
|
||||||
|
class="text-button danger-text"
|
||||||
|
type="button"
|
||||||
|
onclick={() => removeSource(index)}>Entfernen</button
|
||||||
|
>
|
||||||
|
</div>{/each}
|
||||||
|
</div>{:else}<p class="context-empty">Noch keine Quelle hinterlegt.</p>{/if}
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="piece-editor-panel" hidden={activeSection !== 'presentation'}>
|
||||||
|
<div class="piece-panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Öffentliche Ausgabe</p>
|
||||||
|
<h2>Präsentation</h2>
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
class="secondary-button"
|
||||||
|
href={resolve('/fundus/[id]/praesentation', { id: data.piece.id })}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener">In neuem Fenster testen</a
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="piece-presentation-layout">
|
||||||
|
<div class="piece-presentation-controls">
|
||||||
|
<MarkdownEditorField
|
||||||
|
name="presentationText"
|
||||||
|
label="Öffentlicher Text"
|
||||||
|
placeholder="Text für die Publikumsausgabe"
|
||||||
|
rows={8}
|
||||||
|
bind:value={draft.presentationText}
|
||||||
|
/>
|
||||||
|
<div class="presentation-mode-picker" role="group" aria-label="Darstellung">
|
||||||
|
{#each [['text', 'Text'], ['link', 'Linkvorschau'], ['video', 'Video']] as mode (mode[0])}<label
|
||||||
|
><input
|
||||||
|
type="radio"
|
||||||
|
name="presentationMode"
|
||||||
|
value={mode[0]}
|
||||||
|
bind:group={draft.presentationMode}
|
||||||
|
/>{mode[1]}</label
|
||||||
|
>{/each}
|
||||||
|
</div>
|
||||||
|
<div class="presentation-settings">
|
||||||
|
<label
|
||||||
|
>Quelle<select
|
||||||
|
name="presentationSourcePosition"
|
||||||
|
bind:value={draft.presentationSourcePosition}
|
||||||
|
onchange={presentationSourceChanged}
|
||||||
|
><option value={null}>Quelle auswählen</option
|
||||||
|
>{#each sources as source, index (index)}{#if source.url}<option value={index}
|
||||||
|
>{source.label || source.url}</option
|
||||||
|
>{/if}{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Titel<input
|
||||||
|
name="presentationTitle"
|
||||||
|
maxlength="300"
|
||||||
|
bind:value={draft.presentationTitle}
|
||||||
|
oninput={() => (draft.presentationTitleManual = true)}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Bild-URL<input
|
||||||
|
name="presentationImageUrl"
|
||||||
|
type="url"
|
||||||
|
maxlength="2000"
|
||||||
|
bind:value={draft.presentationImageUrl}
|
||||||
|
oninput={() => (draft.presentationImageManual = true)}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label class="wide-field"
|
||||||
|
>Anreißer<textarea
|
||||||
|
name="presentationDescription"
|
||||||
|
rows="3"
|
||||||
|
maxlength="1000"
|
||||||
|
bind:value={draft.presentationDescription}
|
||||||
|
oninput={() => (draft.presentationDescriptionManual = true)}></textarea></label
|
||||||
|
>
|
||||||
|
<div class="presentation-preview-actions wide-field">
|
||||||
|
<button
|
||||||
|
class="secondary-button"
|
||||||
|
type="button"
|
||||||
|
onclick={() => previewForm.requestSubmit()}
|
||||||
|
disabled={actionsBlocked || draft.presentationSourcePosition === null}
|
||||||
|
>Vorschau laden</button
|
||||||
|
><small
|
||||||
|
>{draft.presentationMetadataFetchedAtUtc
|
||||||
|
? `Zuletzt geladen: ${new Date(draft.presentationMetadataFetchedAtUtc).toLocaleString('de-DE')}`
|
||||||
|
: 'Noch keine Metadaten geladen.'}</small
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<aside class="piece-presentation-preview" aria-label="Präsentationsvorschau">
|
||||||
|
<PresentationDisplay
|
||||||
|
content={previewContent}
|
||||||
|
imageSrc={sourceImageUnavailable ? '' : sourcePreviewImage}
|
||||||
|
/>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationTitleManual"
|
||||||
|
value={draft.presentationTitleManual ? '1' : '0'}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationDescriptionManual"
|
||||||
|
value={draft.presentationDescriptionManual ? '1' : '0'}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationImageManual"
|
||||||
|
value={draft.presentationImageManual ? '1' : '0'}
|
||||||
|
/>
|
||||||
|
<input type="hidden" name="presentationSiteName" value={draft.presentationSiteName} />
|
||||||
|
<input type="hidden" name="presentationProvider" value={draft.presentationProvider} />
|
||||||
|
<input type="hidden" name="presentationProviderId" value={draft.presentationProviderId} />
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="presentationMetadataFetchedAtUtc"
|
||||||
|
value={draft.presentationMetadataFetchedAtUtc ?? ''}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<section class="piece-editor-panel piece-media-panel" hidden={activeSection !== 'research'}>
|
||||||
|
<div class="piece-subsection-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Private Dateien</p>
|
||||||
|
<h3>Material</h3>
|
||||||
|
</div>
|
||||||
|
<small>JPEG, PNG, WebP oder GIF bis 5 MB</small>
|
||||||
|
</div>
|
||||||
|
{#if data.piece.media.length}<div class="media-grid">
|
||||||
|
{#each data.piece.media as media (media.id)}<figure>
|
||||||
|
<img src={`/media/${media.id}`} alt={media.altText} />
|
||||||
|
<figcaption>
|
||||||
|
<span>{media.altText || media.originalName}</span>
|
||||||
|
<form method="POST" action="?/deleteImage">
|
||||||
|
<input type="hidden" name="revision" value={revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="mediaId"
|
||||||
|
value={media.id}
|
||||||
|
/><button class="text-button danger-text" type="submit" disabled={actionsBlocked}
|
||||||
|
>Entfernen</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</figcaption>
|
||||||
|
</figure>{/each}
|
||||||
|
</div>{/if}
|
||||||
|
<form method="POST" action="?/upload" enctype="multipart/form-data" class="upload-form">
|
||||||
|
<input type="hidden" name="revision" value={revision} /><label
|
||||||
|
>Bild<input
|
||||||
|
name="image"
|
||||||
|
type="file"
|
||||||
|
accept="image/jpeg,image/png,image/webp,image/gif"
|
||||||
|
required
|
||||||
|
/></label
|
||||||
|
><label
|
||||||
|
>Alternativtext<input
|
||||||
|
name="altText"
|
||||||
|
maxlength="300"
|
||||||
|
placeholder="Was ist auf dem Bild zu sehen?"
|
||||||
|
/></label
|
||||||
|
><button class="secondary-button" type="submit" disabled={actionsBlocked}
|
||||||
|
>Bild hochladen</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{#snippet footer()}
|
||||||
|
<div class="piece-dialog-secondary-actions">
|
||||||
|
<form method="POST" action="?/duplicate">
|
||||||
|
<button class="text-button" type="submit" disabled={actionsBlocked}>Duplizieren</button>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action="?/archive">
|
||||||
|
<input type="hidden" name="revision" value={revision} /><button
|
||||||
|
class="text-button danger-text"
|
||||||
|
type="submit"
|
||||||
|
aria-label="Piece archivieren"
|
||||||
|
disabled={actionsBlocked}>Archivieren</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="piece-dialog-primary-action">
|
||||||
|
<span
|
||||||
|
class="save-indicator"
|
||||||
|
class:problem={saveState === 'error' || saveState === 'conflict'}
|
||||||
|
role="status"
|
||||||
|
aria-live="polite">{saveMessage}</span
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
bind:this={saveButton}
|
||||||
|
class="primary-button"
|
||||||
|
type="submit"
|
||||||
|
form="piece-editor-form"
|
||||||
|
disabled={saving}>Jetzt speichern</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
</PieceEditorDialog>
|
||||||
|
|
||||||
|
<form
|
||||||
|
bind:this={previewForm}
|
||||||
|
id="preview-load-form"
|
||||||
|
method="POST"
|
||||||
|
action="?/loadPreview"
|
||||||
|
use:enhance
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={revision} />
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { getPiece } from '#lib/server/content.js';
|
||||||
|
import { renderMarkdown } from '#lib/server/markdown.js';
|
||||||
|
import { buildEmbedUrl, type PresentationContent } from '#lib/server/presentation.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals, params }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const piece = getPiece(params.id);
|
||||||
|
if (!piece) error(404, 'Piece nicht gefunden');
|
||||||
|
const source =
|
||||||
|
piece.presentationSourcePosition === null
|
||||||
|
? null
|
||||||
|
: (piece.sources[piece.presentationSourcePosition] ?? null);
|
||||||
|
const content: PresentationContent & {
|
||||||
|
sources: typeof piece.sources;
|
||||||
|
images: { id: string; altText: string }[];
|
||||||
|
} = {
|
||||||
|
mode: piece.presentationMode,
|
||||||
|
title: piece.title,
|
||||||
|
html: renderMarkdown(piece.presentationText),
|
||||||
|
source,
|
||||||
|
previewTitle: piece.presentationTitle,
|
||||||
|
description: piece.presentationDescription,
|
||||||
|
imageUrl: piece.presentationImageUrl,
|
||||||
|
siteName: piece.presentationSiteName,
|
||||||
|
provider:
|
||||||
|
piece.presentationProvider === 'youtube' || piece.presentationProvider === 'tiktok'
|
||||||
|
? piece.presentationProvider
|
||||||
|
: '',
|
||||||
|
providerId: piece.presentationProviderId,
|
||||||
|
embedUrl: buildEmbedUrl(
|
||||||
|
piece.presentationProvider === 'youtube' || piece.presentationProvider === 'tiktok'
|
||||||
|
? piece.presentationProvider
|
||||||
|
: '',
|
||||||
|
piece.presentationProviderId,
|
||||||
|
source?.timecodeSeconds ?? null
|
||||||
|
),
|
||||||
|
sources: piece.sources,
|
||||||
|
images: piece.media.map((item) => ({ id: item.id, altText: item.altText }))
|
||||||
|
};
|
||||||
|
return { pieceId: piece.id, content };
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import PresentationDisplay from '#lib/components/PresentationDisplay.svelte';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
|
let { data }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Präsentation testen | Sendewerk</title>
|
||||||
|
<meta name="robots" content="noindex, nofollow, noarchive" />
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="heinzlive-output presentation-test-output">
|
||||||
|
<div class="presentation-test-status" role="status">Isolierte Testansicht</div>
|
||||||
|
<PresentationDisplay
|
||||||
|
content={data.content}
|
||||||
|
imageSrc={data.content.mode === 'text'
|
||||||
|
? '/media'
|
||||||
|
: `/fundus/${data.pieceId}/praesentation/preview-image`}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { getPiece } from '#lib/server/content.js';
|
||||||
|
import { fetchPresentationImage } from '#lib/server/presentation.js';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals, params }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const piece = getPiece(params.id);
|
||||||
|
if (!piece?.presentationImageUrl) error(404, 'Vorschaubild nicht verfügbar');
|
||||||
|
try {
|
||||||
|
const image = await fetchPresentationImage(piece.presentationImageUrl);
|
||||||
|
return new Response(new Uint8Array(image.data), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': image.mimeType,
|
||||||
|
'Content-Length': String(image.data.byteLength),
|
||||||
|
'Cache-Control': 'private, max-age=300',
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'Cross-Origin-Resource-Policy': 'same-origin',
|
||||||
|
'Content-Security-Policy': "default-src 'none'; sandbox"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
error(404, 'Vorschaubild nicht verfügbar');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
import { getPresentationView } from '#lib/server/live.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ params }) => {
|
||||||
|
const view = getPresentationView(params.token);
|
||||||
|
if (!view) error(404, 'Präsentationsausgabe nicht gefunden');
|
||||||
|
return { view };
|
||||||
|
};
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { page } from '$app/state';
|
||||||
|
import { onMount, untrack } from 'svelte';
|
||||||
|
import PresentationDisplay from '#lib/components/PresentationDisplay.svelte';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
|
let { data }: PageProps = $props();
|
||||||
|
let view = $state(untrack(() => data.view));
|
||||||
|
let connection = $state<'connected' | 'waiting' | 'interrupted'>('connected');
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
let stopped = false;
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
async function refresh() {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/heinzlive/${page.params.token}/state`, {
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
cache: 'no-store'
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('STATE_UNAVAILABLE');
|
||||||
|
const next = await response.json();
|
||||||
|
if (next.revision !== view.revision) view = next;
|
||||||
|
connection = 'connected';
|
||||||
|
} catch {
|
||||||
|
connection = 'interrupted';
|
||||||
|
}
|
||||||
|
if (!stopped) timer = setTimeout(refresh, connection === 'interrupted' ? 3000 : 1000);
|
||||||
|
}
|
||||||
|
connection = 'waiting';
|
||||||
|
timer = setTimeout(refresh, 500);
|
||||||
|
return () => {
|
||||||
|
stopped = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>heinzlive</title>
|
||||||
|
<meta name="robots" content="noindex, nofollow, noarchive" />
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main class="heinzlive-output">
|
||||||
|
<div class="output-connection sr-only" class:problem={connection === 'interrupted'} role="status">
|
||||||
|
<span></span>{connection === 'interrupted' ? 'Verbindung unterbrochen' : 'Verbunden'}
|
||||||
|
</div>
|
||||||
|
{#if view.content}
|
||||||
|
{#key view.revision}
|
||||||
|
<PresentationDisplay
|
||||||
|
content={view.content}
|
||||||
|
imageSrc={view.content.mode === 'text'
|
||||||
|
? `/heinzlive/${page.params.token}/media`
|
||||||
|
: `/heinzlive/${page.params.token}/preview-image`}
|
||||||
|
/>
|
||||||
|
{/key}
|
||||||
|
{:else}
|
||||||
|
<section class="output-idle">
|
||||||
|
<div class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></div>
|
||||||
|
<h1>Bereit für den nächsten Inhalt</h1>
|
||||||
|
<p>Die Moderation wählt ausdrücklich aus, was hier erscheint.</p>
|
||||||
|
</section>
|
||||||
|
{/if}
|
||||||
|
</main>
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { getPresentationMedia } from '#lib/server/live.js';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ params }) => {
|
||||||
|
const media = await getPresentationMedia(params.token, params.id);
|
||||||
|
if (!media) error(404, 'Bild nicht gefunden');
|
||||||
|
return new Response(media.data, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': media.mimeType,
|
||||||
|
'Content-Length': String(media.byteSize),
|
||||||
|
'Cache-Control': 'no-store',
|
||||||
|
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||||
|
'Cross-Origin-Resource-Policy': 'same-origin',
|
||||||
|
'X-Content-Type-Options': 'nosniff'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { getPresentationPreviewImage } from '#lib/server/live.js';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ params }) => {
|
||||||
|
const image = await getPresentationPreviewImage(params.token);
|
||||||
|
if (!image) error(404, 'Vorschaubild nicht verfügbar');
|
||||||
|
return new Response(new Uint8Array(image.data), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': image.mimeType,
|
||||||
|
'Content-Length': String(image.data.byteLength),
|
||||||
|
'Cache-Control': 'private, max-age=300',
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'Cross-Origin-Resource-Policy': 'same-origin',
|
||||||
|
'Content-Security-Policy': "default-src 'none'; sandbox"
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { error, json } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { getPresentationView } from '#lib/server/live.js';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = ({ params }) => {
|
||||||
|
const view = getPresentationView(params.token);
|
||||||
|
if (!view) error(404, 'Präsentationsausgabe nicht gefunden');
|
||||||
|
return json(view, { headers: { 'Cache-Control': 'no-store' } });
|
||||||
|
};
|
||||||
+125
-13
@@ -1,15 +1,127 @@
|
|||||||
import { getShow } from '#lib/server/previews.js';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { error, fail } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import {
|
||||||
|
completeCurrent,
|
||||||
|
getLiveView,
|
||||||
|
goBack,
|
||||||
|
issuePresentationAccess,
|
||||||
|
moveOpenUsage,
|
||||||
|
presentUsage,
|
||||||
|
skipCurrent,
|
||||||
|
startOrResumeLive
|
||||||
|
} from '#lib/server/live.js';
|
||||||
|
import { listShows } from '#lib/server/shows.js';
|
||||||
|
|
||||||
export function load() {
|
function text(data: FormData, name: string) {
|
||||||
const show = getShow();
|
return String(data.get(name) || '');
|
||||||
const usages = show.sections.flatMap((section) =>
|
|
||||||
section.usages
|
|
||||||
.filter((usage) => !usage.isReserve)
|
|
||||||
.map((usage) => ({ ...usage, section: section.name }))
|
|
||||||
);
|
|
||||||
const currentIndex = Math.max(
|
|
||||||
0,
|
|
||||||
usages.findIndex((usage) => usage.status === 'current')
|
|
||||||
);
|
|
||||||
return { show, current: usages[currentIndex], next: usages[currentIndex + 1] ?? null };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function actionError(cause: unknown) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'CONFLICT')
|
||||||
|
return {
|
||||||
|
status: 409,
|
||||||
|
error: 'Der Live-Stand wurde bereits geändert. Die Ansicht wurde erneuert.'
|
||||||
|
};
|
||||||
|
if (code === 'NO_CURRENT') return { status: 409, error: 'Es ist kein aktuelles Piece aktiv.' };
|
||||||
|
if (code === 'NO_PREVIOUS') return { status: 409, error: 'Es gibt kein vorheriges Piece.' };
|
||||||
|
if (code === 'LIVE_ORDER_LOCKED')
|
||||||
|
return {
|
||||||
|
status: 409,
|
||||||
|
error: 'Nur offene Pieces hinter dem aktuellen Stand können sortiert werden.'
|
||||||
|
};
|
||||||
|
if (code === 'SHOW_COMPLETED')
|
||||||
|
return { status: 409, error: 'Abgeschlossene Sendungen können nicht live gesteuert werden.' };
|
||||||
|
if (code === 'NOT_FOUND')
|
||||||
|
return { status: 404, error: 'Sendung oder Piece wurde nicht gefunden.' };
|
||||||
|
if (code.startsWith('INVALID_')) return { status: 400, error: 'Die Live-Aktion ist ungültig.' };
|
||||||
|
return { status: 500, error: 'Die Live-Aktion konnte nicht gespeichert werden.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function attempt(intent: string, operation: () => unknown) {
|
||||||
|
try {
|
||||||
|
return { intent, success: true, result: operation() };
|
||||||
|
} catch (cause) {
|
||||||
|
const problem = actionError(cause);
|
||||||
|
return fail(problem.status, { intent, ...problem });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals, url }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const showId = url.searchParams.get('show') || listShows()[0]?.id;
|
||||||
|
if (!showId) error(404, 'Keine Sendung vorhanden');
|
||||||
|
try {
|
||||||
|
return { live: getLiveView(showId), commandId: randomUUID() };
|
||||||
|
} catch (cause) {
|
||||||
|
if (cause instanceof Error && cause.message === 'NOT_FOUND')
|
||||||
|
error(404, 'Sendung nicht gefunden');
|
||||||
|
throw cause;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
start: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('start', () =>
|
||||||
|
startOrResumeLive(text(data, 'showId'), text(data, 'commandId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
complete: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('complete', () =>
|
||||||
|
completeCurrent(text(data, 'showId'), text(data, 'commandId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
skip: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('skip', () =>
|
||||||
|
skipCurrent(text(data, 'showId'), text(data, 'commandId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
back: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('back', () =>
|
||||||
|
goBack(text(data, 'showId'), text(data, 'commandId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
present: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('present', () =>
|
||||||
|
presentUsage(
|
||||||
|
text(data, 'showId'),
|
||||||
|
text(data, 'usageId') || null,
|
||||||
|
text(data, 'commandId'),
|
||||||
|
Number(data.get('revision'))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
moveUsage: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('moveUsage', () =>
|
||||||
|
moveOpenUsage(text(data, 'showId'), text(data, 'usageId'), Number(data.get('showRevision')), {
|
||||||
|
sectionId: text(data, 'sectionId') || null,
|
||||||
|
position: Number(data.get('position'))
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
createOutput: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
const token = issuePresentationAccess(text(data, 'showId'));
|
||||||
|
return { intent: 'createOutput', success: true, outputUrl: `/heinzlive/${token}` };
|
||||||
|
} catch (cause) {
|
||||||
|
const problem = actionError(cause);
|
||||||
|
return fail(problem.status, { intent: 'createOutput', ...problem });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
+373
-64
@@ -1,92 +1,401 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import PreviewNotice from '#lib/components/PreviewNotice.svelte';
|
import { enhance, type SubmitFunction } from '$app/forms';
|
||||||
import { formatClock } from '#lib/format.js';
|
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import type { PageData } from './$types';
|
import { onMount, untrack } from 'svelte';
|
||||||
|
import { formatClock, formatDuration } from '#lib/format.js';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
let { data }: { data: PageData } = $props();
|
let { data, form }: PageProps = $props();
|
||||||
let promptSize = $state(1.55);
|
let promptSize = $state(1.55);
|
||||||
|
let showRail = $state(true);
|
||||||
|
let showTimes = $state(true);
|
||||||
|
let popupMessage = $state('');
|
||||||
|
let now = $state(Date.now());
|
||||||
|
let loadedAt = $state(Date.now());
|
||||||
|
let currentId = $state(untrack(() => data.live.current?.id ?? null));
|
||||||
|
let outputWindow: Window | null = null;
|
||||||
|
let progress = $derived(
|
||||||
|
data.live.totalCount ? Math.round((data.live.completedCount / data.live.totalCount) * 100) : 0
|
||||||
|
);
|
||||||
|
let currentActualSeconds = $derived(
|
||||||
|
(data.live.current?.actualDurationSeconds ?? 0) +
|
||||||
|
(data.live.current ? Math.max(0, Math.floor((now - loadedAt) / 1000)) : 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const nextCurrentId = data.live.current?.id ?? null;
|
||||||
|
if (nextCurrentId !== currentId) {
|
||||||
|
currentId = nextCurrentId;
|
||||||
|
loadedAt = Date.now();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const key = `sendewerk-live-${data.live.show.id}`;
|
||||||
|
try {
|
||||||
|
const settings = JSON.parse(localStorage.getItem(key) || '{}');
|
||||||
|
if (typeof settings.promptSize === 'number') promptSize = settings.promptSize;
|
||||||
|
if (typeof settings.showRail === 'boolean') showRail = settings.showRail;
|
||||||
|
if (typeof settings.showTimes === 'boolean') showTimes = settings.showTimes;
|
||||||
|
if (typeof settings.scrollY === 'number')
|
||||||
|
requestAnimationFrame(() => scrollTo(0, settings.scrollY));
|
||||||
|
} catch {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
const interval = setInterval(() => (now = Date.now()), 1000);
|
||||||
|
const persistScroll = () => persistSettings();
|
||||||
|
addEventListener('scroll', persistScroll, { passive: true });
|
||||||
|
return () => {
|
||||||
|
clearInterval(interval);
|
||||||
|
removeEventListener('scroll', persistScroll);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function persistSettings() {
|
||||||
|
localStorage.setItem(
|
||||||
|
`sendewerk-live-${data.live.show.id}`,
|
||||||
|
JSON.stringify({ promptSize, showRail, showTimes, scrollY })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function changePromptSize(delta: number) {
|
||||||
|
promptSize = Math.min(2.4, Math.max(1.1, promptSize + delta));
|
||||||
|
persistSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleRail() {
|
||||||
|
showRail = !showRail;
|
||||||
|
persistSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleTimes() {
|
||||||
|
showTimes = !showTimes;
|
||||||
|
persistSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
function liveAction(name: string) {
|
||||||
|
return `?show=${encodeURIComponent(data.live.show.id)}&/${name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const enhanceCommand: SubmitFunction = ({ formElement, formData, submitter }) => {
|
||||||
|
const command = formElement.elements.namedItem('commandId');
|
||||||
|
if (command instanceof HTMLInputElement) {
|
||||||
|
command.value = crypto.randomUUID();
|
||||||
|
formData.set('commandId', command.value);
|
||||||
|
}
|
||||||
|
if (submitter instanceof HTMLButtonElement) submitter.disabled = true;
|
||||||
|
return async ({ update }) => {
|
||||||
|
await update({ reset: false, invalidateAll: true });
|
||||||
|
if (submitter instanceof HTMLButtonElement) submitter.disabled = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const enhanceOutput: SubmitFunction = ({ submitter }) => {
|
||||||
|
popupMessage = '';
|
||||||
|
outputWindow = window.open('about:blank', 'heinzlive-output');
|
||||||
|
if (!outputWindow) popupMessage = 'Popup blockiert. Bitte Popups erlauben und erneut öffnen.';
|
||||||
|
if (submitter instanceof HTMLButtonElement) submitter.disabled = true;
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'success') {
|
||||||
|
const response = result.data as { outputUrl: string };
|
||||||
|
if (outputWindow && !outputWindow.closed) {
|
||||||
|
outputWindow.location.href = response.outputUrl;
|
||||||
|
popupMessage = 'Präsentationsfenster verbunden.';
|
||||||
|
} else {
|
||||||
|
popupMessage = `Präsentationsfenster konnte nicht geöffnet werden: ${response.outputUrl}`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
outputWindow?.close();
|
||||||
|
}
|
||||||
|
await update({ reset: false, invalidateAll: false });
|
||||||
|
if (submitter instanceof HTMLButtonElement) submitter.disabled = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head><title>Live-Vorschau | Sendewerk</title></svelte:head>
|
<svelte:head><title>Live | {data.live.show.title} | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
<div class="page-wrap live-page">
|
<div class="page-wrap live-page live-controller">
|
||||||
<header class="live-header">
|
<header class="live-header">
|
||||||
<div>
|
<div>
|
||||||
<p class="eyebrow"><span class="live-pulse"></span> Live-Modus · Vorschau</p>
|
<p class="eyebrow"><span class="live-pulse"></span> Live-Steuerung</p>
|
||||||
<h1>{data.show.title}</h1>
|
<h1>{data.live.show.title}</h1>
|
||||||
|
<p class="live-state-line">
|
||||||
|
{data.live.startedAtUtc
|
||||||
|
? 'Live-Stand wird automatisch gespeichert.'
|
||||||
|
: 'Noch nicht gestartet.'}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="live-header-actions">
|
<div class="live-header-actions">
|
||||||
<div class="font-control" aria-label="Prompter-Schriftgröße">
|
<div class="font-control" aria-label="Prompter-Schriftgröße">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onclick={() => (promptSize = Math.max(1.15, promptSize - 0.1))}
|
onclick={() => changePromptSize(-0.1)}
|
||||||
aria-label="Schrift verkleinern">A−</button
|
aria-label="Schrift verkleinern">A−</button
|
||||||
>
|
>
|
||||||
<button
|
<button type="button" onclick={() => changePromptSize(0.1)} aria-label="Schrift vergrößern"
|
||||||
type="button"
|
>A+</button
|
||||||
onclick={() => (promptSize = Math.min(2.1, promptSize + 0.1))}
|
|
||||||
aria-label="Schrift vergrößern">A+</button
|
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
<a href={resolve('/sendungen')}>Planung schließen</a>
|
<button type="button" class="text-button" aria-pressed={!showTimes} onclick={toggleTimes}
|
||||||
|
>{showTimes ? 'Zeiten ausblenden' : 'Zeiten einblenden'}</button
|
||||||
|
>
|
||||||
|
<button type="button" class="text-button" aria-pressed={!showRail} onclick={toggleRail}
|
||||||
|
>{showRail ? 'Ablauf ausblenden' : 'Ablauf einblenden'}</button
|
||||||
|
>
|
||||||
|
<a href={resolve('/sendungen/[id]', { id: data.live.show.id })}>Zur Planung</a>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<PreviewNotice area="Live-Modus" />
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
{#if popupMessage}<div class="form-message" role="status">{popupMessage}</div>{/if}
|
||||||
|
|
||||||
<div class="live-grid">
|
<section class="live-toolbar" aria-label="Live-Sitzung">
|
||||||
<section class="live-current" style={`--prompt-size: ${promptSize}rem`}>
|
<form method="POST" action={liveAction('start')} use:enhance={enhanceCommand}>
|
||||||
<div class="live-kicker">
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
<span>Aktuell · {data.current.section}</span><strong
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
>{formatClock(data.current.durationSeconds)}</strong
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
>
|
<button class="primary-button" type="submit">
|
||||||
</div>
|
{data.live.startedAtUtc ? 'Live-Stand wiederaufnehmen' : 'Sendung starten'}
|
||||||
<h2>{data.current.title}</h2>
|
</button>
|
||||||
<div class="prompter-copy">{data.current.intro}</div>
|
</form>
|
||||||
<div class="moderation-card">
|
<form method="POST" action={liveAction('createOutput')} use:enhance={enhanceOutput}>
|
||||||
<span>Moderationsstichpunkte</span>
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
<p>{data.current.moderation}</p>
|
<button class="secondary-button" type="submit">Präsentationsfenster öffnen</button>
|
||||||
</div>
|
</form>
|
||||||
<details class="research-details">
|
<div class="live-session-summary">
|
||||||
<summary>Recherche öffnen</summary>
|
<strong>{data.live.completedCount} / {data.live.totalCount}</strong>
|
||||||
|
<span>{progress}% bearbeitet</span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class:without-rail={!showRail} class="live-grid">
|
||||||
|
{#if data.live.current}<main
|
||||||
|
class="live-current"
|
||||||
|
style={`--prompt-size: ${promptSize}rem`}
|
||||||
|
aria-labelledby="current-title"
|
||||||
|
>
|
||||||
|
<div class="live-kicker">
|
||||||
|
<span>Aktuell · {data.live.current.sectionName}</span>
|
||||||
|
{#if showTimes}<strong
|
||||||
|
>{formatClock(currentActualSeconds)} / {formatClock(
|
||||||
|
data.live.current.durationSeconds
|
||||||
|
)}</strong
|
||||||
|
>{/if}
|
||||||
|
</div>
|
||||||
|
<h2 id="current-title">{data.live.current.title}</h2>
|
||||||
|
<!-- HTML is produced exclusively by the server-side allowlist sanitizer. -->
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
<div class="prompter-copy">{@html data.live.current.introHtml}</div>
|
||||||
|
{#if data.live.current.moderationHtml}<section class="moderation-card">
|
||||||
|
<span>Moderationsstichpunkte</span>
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
<div class="live-markdown">{@html data.live.current.moderationHtml}</div>
|
||||||
|
</section>{/if}
|
||||||
|
<details class="research-details">
|
||||||
|
<summary>Manuelle Recherche öffnen</summary>
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
<div class="live-markdown">{@html data.live.current.researchHtml}</div>
|
||||||
|
</details>
|
||||||
|
{#if data.live.current.transitionHtml}<section class="transition-card">
|
||||||
|
<span>Überleitung</span>
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
<div class="live-markdown">{@html data.live.current.transitionHtml}</div>
|
||||||
|
</section>{/if}
|
||||||
|
|
||||||
|
<div class="live-current-actions">
|
||||||
|
<form method="POST" action={liveAction('back')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
|
<button class="secondary-button" type="submit">Zurück</button>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action={liveAction('present')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="usageId" value={data.live.current.id} />
|
||||||
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
|
<button class="secondary-button" type="submit">
|
||||||
|
{data.live.presentationUsageId === data.live.current.id
|
||||||
|
? 'Erneut präsentieren'
|
||||||
|
: 'Präsentieren'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action={liveAction('skip')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
|
<button class="text-button" type="submit">Überspringen</button>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action={liveAction('complete')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
|
<button class="primary-button" type="submit">Erledigen und weiter</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</main>{:else}<main class="live-current live-empty">
|
||||||
|
<p class="eyebrow">Kein aktives Piece</p>
|
||||||
|
<h2>{data.live.totalCount ? 'Live-Stand bereit' : 'Noch kein Piece eingeplant'}</h2>
|
||||||
<p>
|
<p>
|
||||||
Die Recherche bleibt im echten Live-Modus standardmäßig geschlossen und bewahrt beim
|
{data.live.totalCount
|
||||||
Öffnen die Leseposition.
|
? 'Sendung starten oder einen abgeschlossenen Schritt zurückgehen.'
|
||||||
|
: 'In der Planung kann zuerst ein sendefertiges Piece hinzugefügt werden.'}
|
||||||
</p>
|
</p>
|
||||||
</details>
|
{#if data.live.completedCount}<form
|
||||||
<div class="transition-card">
|
method="POST"
|
||||||
<span>Überleitung</span>
|
action={liveAction('back')}
|
||||||
<p>{data.current.transition}</p>
|
use:enhance={enhanceCommand}
|
||||||
</div>
|
>
|
||||||
</section>
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
|
<button class="secondary-button" type="submit">Zum letzten Piece zurück</button>
|
||||||
|
</form>{/if}
|
||||||
|
</main>{/if}
|
||||||
|
|
||||||
<aside class="live-rail">
|
{#if showRail}<aside class="live-rail">
|
||||||
<div class="next-card">
|
<section class="next-card">
|
||||||
<span>Als Nächstes</span>
|
<span>Als Nächstes</span>
|
||||||
{#if data.next}
|
{#if data.live.next}
|
||||||
<h3>{data.next.title}</h3>
|
<h3>{data.live.next.title}</h3>
|
||||||
<p>{data.next.section} · {formatClock(data.next.durationSeconds)}</p>
|
<p>
|
||||||
{:else}
|
{data.live.next.sectionName}{#if showTimes}
|
||||||
<h3>Sendungsende</h3>
|
· {formatClock(data.live.next.durationSeconds)}{/if}
|
||||||
<p>Kein weiteres Stück eingeplant.</p>
|
</p>
|
||||||
{/if}
|
{:else}
|
||||||
</div>
|
<h3>Sendungsende</h3>
|
||||||
<div class="live-progress">
|
<p>Kein weiteres offenes Piece eingeplant.</p>
|
||||||
<header><span>Ablauf</span><strong>2 / 4</strong></header>
|
{/if}
|
||||||
<div class="progress-track"><span></span></div>
|
</section>
|
||||||
{#each data.show.sections as section, index (section.id)}
|
|
||||||
<div class:active={index === 1} class="rail-section">
|
<section class="live-progress">
|
||||||
<span>{String(index + 1).padStart(2, '0')}</span>
|
<header>
|
||||||
<div>
|
<span>Ablauf</span><strong>{data.live.completedCount} / {data.live.totalCount}</strong>
|
||||||
<strong>{section.name}</strong><small>{formatClock(section.durationSeconds)}</small>
|
</header>
|
||||||
|
<div class="progress-track"><span style={`width:${progress}%`}></span></div>
|
||||||
|
{#each data.live.sections as section, sectionIndex (section.id)}
|
||||||
|
<div class:active={section.id === data.live.current?.sectionId} class="rail-section">
|
||||||
|
<span>{String(sectionIndex + 1).padStart(2, '0')}</span>
|
||||||
|
<div>
|
||||||
|
<strong>{section.name}</strong>
|
||||||
|
{#if showTimes}<small>{formatDuration(section.durationSeconds)}</small>{/if}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
{#each section.usages as usage, usageIndex (usage.id)}
|
||||||
{/each}
|
<div class:current={usage.id === data.live.current?.id} class="live-run-item">
|
||||||
</div>
|
<div>
|
||||||
<div class="readonly-actions" aria-label="Spätere Live-Aktionen">
|
<strong>{usage.title}</strong><small>{usage.status}</small>
|
||||||
<span>Zurück</span><strong>In Etappe 5 steuerbar</strong><span>Erledigen</span>
|
</div>
|
||||||
</div>
|
<div class="live-run-actions">
|
||||||
</aside>
|
{#if usage.status === 'open'}
|
||||||
|
<form
|
||||||
|
method="POST"
|
||||||
|
action={liveAction('moveUsage')}
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="showRevision" value={data.live.show.revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<input type="hidden" name="sectionId" value={section.id} />
|
||||||
|
<input type="hidden" name="position" value={usageIndex - 1} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={usageIndex === 0 ||
|
||||||
|
section.usages[usageIndex - 1]?.status !== 'open'}
|
||||||
|
aria-label={`${usage.title} nach oben`}>↑</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
method="POST"
|
||||||
|
action={liveAction('moveUsage')}
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="showRevision" value={data.live.show.revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<input type="hidden" name="sectionId" value={section.id} />
|
||||||
|
<input type="hidden" name="position" value={usageIndex + 1} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={usageIndex === section.usages.length - 1 ||
|
||||||
|
section.usages[usageIndex + 1]?.status !== 'open'}
|
||||||
|
aria-label={`${usage.title} nach unten`}>↓</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
<form method="POST" action={liveAction('present')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<input type="hidden" name="revision" value={data.live.liveRevision} />
|
||||||
|
<input type="hidden" name="commandId" value={data.commandId} />
|
||||||
|
<button type="submit" aria-label={`${usage.title} präsentieren`}>↗</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{/each}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="live-reserve">
|
||||||
|
<header><span>Reserve</span><strong>{data.live.reserve.length}</strong></header>
|
||||||
|
{#each data.live.reserve as usage, reserveIndex (usage.id)}
|
||||||
|
<div class="live-reserve-item">
|
||||||
|
<div>
|
||||||
|
<strong>{usage.title}</strong>{#if showTimes}<small
|
||||||
|
>{formatClock(usage.durationSeconds)}</small
|
||||||
|
>{/if}
|
||||||
|
</div>
|
||||||
|
<div class="live-run-actions">
|
||||||
|
<form method="POST" action={liveAction('moveUsage')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="showRevision" value={data.live.show.revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<input type="hidden" name="sectionId" value="" />
|
||||||
|
<input type="hidden" name="position" value={reserveIndex - 1} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={reserveIndex === 0}
|
||||||
|
aria-label={`${usage.title} in Reserve nach oben`}>↑</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action={liveAction('moveUsage')} use:enhance={enhanceCommand}>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="showRevision" value={data.live.show.revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<input type="hidden" name="sectionId" value="" />
|
||||||
|
<input type="hidden" name="position" value={reserveIndex + 1} />
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={reserveIndex === data.live.reserve.length - 1}
|
||||||
|
aria-label={`${usage.title} in Reserve nach unten`}>↓</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
{#if data.live.current || data.live.sections[0]}<form
|
||||||
|
method="POST"
|
||||||
|
action={liveAction('moveUsage')}
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="showId" value={data.live.show.id} />
|
||||||
|
<input type="hidden" name="showRevision" value={data.live.show.revision} />
|
||||||
|
<input type="hidden" name="usageId" value={usage.id} />
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="sectionId"
|
||||||
|
value={data.live.current?.sectionId ?? data.live.sections[0]?.id}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name="position"
|
||||||
|
value={(data.live.current?.position ?? -1) + 1}
|
||||||
|
/>
|
||||||
|
<button class="text-button" type="submit">Als Nächstes</button>
|
||||||
|
</form>{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if !data.live.reserve.length}<p>Keine Pieces in Reserve.</p>{/if}
|
||||||
|
</section>
|
||||||
|
</aside>{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import {
|
||||||
|
authenticate,
|
||||||
|
createSession,
|
||||||
|
hasUsers,
|
||||||
|
reserveLoginAttempt,
|
||||||
|
validEmail
|
||||||
|
} from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals }) => {
|
||||||
|
if (!hasUsers()) redirect(303, '/setup');
|
||||||
|
if (locals.user) redirect(303, '/fundus');
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
default: async ({ request, cookies, getClientAddress }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
const email = String(data.get('email') || '').trim();
|
||||||
|
const password = String(data.get('password') || '');
|
||||||
|
const address = getClientAddress();
|
||||||
|
if (!validEmail(email) || !password || Buffer.byteLength(password, 'utf8') > 256) {
|
||||||
|
return fail(400, { email, error: 'E-Mail oder Passwort ist nicht korrekt.' });
|
||||||
|
}
|
||||||
|
if (!reserveLoginAttempt(email, address)) {
|
||||||
|
return fail(429, {
|
||||||
|
email,
|
||||||
|
error: 'Zu viele Anmeldeversuche. Bitte in 15 Minuten erneut versuchen.'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const user = await authenticate(email, password);
|
||||||
|
if (!user) return fail(400, { email, error: 'E-Mail oder Passwort ist nicht korrekt.' });
|
||||||
|
createSession(user.id, cookies);
|
||||||
|
redirect(303, '/fundus');
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>Anmelden | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<section class="auth-card">
|
||||||
|
<p class="eyebrow">Redaktionszugang</p>
|
||||||
|
<h1>Bei Sendewerk anmelden</h1>
|
||||||
|
<p>Für Barkeeper und Thekencrew. Eine öffentliche Registrierung gibt es nicht.</p>
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
<form class="auth-form" method="POST">
|
||||||
|
<label
|
||||||
|
>E-Mail<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
maxlength="254"
|
||||||
|
value={form?.email ?? ''}
|
||||||
|
autocomplete="email"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Passwort<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
maxlength="256"
|
||||||
|
autocomplete="current-password"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Anmelden</button>
|
||||||
|
</form>
|
||||||
|
<a class="auth-link" href={resolve('/passwort-vergessen')}>Passwort vergessen?</a>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { redirect } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { deleteSession } from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
export const POST: RequestHandler = ({ cookies }) => {
|
||||||
|
deleteSession(cookies);
|
||||||
|
redirect(303, '/login');
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { getMediaFile } from '#lib/server/content.js';
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ locals, params }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const media = await getMediaFile(params.id);
|
||||||
|
if (!media) error(404, 'Bild nicht gefunden');
|
||||||
|
return new Response(media.data, {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': media.mimeType,
|
||||||
|
'Content-Length': String(media.byteSize),
|
||||||
|
'Cache-Control': 'private, no-store',
|
||||||
|
'Content-Security-Policy': "default-src 'none'; sandbox",
|
||||||
|
'Cross-Origin-Resource-Policy': 'same-origin',
|
||||||
|
'X-Content-Type-Options': 'nosniff'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { fail } from '@sveltejs/kit';
|
||||||
|
import type { Actions } from './$types';
|
||||||
|
import { requestPasswordReset, reservePasswordResetRequest, validEmail } from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
default: async ({ request, getClientAddress }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
const email = String(data.get('email') || '').trim();
|
||||||
|
if (!validEmail(email))
|
||||||
|
return fail(400, { email, error: 'Bitte eine gültige E-Mail eingeben.' });
|
||||||
|
if (!reservePasswordResetRequest(email, getClientAddress())) {
|
||||||
|
return { sent: true };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await requestPasswordReset(email);
|
||||||
|
} catch {
|
||||||
|
// Die sichtbare Antwort bleibt identisch, damit der Mailzustand kein Konto verrät.
|
||||||
|
console.error('Eine Passwortreset-Nachricht konnte nicht bereitgestellt werden.');
|
||||||
|
}
|
||||||
|
return { sent: true };
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>Passwort vergessen | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<section class="auth-card">
|
||||||
|
<p class="eyebrow">Kontozugang</p>
|
||||||
|
<h1>Passwort zurücksetzen</h1>
|
||||||
|
<p>Wenn das Konto existiert, wird ein 24 Stunden gültiger, einmaliger Link bereitgestellt.</p>
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
{#if form?.sent}<div class="form-message success" role="status">
|
||||||
|
Anfrage verarbeitet. Bitte Postfach beziehungsweise lokale Outbox prüfen.
|
||||||
|
</div>{/if}
|
||||||
|
<form class="auth-form" method="POST">
|
||||||
|
<label
|
||||||
|
>E-Mail<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
maxlength="254"
|
||||||
|
value={form?.email ?? ''}
|
||||||
|
autocomplete="email"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Reset-Link anfordern</button>
|
||||||
|
</form>
|
||||||
|
<a class="auth-link" href={resolve('/login')}>Zurück zur Anmeldung</a>
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import {
|
||||||
|
deleteLinkToken,
|
||||||
|
passwordResetIsValid,
|
||||||
|
readLinkToken,
|
||||||
|
RESET_COOKIE,
|
||||||
|
resetPassword,
|
||||||
|
storeLinkToken,
|
||||||
|
validPassword
|
||||||
|
} from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ url, cookies }) => {
|
||||||
|
const queryToken = url.searchParams.get('token');
|
||||||
|
if (queryToken) {
|
||||||
|
if (queryToken.length <= 100) storeLinkToken(cookies, RESET_COOKIE, queryToken);
|
||||||
|
else deleteLinkToken(cookies, RESET_COOKIE);
|
||||||
|
redirect(303, '/passwort-zuruecksetzen');
|
||||||
|
}
|
||||||
|
return { valid: passwordResetIsValid(readLinkToken(cookies, RESET_COOKIE)) };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
default: async ({ request, cookies }) => {
|
||||||
|
const data = await request.formData();
|
||||||
|
const token = readLinkToken(cookies, RESET_COOKIE);
|
||||||
|
const password = String(data.get('password') || '');
|
||||||
|
if (!validPassword(password)) {
|
||||||
|
return fail(400, { error: 'Das neue Passwort muss mindestens 12 Zeichen lang sein.' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await resetPassword(token, password);
|
||||||
|
deleteLinkToken(cookies, RESET_COOKIE);
|
||||||
|
} catch {
|
||||||
|
return fail(400, { error: 'Der Link ist ungültig, abgelaufen oder bereits verwendet.' });
|
||||||
|
}
|
||||||
|
redirect(303, '/login?reset=erfolgreich');
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>Neues Passwort | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<section class="auth-card">
|
||||||
|
<p class="eyebrow">Kontozugang</p>
|
||||||
|
<h1>Neues Passwort setzen</h1>
|
||||||
|
{#if !data.valid && !form?.error}
|
||||||
|
<div class="form-message error" role="alert">
|
||||||
|
Der Link ist ungültig, abgelaufen oder bereits verwendet.
|
||||||
|
</div>
|
||||||
|
<a class="auth-link" href={resolve('/passwort-vergessen')}>Neuen Link anfordern</a>
|
||||||
|
{:else}
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
<form class="auth-form" method="POST">
|
||||||
|
<label
|
||||||
|
>Neues Passwort<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minlength="12"
|
||||||
|
maxlength="256"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Passwort speichern</button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
@@ -1,5 +1,74 @@
|
|||||||
import { getPieces, getShow } from '#lib/server/previews.js';
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { createShow, listShows, listShowTemplates } from '#lib/server/shows.js';
|
||||||
|
|
||||||
export function load() {
|
function berlinLocalToUtc(value: string): string | null {
|
||||||
return { pieces: getPieces(), show: getShow() };
|
if (!value) return null;
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value);
|
||||||
|
if (!match) throw new Error('INVALID_TIMESTAMP');
|
||||||
|
const parts = match.slice(1).map(Number);
|
||||||
|
const localMilliseconds = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4]);
|
||||||
|
let candidate = localMilliseconds;
|
||||||
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||||
|
const formatted = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
timeZone: 'Europe/Berlin',
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
hourCycle: 'h23'
|
||||||
|
}).formatToParts(new Date(candidate));
|
||||||
|
const read = (type: Intl.DateTimeFormatPartTypes) =>
|
||||||
|
Number(formatted.find((part) => part.type === type)?.value);
|
||||||
|
const represented = Date.UTC(
|
||||||
|
read('year'),
|
||||||
|
read('month') - 1,
|
||||||
|
read('day'),
|
||||||
|
read('hour'),
|
||||||
|
read('minute')
|
||||||
|
);
|
||||||
|
candidate += localMilliseconds - represented;
|
||||||
|
}
|
||||||
|
return new Date(candidate).toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
return { shows: listShows(), templates: listShowTemplates() };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
create: async ({ locals, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const title = String(data.get('title') || '');
|
||||||
|
const startsAt = String(data.get('startsAt') || '');
|
||||||
|
const templateId = String(data.get('templateId') || '') || null;
|
||||||
|
let id: string;
|
||||||
|
try {
|
||||||
|
id = createShow({ title, startsAtUtc: berlinLocalToUtc(startsAt), templateId }).id;
|
||||||
|
} catch (cause) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'INVALID_TITLE') {
|
||||||
|
return fail(400, { error: 'Bitte einen Titel eingeben.', title, startsAt, templateId });
|
||||||
|
}
|
||||||
|
if (code === 'INVALID_TIMESTAMP') {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Bitte einen gültigen Termin eingeben.',
|
||||||
|
title,
|
||||||
|
startsAt,
|
||||||
|
templateId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Die Sendung konnte nicht angelegt werden.',
|
||||||
|
title,
|
||||||
|
startsAt,
|
||||||
|
templateId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
redirect(303, `/sendungen/${id}`);
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -1,141 +1,104 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import PreviewNotice from '#lib/components/PreviewNotice.svelte';
|
|
||||||
import { formatClock, formatDuration } from '#lib/format.js';
|
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import type { PageData } from './$types';
|
import { formatDuration } from '#lib/format.js';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
let { data }: { data: PageData } = $props();
|
let { data, form }: PageProps = $props();
|
||||||
let mobilePane = $state<'fundus' | 'plan'>('plan');
|
|
||||||
let plannedCount = $derived(
|
function berlinDate(value: string | null) {
|
||||||
data.show.sections.reduce(
|
if (!value) return 'Termin offen';
|
||||||
(total, section) => total + section.usages.filter((usage) => !usage.isReserve).length,
|
return new Intl.DateTimeFormat('de-DE', {
|
||||||
0
|
timeZone: 'Europe/Berlin',
|
||||||
)
|
dateStyle: 'medium',
|
||||||
);
|
timeStyle: 'short'
|
||||||
|
}).format(new Date(value));
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head><title>Sendungen | Sendewerk</title></svelte:head>
|
<svelte:head><title>Sendungen | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
<div class="page-wrap builder-page">
|
<div class="page-wrap shows-page">
|
||||||
<header class="page-heading show-heading">
|
<header class="page-heading">
|
||||||
<div>
|
<div>
|
||||||
<p class="eyebrow">Nächste Sendung · {data.show.startsAtBerlin} Uhr</p>
|
<h1>Sendungen</h1>
|
||||||
<h1>{data.show.title}</h1>
|
<p class="page-intro">Streams aus Fundus-Pieces und freien Abschnitten zusammenstellen.</p>
|
||||||
</div>
|
|
||||||
<div class="show-summary">
|
|
||||||
<div><strong>{plannedCount}</strong><span>Stücke</span></div>
|
|
||||||
<div>
|
|
||||||
<strong>{formatDuration(data.show.totalDurationSeconds)}</strong><span>Planzeit</span>
|
|
||||||
</div>
|
|
||||||
<a class="live-link" href={resolve('/live')}>Live-Vorschau <span>↗</span></a>
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<PreviewNotice area="Sendungsbau" />
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
|
||||||
<div class="mobile-pane-switch" aria-label="Arbeitsbereich auswählen">
|
<section class="show-create-panel">
|
||||||
<button
|
<div>
|
||||||
class:active={mobilePane === 'fundus'}
|
<p class="eyebrow">Neuen Stream planen</p>
|
||||||
type="button"
|
<h2>Leer starten oder Ablauf übernehmen</h2>
|
||||||
onclick={() => (mobilePane = 'fundus')}>Fundus</button
|
</div>
|
||||||
>
|
<form method="POST" action="?/create" class="show-create-form">
|
||||||
<button class:active={mobilePane === 'plan'} type="button" onclick={() => (mobilePane = 'plan')}
|
<label
|
||||||
>Ablauf</button
|
>Titel<input
|
||||||
>
|
name="title"
|
||||||
</div>
|
required
|
||||||
|
maxlength="200"
|
||||||
|
value={form?.title ?? ''}
|
||||||
|
placeholder="Nächste heinzlive-Sendung"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Termin<input name="startsAt" type="datetime-local" value={form?.startsAt ?? ''} /></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Ausgangspunkt<select name="templateId" value={form?.templateId ?? ''}
|
||||||
|
><option value="">Leer starten</option
|
||||||
|
>{#each data.templates as template (template.id)}<option value={template.id}
|
||||||
|
>{template.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Sendung anlegen</button>
|
||||||
|
</form>
|
||||||
|
<div class="template-notes">
|
||||||
|
{#each data.templates as template (template.id)}<p>
|
||||||
|
<strong>{template.name}:</strong>
|
||||||
|
{template.description}
|
||||||
|
</p>{/each}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<div class="builder-workspace">
|
<section class="show-library" aria-labelledby="show-library-title">
|
||||||
<section
|
<header>
|
||||||
class="builder-pane source-pane"
|
<h2 id="show-library-title">Geplante Sendungen</h2>
|
||||||
class:mobile-hidden={mobilePane !== 'fundus'}
|
<span>{data.shows.length}</span>
|
||||||
aria-labelledby="source-title"
|
</header>
|
||||||
>
|
{#if data.shows.length}
|
||||||
<header class="pane-heading">
|
<div class="show-card-list">
|
||||||
<div>
|
{#each data.shows as show (show.id)}
|
||||||
<p class="eyebrow">Quelle</p>
|
<a class="show-card" href={resolve('/sendungen/[id]', { id: show.id })}>
|
||||||
<h2 id="source-title">Sendefertiger Fundus</h2>
|
|
||||||
</div>
|
|
||||||
<span>{data.pieces.filter((piece) => piece.status === 'ready').length}</span>
|
|
||||||
</header>
|
|
||||||
<label class="compact-search">
|
|
||||||
<span aria-hidden="true">⌕</span><span class="sr-only">Fundus durchsuchen</span>
|
|
||||||
<input
|
|
||||||
type="search"
|
|
||||||
placeholder="Fundus durchsuchen"
|
|
||||||
disabled
|
|
||||||
title="Die vollständige Suche folgt in Etappe 3"
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
<div class="source-list">
|
|
||||||
{#each data.pieces.filter((piece) => piece.status === 'ready') as piece (piece.id)}
|
|
||||||
<article class="source-card" style={`--category: ${piece.categoryColor}`}>
|
|
||||||
<div>
|
<div>
|
||||||
<span class="category-label"><i></i>{piece.category}</span><span
|
<span class={`show-state ${show.status}`}
|
||||||
>{formatClock(piece.durationSeconds)}</span
|
>{show.status === 'ready'
|
||||||
|
? 'Bereit'
|
||||||
|
: show.status === 'draft'
|
||||||
|
? 'Entwurf'
|
||||||
|
: show.status === 'live'
|
||||||
|
? 'Live'
|
||||||
|
: 'Abgeschlossen'}</span
|
||||||
>
|
>
|
||||||
|
<h3>{show.title}</h3>
|
||||||
|
<p>{berlinDate(show.startsAtUtc)} Uhr</p>
|
||||||
</div>
|
</div>
|
||||||
<h3>{piece.title}</h3>
|
<div class="show-card-facts">
|
||||||
<p>{piece.format} · {piece.topics.join(', ')}</p>
|
<span><strong>{show.sectionCount}</strong> Abschnitte</span><span
|
||||||
</article>
|
><strong>{formatDuration(show.totalDurationSeconds)}</strong> Planzeit</span
|
||||||
|
><b aria-hidden="true">→</b>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
{/each}
|
{/each}
|
||||||
</div>
|
</div>
|
||||||
<div class="reserve-box">
|
{:else}
|
||||||
<div>
|
<div class="empty-state">
|
||||||
<span aria-hidden="true">◇</span>
|
<span aria-hidden="true">+</span>
|
||||||
<div><strong>Reservebank</strong><small>1 Stück vorbereitet</small></div>
|
<h2>Noch keine Sendung</h2>
|
||||||
</div>
|
<p>Oben kann der erste Stream geplant werden.</p>
|
||||||
<p>„Pixelart, die nicht nostalgisch sein will“ wartet als Ersatz.</p>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
{/if}
|
||||||
|
</section>
|
||||||
<section
|
|
||||||
class="builder-pane run-pane"
|
|
||||||
class:mobile-hidden={mobilePane !== 'plan'}
|
|
||||||
aria-labelledby="run-title"
|
|
||||||
>
|
|
||||||
<header class="pane-heading">
|
|
||||||
<div>
|
|
||||||
<p class="eyebrow">Sendungsplan</p>
|
|
||||||
<h2 id="run-title">Ablauf</h2>
|
|
||||||
</div>
|
|
||||||
<span>{formatDuration(data.show.totalDurationSeconds)}</span>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<div class="run-list">
|
|
||||||
{#each data.show.sections as section, index (section.id)}
|
|
||||||
<article class="run-section" style={`--category: ${section.categoryColor}`}>
|
|
||||||
<header>
|
|
||||||
<div class="section-number">{String(index + 1).padStart(2, '0')}</div>
|
|
||||||
<div>
|
|
||||||
<span class="category-label"><i></i>{section.category}</span>
|
|
||||||
<h3>{section.name}</h3>
|
|
||||||
</div>
|
|
||||||
<strong>{formatClock(section.durationSeconds)}</strong>
|
|
||||||
</header>
|
|
||||||
{#if section.usages.filter((usage) => !usage.isReserve).length > 0}
|
|
||||||
<div class="usage-list">
|
|
||||||
{#each section.usages.filter((usage) => !usage.isReserve) as usage (usage.id)}
|
|
||||||
<div class="usage-row">
|
|
||||||
<span class="drag-hint" aria-hidden="true">⠿</span>
|
|
||||||
<div>
|
|
||||||
<strong>{usage.title}</strong><small
|
|
||||||
>{formatClock(usage.durationSeconds)} · Eigene Sendungskopie</small
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<span class:current={usage.status === 'current'} class="usage-status"
|
|
||||||
>{usage.status === 'current' ? 'Aktuell' : 'Offen'}</span
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
{:else}
|
|
||||||
<div class="section-placeholder">
|
|
||||||
Eigenständiger Spieleblock · keine Piece-Kopie nötig
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</article>
|
|
||||||
{/each}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
import { error, fail } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import { requireUser } from '#lib/server/auth.js';
|
||||||
|
import { getTaxonomy, listPieces } from '#lib/server/content.js';
|
||||||
|
import {
|
||||||
|
addPieceUsage,
|
||||||
|
addShowSection,
|
||||||
|
duplicatePieceUsage,
|
||||||
|
getShow,
|
||||||
|
getPieceUsageContexts,
|
||||||
|
movePieceUsage,
|
||||||
|
moveShowSection,
|
||||||
|
refreshPieceUsageFromOriginal,
|
||||||
|
removePieceUsage,
|
||||||
|
removeShowSection,
|
||||||
|
saveShowMetadata,
|
||||||
|
updatePieceUsage,
|
||||||
|
updateShowSection,
|
||||||
|
type EditableShowStatus,
|
||||||
|
type PieceUsageUpdate
|
||||||
|
} from '#lib/server/shows.js';
|
||||||
|
|
||||||
|
function text(data: FormData, name: string) {
|
||||||
|
return String(data.get(name) || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
function nullableDuration(data: FormData) {
|
||||||
|
const value = text(data, 'explicitDurationSeconds').trim();
|
||||||
|
return value === '' ? null : Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function pieceDurationInSeconds(data: FormData) {
|
||||||
|
return Math.round(Number(data.get('durationMinutes')) * 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
function berlinLocalToUtc(value: string): string | null {
|
||||||
|
if (!value) return null;
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value);
|
||||||
|
if (!match) throw new Error('INVALID_TIMESTAMP');
|
||||||
|
const parts = match.slice(1).map(Number);
|
||||||
|
const localMilliseconds = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4]);
|
||||||
|
let candidate = localMilliseconds;
|
||||||
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||||
|
const formatted = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
timeZone: 'Europe/Berlin',
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
hourCycle: 'h23'
|
||||||
|
}).formatToParts(new Date(candidate));
|
||||||
|
const read = (type: Intl.DateTimeFormatPartTypes) =>
|
||||||
|
Number(formatted.find((part) => part.type === type)?.value);
|
||||||
|
candidate +=
|
||||||
|
localMilliseconds -
|
||||||
|
Date.UTC(read('year'), read('month') - 1, read('day'), read('hour'), read('minute'));
|
||||||
|
}
|
||||||
|
return new Date(candidate).toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function berlinInput(value: string | null) {
|
||||||
|
if (!value) return '';
|
||||||
|
const parts = new Intl.DateTimeFormat('en-CA', {
|
||||||
|
timeZone: 'Europe/Berlin',
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
hourCycle: 'h23'
|
||||||
|
}).formatToParts(new Date(value));
|
||||||
|
const read = (type: Intl.DateTimeFormatPartTypes) =>
|
||||||
|
parts.find((part) => part.type === type)?.value ?? '';
|
||||||
|
return `${read('year')}-${read('month')}-${read('day')}T${read('hour')}:${read('minute')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function actionError(cause: unknown) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'CONFLICT')
|
||||||
|
return {
|
||||||
|
status: 409,
|
||||||
|
error: 'Die Sendung wurde inzwischen geändert. Bitte neu laden.',
|
||||||
|
conflict: true
|
||||||
|
};
|
||||||
|
if (code === 'SHOW_COMPLETED')
|
||||||
|
return { status: 409, error: 'Abgeschlossene Sendungen können nicht bearbeitet werden.' };
|
||||||
|
if (code === 'PIECE_NOT_READY')
|
||||||
|
return { status: 400, error: 'Nur sendefertige Pieces können eingeplant werden.' };
|
||||||
|
if (code === 'ORIGINAL_NOT_FOUND')
|
||||||
|
return { status: 409, error: 'Das zugehörige Fundus-Piece ist nicht mehr verfügbar.' };
|
||||||
|
if (code === 'NOT_FOUND') return { status: 404, error: 'Der Eintrag wurde nicht gefunden.' };
|
||||||
|
if (code === 'INVALID_DURATION')
|
||||||
|
return { status: 400, error: 'Piece-Dauern müssen zwischen 0 und 1.440 Minuten liegen.' };
|
||||||
|
if (code.startsWith('INVALID_'))
|
||||||
|
return { status: 400, error: 'Mindestens ein Feld ist ungültig oder zu lang.' };
|
||||||
|
return { status: 500, error: 'Die Änderung konnte nicht gespeichert werden.' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function attempt(intent: string, operation: () => unknown) {
|
||||||
|
try {
|
||||||
|
return { intent, success: 'Änderung gespeichert.', result: operation() };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(actionError(cause).status, { intent, ...actionError(cause) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const load: PageServerLoad = ({ locals, params, url }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const show = getShow(params.id);
|
||||||
|
if (!show) error(404, 'Sendung nicht gefunden');
|
||||||
|
const pieces = listPieces({
|
||||||
|
statuses: ['ready'],
|
||||||
|
query: url.searchParams.get('q') ?? '',
|
||||||
|
categoryId: url.searchParams.get('category') ?? ''
|
||||||
|
});
|
||||||
|
const usageContexts = getPieceUsageContexts(
|
||||||
|
pieces.map((piece) => piece.id),
|
||||||
|
show.id
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
show,
|
||||||
|
startsAtLocal: berlinInput(show.startsAtUtc),
|
||||||
|
pieces: pieces.map((piece) => ({ ...piece, ...usageContexts[piece.id] })),
|
||||||
|
taxonomy: getTaxonomy(),
|
||||||
|
filters: {
|
||||||
|
query: url.searchParams.get('q') ?? '',
|
||||||
|
categoryId: url.searchParams.get('category') ?? '',
|
||||||
|
includeUsed: url.searchParams.get('includeUsed') === '1',
|
||||||
|
includePlanned: url.searchParams.get('includePlanned') === '1'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
saveMetadata: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('saveMetadata', () =>
|
||||||
|
saveShowMetadata(params.id, Number(data.get('revision')), {
|
||||||
|
title: text(data, 'title'),
|
||||||
|
startsAtUtc: berlinLocalToUtc(text(data, 'startsAt')),
|
||||||
|
twitchTitle: text(data, 'twitchTitle'),
|
||||||
|
announcementText: text(data, 'announcementText'),
|
||||||
|
status: text(data, 'status') as EditableShowStatus
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
addSection: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('addSection', () =>
|
||||||
|
addShowSection(params.id, Number(data.get('revision')), {
|
||||||
|
name: text(data, 'name'),
|
||||||
|
categoryId: text(data, 'categoryId') || null,
|
||||||
|
explicitDurationSeconds: nullableDuration(data)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
updateSection: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('updateSection', () =>
|
||||||
|
updateShowSection(params.id, text(data, 'sectionId'), Number(data.get('revision')), {
|
||||||
|
name: text(data, 'name'),
|
||||||
|
categoryId: text(data, 'categoryId') || null,
|
||||||
|
explicitDurationSeconds: nullableDuration(data)
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
removeSection: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('removeSection', () =>
|
||||||
|
removeShowSection(params.id, text(data, 'sectionId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
moveSection: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('moveSection', () =>
|
||||||
|
moveShowSection(
|
||||||
|
params.id,
|
||||||
|
text(data, 'sectionId'),
|
||||||
|
Number(data.get('position')),
|
||||||
|
Number(data.get('revision'))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
addUsage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('addUsage', () =>
|
||||||
|
addPieceUsage(params.id, Number(data.get('revision')), {
|
||||||
|
pieceId: text(data, 'pieceId'),
|
||||||
|
sectionId: text(data, 'sectionId') || null
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
updateUsage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('updateUsage', () =>
|
||||||
|
updatePieceUsage(params.id, text(data, 'usageId'), Number(data.get('revision')), {
|
||||||
|
title: text(data, 'title'),
|
||||||
|
durationSeconds: pieceDurationInSeconds(data),
|
||||||
|
ownNotes: text(data, 'ownNotes'),
|
||||||
|
intro: text(data, 'intro'),
|
||||||
|
research: text(data, 'research'),
|
||||||
|
moderation: text(data, 'moderation'),
|
||||||
|
transition: text(data, 'transition'),
|
||||||
|
presentation: text(data, 'presentation'),
|
||||||
|
presentationMode: text(data, 'presentationMode') as PieceUsageUpdate['presentationMode'],
|
||||||
|
presentationSourceLabel: text(data, 'presentationSourceLabel'),
|
||||||
|
presentationSourceUrl: text(data, 'presentationSourceUrl'),
|
||||||
|
presentationSourceTimecodeSeconds: text(data, 'presentationSourceTimecodeSeconds')
|
||||||
|
? Number(data.get('presentationSourceTimecodeSeconds'))
|
||||||
|
: null,
|
||||||
|
presentationTitle: text(data, 'presentationTitle'),
|
||||||
|
presentationDescription: text(data, 'presentationDescription'),
|
||||||
|
presentationImageUrl: text(data, 'presentationImageUrl'),
|
||||||
|
presentationSiteName: text(data, 'presentationSiteName')
|
||||||
|
})
|
||||||
|
);
|
||||||
|
},
|
||||||
|
duplicateUsage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('duplicateUsage', () =>
|
||||||
|
duplicatePieceUsage(params.id, text(data, 'usageId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
refreshUsage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('refreshUsage', () =>
|
||||||
|
refreshPieceUsageFromOriginal(params.id, text(data, 'usageId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
removeUsage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('removeUsage', () =>
|
||||||
|
removePieceUsage(params.id, text(data, 'usageId'), Number(data.get('revision')))
|
||||||
|
);
|
||||||
|
},
|
||||||
|
moveUsage: async ({ locals, params, request }) => {
|
||||||
|
requireUser(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
return attempt('moveUsage', () =>
|
||||||
|
movePieceUsage(params.id, text(data, 'usageId'), Number(data.get('revision')), {
|
||||||
|
sectionId: text(data, 'sectionId') || null,
|
||||||
|
position: Number(data.get('position'))
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,850 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { enhance, type SubmitFunction } from '$app/forms';
|
||||||
|
import { replaceState } from '$app/navigation';
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import { page } from '$app/state';
|
||||||
|
import { flip } from 'svelte/animate';
|
||||||
|
import { onMount, untrack } from 'svelte';
|
||||||
|
import PieceUsageHistory from '#lib/components/PieceUsageHistory.svelte';
|
||||||
|
import UsageEditorDialog from '#lib/components/UsageEditorDialog.svelte';
|
||||||
|
import { formatClock, formatDuration } from '#lib/format.js';
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
let mobilePane = $state<'fundus' | 'plan'>('plan');
|
||||||
|
let dragged = $state<{ kind: 'piece' | 'section' | 'usage'; id: string } | null>(null);
|
||||||
|
let dropPreview = $state<
|
||||||
|
| { kind: 'section'; position: number }
|
||||||
|
| { kind: 'usage'; sectionId: string | null; position: number }
|
||||||
|
| null
|
||||||
|
>(null);
|
||||||
|
let dropTarget = $state<string | null>(null);
|
||||||
|
let moveSectionForm: HTMLFormElement;
|
||||||
|
let moveUsageForm: HTMLFormElement;
|
||||||
|
let addUsageForm: HTMLFormElement;
|
||||||
|
let draggedSectionId = $state('');
|
||||||
|
let draggedUsageId = $state('');
|
||||||
|
let draggedPieceId = $state('');
|
||||||
|
let dropSectionId = $state('');
|
||||||
|
let dropPosition = $state(0);
|
||||||
|
let copyMessage = $state('');
|
||||||
|
let showUsedPieces = $state(untrack(() => data.filters.includeUsed));
|
||||||
|
let showPlannedPieces = $state(untrack(() => data.filters.includePlanned));
|
||||||
|
let visiblePieces = $derived(
|
||||||
|
data.pieces.filter(
|
||||||
|
(piece) =>
|
||||||
|
(showUsedPieces || piece.sentHistory.length === 0) &&
|
||||||
|
(showPlannedPieces || !piece.isPlannedInCurrentShow)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
let plannedCount = $derived(
|
||||||
|
data.show.sections.reduce((total, section) => total + section.usages.length, 0)
|
||||||
|
);
|
||||||
|
onMount(() => {
|
||||||
|
const syncFiltersFromHistory = () => {
|
||||||
|
const search = new URL(window.location.href).searchParams;
|
||||||
|
showUsedPieces = search.get('includeUsed') === '1';
|
||||||
|
showPlannedPieces = search.get('includePlanned') === '1';
|
||||||
|
};
|
||||||
|
window.addEventListener('popstate', syncFiltersFromHistory);
|
||||||
|
return () => window.removeEventListener('popstate', syncFiltersFromHistory);
|
||||||
|
});
|
||||||
|
|
||||||
|
function berlinDate(value: string | null) {
|
||||||
|
if (!value) return 'Termin offen';
|
||||||
|
return new Intl.DateTimeFormat('de-DE', {
|
||||||
|
timeZone: 'Europe/Berlin',
|
||||||
|
dateStyle: 'full',
|
||||||
|
timeStyle: 'short'
|
||||||
|
}).format(new Date(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setSourceFilter(name: 'includeUsed' | 'includePlanned', checked: boolean) {
|
||||||
|
if (name === 'includeUsed') showUsedPieces = checked;
|
||||||
|
else showPlannedPieces = checked;
|
||||||
|
const url = new URL(page.url.href);
|
||||||
|
if (checked) url.searchParams.set(name, '1');
|
||||||
|
else url.searchParams.delete(name);
|
||||||
|
// This URL is cloned from the current page; only same-route filter parameters change.
|
||||||
|
// eslint-disable-next-line svelte/no-navigation-without-resolve
|
||||||
|
replaceState(url, page.state);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startDrag(kind: 'piece' | 'section' | 'usage', id: string, event: DragEvent) {
|
||||||
|
dragged = { kind, id };
|
||||||
|
event.dataTransfer?.setData('text/plain', id);
|
||||||
|
if (event.dataTransfer) event.dataTransfer.effectAllowed = kind === 'piece' ? 'copy' : 'move';
|
||||||
|
}
|
||||||
|
|
||||||
|
function finishDrag() {
|
||||||
|
dragged = null;
|
||||||
|
dropPreview = null;
|
||||||
|
dropTarget = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function draggedTitle() {
|
||||||
|
if (!dragged) return '';
|
||||||
|
const draggedId = dragged.id;
|
||||||
|
if (dragged.kind === 'piece') {
|
||||||
|
return data.pieces.find((piece) => piece.id === draggedId)?.title ?? 'Piece';
|
||||||
|
}
|
||||||
|
if (dragged.kind === 'section') {
|
||||||
|
return data.show.sections.find((section) => section.id === draggedId)?.name ?? 'Abschnitt';
|
||||||
|
}
|
||||||
|
for (const section of data.show.sections) {
|
||||||
|
const usage = section.usages.find((item) => item.id === draggedId);
|
||||||
|
if (usage) return usage.title;
|
||||||
|
}
|
||||||
|
return data.show.reserve.find((usage) => usage.id === draggedId)?.title ?? 'Piece';
|
||||||
|
}
|
||||||
|
|
||||||
|
function positionAtPointer(event: DragEvent, position: number) {
|
||||||
|
const target = event.currentTarget as HTMLElement;
|
||||||
|
const bounds = target.getBoundingClientRect();
|
||||||
|
return event.clientY < bounds.top + bounds.height / 2 ? position : position + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function previewSection(event: DragEvent, position: number) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (dragged?.kind !== 'section') return;
|
||||||
|
dropPreview = { kind: 'section', position: positionAtPointer(event, position) };
|
||||||
|
dropTarget = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function previewUsage(
|
||||||
|
event: DragEvent,
|
||||||
|
sectionId: string | null,
|
||||||
|
position: number,
|
||||||
|
atPointer = true
|
||||||
|
) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!dragged || dragged.kind === 'section') return;
|
||||||
|
event.stopPropagation();
|
||||||
|
dropPreview = {
|
||||||
|
kind: 'usage',
|
||||||
|
sectionId,
|
||||||
|
position: atPointer ? positionAtPointer(event, position) : position
|
||||||
|
};
|
||||||
|
dropTarget = sectionId ?? 'reserve';
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropAtPreview() {
|
||||||
|
if (!dropPreview) return;
|
||||||
|
if (dropPreview.kind === 'section') dropSection(dropPreview.position);
|
||||||
|
else dropUsage(dropPreview.sectionId, dropPreview.position);
|
||||||
|
}
|
||||||
|
|
||||||
|
function showsUsagePreview(sectionId: string | null, position?: number) {
|
||||||
|
return (
|
||||||
|
dropPreview?.kind === 'usage' &&
|
||||||
|
dropPreview.sectionId === sectionId &&
|
||||||
|
(position === undefined || dropPreview.position === position)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropSection(position: number) {
|
||||||
|
if (!dragged || dragged.kind !== 'section') return;
|
||||||
|
draggedSectionId = dragged.id;
|
||||||
|
dropPosition = position;
|
||||||
|
finishDrag();
|
||||||
|
setTimeout(() => moveSectionForm.requestSubmit());
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropUsage(sectionId: string | null, position: number) {
|
||||||
|
if (!dragged || dragged.kind === 'section') return;
|
||||||
|
dropSectionId = sectionId ?? '';
|
||||||
|
dropPosition = position;
|
||||||
|
if (dragged.kind === 'piece') {
|
||||||
|
draggedPieceId = dragged.id;
|
||||||
|
finishDrag();
|
||||||
|
setTimeout(() => addUsageForm.requestSubmit());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
draggedUsageId = dragged.id;
|
||||||
|
finishDrag();
|
||||||
|
setTimeout(() => moveUsageForm.requestSubmit());
|
||||||
|
}
|
||||||
|
|
||||||
|
const enhanceCommand: SubmitFunction = ({ formElement, submitter }) => {
|
||||||
|
const affected = formElement.closest<HTMLElement>(
|
||||||
|
'.run-section, .editable-reserve, .builder-source-card, .show-settings, .add-section-form'
|
||||||
|
);
|
||||||
|
affected?.classList.add('is-updating');
|
||||||
|
if (submitter instanceof HTMLButtonElement) submitter.disabled = true;
|
||||||
|
return async ({ result, update }) => {
|
||||||
|
if (result.type === 'success') formElement.closest<HTMLDialogElement>('dialog')?.close();
|
||||||
|
await update({ reset: result.type === 'success', invalidateAll: true });
|
||||||
|
affected?.classList.remove('is-updating');
|
||||||
|
if (submitter instanceof HTMLButtonElement) submitter.disabled = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
async function copyText(label: string, value: string) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
copyMessage = `${label} kopiert.`;
|
||||||
|
} catch {
|
||||||
|
copyMessage = 'Kopieren wurde vom Browser blockiert.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>{data.show.title} | Sendungen | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<div class="page-wrap builder-page">
|
||||||
|
<header class="page-heading show-heading">
|
||||||
|
<div class="show-heading-copy">
|
||||||
|
<a class="back-link" href={resolve('/sendungen')}>← Sendungen</a>
|
||||||
|
<h1>{data.show.title}</h1>
|
||||||
|
<p class="show-date">
|
||||||
|
{data.show.startsAtUtc ? `${berlinDate(data.show.startsAtUtc)} Uhr` : 'Termin offen'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="show-summary">
|
||||||
|
<div><strong>{plannedCount}</strong><span>Pieces</span></div>
|
||||||
|
<div>
|
||||||
|
<strong>{formatDuration(data.show.totalDurationSeconds)}</strong><span>Planzeit</span>
|
||||||
|
</div>
|
||||||
|
<a class="live-link" href={resolve(`/live?show=${encodeURIComponent(data.show.id)}`)}
|
||||||
|
>Live-Steuerung <span>↗</span></a
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
{#if form?.success}<div class="form-message success" role="status">{form.success}</div>{/if}
|
||||||
|
<div class="sr-only" role="status" aria-live="polite">{copyMessage}</div>
|
||||||
|
|
||||||
|
<details class="show-settings">
|
||||||
|
<summary>Sendungsdaten und Twitch-Texte</summary>
|
||||||
|
<form
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/saveMetadata"
|
||||||
|
class="show-settings-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} />
|
||||||
|
<label class="wide-field"
|
||||||
|
>Interner Titel<input
|
||||||
|
name="title"
|
||||||
|
required
|
||||||
|
maxlength="200"
|
||||||
|
value={data.show.title}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Termin<input name="startsAt" type="datetime-local" value={data.startsAtLocal} /><small
|
||||||
|
>Die Anzeige erfolgt immer in Europe/Berlin.</small
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Status<select name="status" value={data.show.status}
|
||||||
|
><option value="draft">Entwurf</option><option value="ready">Bereit</option><option
|
||||||
|
value="live">Live</option
|
||||||
|
></select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label class="wide-field"
|
||||||
|
>Twitch-Titel<span class="copy-field"
|
||||||
|
><input name="twitchTitle" maxlength="200" value={data.show.twitchTitle} /><button
|
||||||
|
type="button"
|
||||||
|
onclick={() => copyText('Twitch-Titel', data.show.twitchTitle)}>Kopieren</button
|
||||||
|
></span
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<label class="wide-field"
|
||||||
|
>Ankündigung<span class="copy-field"
|
||||||
|
><textarea name="announcementText" maxlength="20000" rows="4"
|
||||||
|
>{data.show.announcementText}</textarea
|
||||||
|
><button type="button" onclick={() => copyText('Ankündigung', data.show.announcementText)}
|
||||||
|
>Kopieren</button
|
||||||
|
></span
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<div class="wide-field settings-submit">
|
||||||
|
<span>{copyMessage}</span><button class="primary-button" type="submit"
|
||||||
|
>Sendungsdaten speichern</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<div class="mobile-pane-switch" aria-label="Arbeitsbereich auswählen">
|
||||||
|
<button
|
||||||
|
class:active={mobilePane === 'fundus'}
|
||||||
|
aria-pressed={mobilePane === 'fundus'}
|
||||||
|
type="button"
|
||||||
|
onclick={() => (mobilePane = 'fundus')}>Fundus</button
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
class:active={mobilePane === 'plan'}
|
||||||
|
aria-pressed={mobilePane === 'plan'}
|
||||||
|
type="button"
|
||||||
|
onclick={() => (mobilePane = 'plan')}>Ablauf</button
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="builder-workspace">
|
||||||
|
<section
|
||||||
|
class="builder-pane source-pane"
|
||||||
|
class:mobile-hidden={mobilePane !== 'fundus'}
|
||||||
|
aria-labelledby="source-title"
|
||||||
|
>
|
||||||
|
<header class="pane-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Quelle</p>
|
||||||
|
<h2 id="source-title">Sendefertiger Fundus</h2>
|
||||||
|
</div>
|
||||||
|
<span>{visiblePieces.length}</span>
|
||||||
|
</header>
|
||||||
|
<form id="builder-filters" method="GET" class="builder-filter">
|
||||||
|
<label
|
||||||
|
><span class="sr-only">Fundus durchsuchen</span><input
|
||||||
|
type="search"
|
||||||
|
name="q"
|
||||||
|
value={data.filters.query}
|
||||||
|
placeholder="Fundus durchsuchen"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
><span class="sr-only">Abschnitt filtern</span><select name="category"
|
||||||
|
><option value="">Alle Abschnitte</option
|
||||||
|
>{#each data.taxonomy.categories as category (category.id)}<option
|
||||||
|
value={category.id}
|
||||||
|
selected={data.filters.categoryId === category.id}>{category.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<button class="text-button" type="submit">Filtern</button>
|
||||||
|
</form>
|
||||||
|
<div class="builder-filter-options" aria-label="Fundusauswahl erweitern">
|
||||||
|
<label class="filter-checkbox">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name="includeUsed"
|
||||||
|
value="1"
|
||||||
|
form="builder-filters"
|
||||||
|
checked={showUsedPieces}
|
||||||
|
onchange={(event) => setSourceFilter('includeUsed', event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
<span>Auch verwendete Inhalte zeigen</span>
|
||||||
|
</label>
|
||||||
|
<label class="filter-checkbox">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
name="includePlanned"
|
||||||
|
value="1"
|
||||||
|
form="builder-filters"
|
||||||
|
checked={showPlannedPieces}
|
||||||
|
onchange={(event) => setSourceFilter('includePlanned', event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
<span>Auch eingeplante Inhalte zeigen</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div class="builder-source-list">
|
||||||
|
{#each visiblePieces as piece (piece.id)}
|
||||||
|
<article
|
||||||
|
class="builder-source-card"
|
||||||
|
class:is-dragging={dragged?.kind === 'piece' && dragged.id === piece.id}
|
||||||
|
style={`--category:${piece.categories[0]?.color ?? '#8b8f98'}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="source-drag-copy"
|
||||||
|
role="group"
|
||||||
|
aria-label={`${piece.title} in den Ablauf ziehen`}
|
||||||
|
draggable="true"
|
||||||
|
ondragstart={(event) => startDrag('piece', piece.id, event)}
|
||||||
|
ondragend={finishDrag}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<span class="category-label"
|
||||||
|
><i></i>{piece.categories.map((item) => item.name).join(', ') || 'Offen'}</span
|
||||||
|
><span>{formatClock(piece.durationSeconds)}</span>
|
||||||
|
</div>
|
||||||
|
<h3>{piece.title}</h3>
|
||||||
|
<p>
|
||||||
|
{piece.format} · {piece.topics.map((item) => item.name).join(', ') || 'Ohne Thema'}
|
||||||
|
</p>
|
||||||
|
{#if piece.isPlannedInCurrentShow}<span class="planned-label">Eingeplant</span>{/if}
|
||||||
|
<PieceUsageHistory history={piece.sentHistory} />
|
||||||
|
<small class="drag-hint">Ziehen oder Ziel auswählen</small>
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/addUsage"
|
||||||
|
class="source-add-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="pieceId"
|
||||||
|
value={piece.id}
|
||||||
|
/>
|
||||||
|
<label
|
||||||
|
><span class="sr-only">Ziel für {piece.title}</span><select
|
||||||
|
name="sectionId"
|
||||||
|
aria-label={`Ziel für ${piece.title}`}
|
||||||
|
><option value="">Reservebank</option
|
||||||
|
>{#each data.show.sections as section (section.id)}<option value={section.id}
|
||||||
|
>{section.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<button class="secondary-button" type="submit">Hinzufügen</button>
|
||||||
|
</form>
|
||||||
|
</article>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{#if !visiblePieces.length}<div class="empty-state">
|
||||||
|
<span aria-hidden="true">⌕</span>
|
||||||
|
<h2>Keine verfügbaren Pieces</h2>
|
||||||
|
<p>
|
||||||
|
Suchfilter ändern, ausgeblendete Inhalte einblenden oder Pieces im Fundus sendefertig
|
||||||
|
markieren.
|
||||||
|
</p>
|
||||||
|
</div>{/if}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section
|
||||||
|
class="builder-pane run-pane"
|
||||||
|
class:mobile-hidden={mobilePane !== 'plan'}
|
||||||
|
aria-labelledby="run-title"
|
||||||
|
>
|
||||||
|
<header class="pane-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Sendungsplan</p>
|
||||||
|
<h2 id="run-title">Ablauf</h2>
|
||||||
|
</div>
|
||||||
|
<span>{formatDuration(data.show.totalDurationSeconds)}</span>
|
||||||
|
</header>
|
||||||
|
<div class="run-list">
|
||||||
|
{#each data.show.sections as section, index (section.id)}
|
||||||
|
<div
|
||||||
|
class="section-drag-slot"
|
||||||
|
role="presentation"
|
||||||
|
ondragover={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}}
|
||||||
|
ondrop={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
dropAtPreview();
|
||||||
|
}}
|
||||||
|
animate:flip={{ duration: 180 }}
|
||||||
|
>
|
||||||
|
{#if dropPreview?.kind === 'section' && dropPreview.position === index}
|
||||||
|
<div class="drag-insert-preview section-insert-preview" data-drop-preview="section">
|
||||||
|
<span>Hier einfügen</span><strong>{draggedTitle()}</strong>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<article
|
||||||
|
class="run-section editable-run-section"
|
||||||
|
class:is-dragging={dragged?.kind === 'section' && dragged.id === section.id}
|
||||||
|
class:drop-ready={dropTarget === section.id}
|
||||||
|
style={`--category:${section.categoryColor ?? '#8b8f98'}`}
|
||||||
|
ondragover={(event) => {
|
||||||
|
if (dragged?.kind === 'section') previewSection(event, index);
|
||||||
|
else previewUsage(event, section.id, section.usages.length, false);
|
||||||
|
}}
|
||||||
|
ondrop={dropAtPreview}
|
||||||
|
>
|
||||||
|
<header
|
||||||
|
class="section-drag-handle"
|
||||||
|
role="group"
|
||||||
|
aria-label={`${section.name} verschieben`}
|
||||||
|
draggable="true"
|
||||||
|
ondragstart={(event) => startDrag('section', section.id, event)}
|
||||||
|
ondragend={finishDrag}
|
||||||
|
>
|
||||||
|
<div class="section-number">{String(index + 1).padStart(2, '0')}</div>
|
||||||
|
<div>
|
||||||
|
<span class="category-label"><i></i>{section.category ?? 'Offen'}</span>
|
||||||
|
<h3>{section.name}</h3>
|
||||||
|
</div>
|
||||||
|
<strong>{formatClock(section.durationSeconds)}</strong>
|
||||||
|
</header>
|
||||||
|
<div class="row-actions" aria-label={`Abschnitt ${section.name} verschieben`}>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/moveSection">
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="sectionId"
|
||||||
|
value={section.id}
|
||||||
|
/><input type="hidden" name="position" value={index - 1} /><button
|
||||||
|
type="submit"
|
||||||
|
disabled={index === 0}
|
||||||
|
aria-label={`${section.name} nach oben`}>↑</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/moveSection">
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="sectionId"
|
||||||
|
value={section.id}
|
||||||
|
/><input type="hidden" name="position" value={index + 1} /><button
|
||||||
|
type="submit"
|
||||||
|
disabled={index === data.show.sections.length - 1}
|
||||||
|
aria-label={`${section.name} nach unten`}>↓</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{#if section.usages.length}<div class="usage-list">
|
||||||
|
{#each section.usages as usage, usageIndex (usage.id)}
|
||||||
|
<div
|
||||||
|
class="usage-drag-slot"
|
||||||
|
role="presentation"
|
||||||
|
ondragover={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}}
|
||||||
|
ondrop={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
dropAtPreview();
|
||||||
|
}}
|
||||||
|
animate:flip={{ duration: 180 }}
|
||||||
|
>
|
||||||
|
{#if showsUsagePreview(section.id, usageIndex)}
|
||||||
|
<div
|
||||||
|
class="drag-insert-preview usage-insert-preview"
|
||||||
|
data-drop-preview="usage"
|
||||||
|
>
|
||||||
|
<strong>{draggedTitle()}</strong><small>Hier einfügen</small>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div
|
||||||
|
class="usage-row editable-usage"
|
||||||
|
class:is-dragging={dragged?.kind === 'usage' && dragged.id === usage.id}
|
||||||
|
role="group"
|
||||||
|
aria-label={`Verwendung ${usage.title}`}
|
||||||
|
ondragover={(event) => previewUsage(event, section.id, usageIndex)}
|
||||||
|
ondrop={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
dropAtPreview();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="usage-drag-copy"
|
||||||
|
role="group"
|
||||||
|
aria-label={`${usage.title} verschieben`}
|
||||||
|
draggable="true"
|
||||||
|
ondragstart={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
startDrag('usage', usage.id, event);
|
||||||
|
}}
|
||||||
|
ondragend={finishDrag}
|
||||||
|
>
|
||||||
|
<strong>{usage.title}</strong><small
|
||||||
|
>{formatClock(usage.durationSeconds)} · sendungsspezifische Kopie</small
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="row-actions">
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/moveUsage">
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/><input type="hidden" name="sectionId" value={section.id} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="position"
|
||||||
|
value={usageIndex - 1}
|
||||||
|
/><button
|
||||||
|
type="submit"
|
||||||
|
disabled={usageIndex === 0}
|
||||||
|
aria-label={`${usage.title} nach oben`}>↑</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/moveUsage">
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/><input type="hidden" name="sectionId" value={section.id} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="position"
|
||||||
|
value={usageIndex + 1}
|
||||||
|
/><button
|
||||||
|
type="submit"
|
||||||
|
disabled={usageIndex === section.usages.length - 1}
|
||||||
|
aria-label={`${usage.title} nach unten`}>↓</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<UsageEditorDialog
|
||||||
|
{usage}
|
||||||
|
revision={data.show.revision}
|
||||||
|
sectionId={section.id}
|
||||||
|
sections={data.show.sections}
|
||||||
|
error={form?.error}
|
||||||
|
{enhanceCommand}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if showsUsagePreview(section.id, section.usages.length)}
|
||||||
|
<div class="drag-insert-preview usage-insert-preview" data-drop-preview="usage">
|
||||||
|
<strong>{draggedTitle()}</strong><small>Hier einfügen</small>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>{:else}
|
||||||
|
{#if showsUsagePreview(section.id, 0)}
|
||||||
|
<div class="usage-list">
|
||||||
|
<div class="drag-insert-preview usage-insert-preview" data-drop-preview="usage">
|
||||||
|
<strong>{draggedTitle()}</strong><small>Hier einfügen</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div
|
||||||
|
class="section-placeholder"
|
||||||
|
role="group"
|
||||||
|
aria-label={`Leerer Abschnitt ${section.name}`}
|
||||||
|
ondragover={(event) => previewUsage(event, section.id, 0, false)}
|
||||||
|
ondrop={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
dropAtPreview();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Leerer Abschnitt · Piece aus dem Fundus hinzufügen oder hierher ziehen
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<details class="section-editor">
|
||||||
|
<summary>Abschnitt bearbeiten</summary>
|
||||||
|
<form
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/updateSection"
|
||||||
|
class="section-edit-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="sectionId"
|
||||||
|
value={section.id}
|
||||||
|
/><label
|
||||||
|
>Name<input name="name" required maxlength="200" value={section.name} /></label
|
||||||
|
><label
|
||||||
|
>Kategorie<select name="categoryId"
|
||||||
|
><option value="">Ohne Kategorie</option
|
||||||
|
>{#each data.taxonomy.categories as category (category.id)}<option
|
||||||
|
value={category.id}
|
||||||
|
selected={section.categoryId === category.id}>{category.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
><label
|
||||||
|
>Explizite Dauer in Sekunden<input
|
||||||
|
name="explicitDurationSeconds"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
max="86400"
|
||||||
|
value={section.explicitDurationSeconds ?? ''}
|
||||||
|
placeholder="Summe der Pieces"
|
||||||
|
/></label
|
||||||
|
><button class="secondary-button" type="submit">Abschnitt speichern</button>
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/removeSection"
|
||||||
|
onsubmit={(event) =>
|
||||||
|
!confirm('Abschnitt samt Einplanungen entfernen?') && event.preventDefault()}
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="sectionId"
|
||||||
|
value={section.id}
|
||||||
|
/><button class="text-button danger-text" type="submit"
|
||||||
|
>Abschnitt entfernen</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if dropPreview?.kind === 'section' && dropPreview.position === data.show.sections.length}
|
||||||
|
<div
|
||||||
|
class="drag-insert-preview section-insert-preview"
|
||||||
|
data-drop-preview="section"
|
||||||
|
role="group"
|
||||||
|
aria-label={`${draggedTitle()} hier einfügen`}
|
||||||
|
ondragover={(event) => event.preventDefault()}
|
||||||
|
ondrop={dropAtPreview}
|
||||||
|
>
|
||||||
|
<span>Hier einfügen</span><strong>{draggedTitle()}</strong>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/addSection"
|
||||||
|
class="add-section-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><label
|
||||||
|
>Name<input name="name" required maxlength="200" placeholder="Neuer Abschnitt" /></label
|
||||||
|
><label
|
||||||
|
>Kategorie<select name="categoryId"
|
||||||
|
><option value="">Ohne Kategorie</option
|
||||||
|
>{#each data.taxonomy.categories as category (category.id)}<option value={category.id}
|
||||||
|
>{category.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
><label
|
||||||
|
>Explizite Dauer <input
|
||||||
|
name="explicitDurationSeconds"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
max="86400"
|
||||||
|
placeholder="optional, Sekunden"
|
||||||
|
/></label
|
||||||
|
><button class="primary-button" type="submit">Abschnitt hinzufügen</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<section
|
||||||
|
class="reserve-box editable-reserve"
|
||||||
|
class:drop-ready={dropTarget === 'reserve'}
|
||||||
|
aria-label="Reservebank"
|
||||||
|
ondragover={(event) => previewUsage(event, null, data.show.reserve.length, false)}
|
||||||
|
ondrop={dropAtPreview}
|
||||||
|
>
|
||||||
|
<header>
|
||||||
|
<div>
|
||||||
|
<span aria-hidden="true">◇</span>
|
||||||
|
<div>
|
||||||
|
<strong>Reservebank</strong><small
|
||||||
|
>{data.show.reserve.length}
|
||||||
|
{data.show.reserve.length === 1 ? 'Piece' : 'Pieces'} · zählt nicht zur Planzeit</small
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
{#each data.show.reserve as usage, usageIndex (usage.id)}
|
||||||
|
<div
|
||||||
|
class="reserve-drag-slot"
|
||||||
|
role="presentation"
|
||||||
|
ondragover={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
}}
|
||||||
|
ondrop={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
dropAtPreview();
|
||||||
|
}}
|
||||||
|
animate:flip={{ duration: 180 }}
|
||||||
|
>
|
||||||
|
{#if showsUsagePreview(null, usageIndex)}
|
||||||
|
<div class="drag-insert-preview reserve-insert-preview" data-drop-preview="usage">
|
||||||
|
<strong>{draggedTitle()}</strong><small>Hier in die Reserve einfügen</small>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div
|
||||||
|
class="reserve-usage"
|
||||||
|
class:is-dragging={dragged?.kind === 'usage' && dragged.id === usage.id}
|
||||||
|
role="group"
|
||||||
|
aria-label={`Reserve ${usage.title}`}
|
||||||
|
ondragover={(event) => previewUsage(event, null, usageIndex)}
|
||||||
|
ondrop={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
dropAtPreview();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="usage-drag-copy"
|
||||||
|
role="group"
|
||||||
|
aria-label={`${usage.title} verschieben`}
|
||||||
|
draggable="true"
|
||||||
|
ondragstart={(event) => startDrag('usage', usage.id, event)}
|
||||||
|
ondragend={finishDrag}
|
||||||
|
>
|
||||||
|
<strong>{usage.title}</strong><small>{formatClock(usage.durationSeconds)}</small>
|
||||||
|
</div>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/moveUsage">
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/><input type="hidden" name="position" value="9999" /><label
|
||||||
|
><span class="sr-only">{usage.title} einplanen in</span><select
|
||||||
|
name="sectionId"
|
||||||
|
required
|
||||||
|
><option value="">Abschnitt wählen</option
|
||||||
|
>{#each data.show.sections as section (section.id)}<option value={section.id}
|
||||||
|
>{section.name}</option
|
||||||
|
>{/each}</select
|
||||||
|
></label
|
||||||
|
><button class="secondary-button" type="submit">Einplanen</button>
|
||||||
|
</form>
|
||||||
|
<form use:enhance={enhanceCommand} method="POST" action="?/removeUsage">
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={usage.id}
|
||||||
|
/><button
|
||||||
|
class="text-button danger-text"
|
||||||
|
type="submit"
|
||||||
|
aria-label={`${usage.title} aus Reserve entfernen`}>Entfernen</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
<UsageEditorDialog
|
||||||
|
{usage}
|
||||||
|
revision={data.show.revision}
|
||||||
|
sectionId=""
|
||||||
|
sections={data.show.sections}
|
||||||
|
error={form?.error}
|
||||||
|
{enhanceCommand}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
{#if showsUsagePreview(null, data.show.reserve.length)}
|
||||||
|
<div class="drag-insert-preview reserve-insert-preview" data-drop-preview="usage">
|
||||||
|
<strong>{draggedTitle()}</strong><small>Hier in die Reserve einfügen</small>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if !data.show.reserve.length}<p>
|
||||||
|
Pieces lassen sich hier parken, ohne die geplante Dauer zu erhöhen.
|
||||||
|
</p>{/if}
|
||||||
|
</section>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form
|
||||||
|
bind:this={moveSectionForm}
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/moveSection"
|
||||||
|
class="hidden-command-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="sectionId"
|
||||||
|
value={draggedSectionId}
|
||||||
|
/><input type="hidden" name="position" value={dropPosition} />
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
bind:this={moveUsageForm}
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/moveUsage"
|
||||||
|
class="hidden-command-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="usageId"
|
||||||
|
value={draggedUsageId}
|
||||||
|
/><input type="hidden" name="sectionId" value={dropSectionId} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="position"
|
||||||
|
value={dropPosition}
|
||||||
|
/>
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
bind:this={addUsageForm}
|
||||||
|
use:enhance={enhanceCommand}
|
||||||
|
method="POST"
|
||||||
|
action="?/addUsage"
|
||||||
|
class="hidden-command-form"
|
||||||
|
>
|
||||||
|
<input type="hidden" name="revision" value={data.show.revision} /><input
|
||||||
|
type="hidden"
|
||||||
|
name="pieceId"
|
||||||
|
value={draggedPieceId}
|
||||||
|
/><input type="hidden" name="sectionId" value={dropSectionId} />
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { fail, redirect } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import {
|
||||||
|
createFirstAdmin,
|
||||||
|
createSession,
|
||||||
|
hasUsers,
|
||||||
|
setupIsConfigured,
|
||||||
|
validDisplayName,
|
||||||
|
validEmail,
|
||||||
|
validPassword
|
||||||
|
} from '#lib/server/auth.js';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = () => {
|
||||||
|
if (hasUsers()) redirect(303, '/login');
|
||||||
|
return { configured: setupIsConfigured() };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
default: async ({ request, cookies }) => {
|
||||||
|
if (hasUsers()) redirect(303, '/login');
|
||||||
|
const data = await request.formData();
|
||||||
|
const setupToken = String(data.get('setupToken') || '');
|
||||||
|
const displayName = String(data.get('displayName') || '').trim();
|
||||||
|
const email = String(data.get('email') || '').trim();
|
||||||
|
const password = String(data.get('password') || '');
|
||||||
|
if (!validDisplayName(displayName) || !validEmail(email) || !validPassword(password)) {
|
||||||
|
return fail(400, {
|
||||||
|
error: 'Bitte Name, gültige E-Mail und ein Passwort mit mindestens 12 Zeichen prüfen.',
|
||||||
|
displayName,
|
||||||
|
email
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const user = await createFirstAdmin({ setupToken, displayName, email, password });
|
||||||
|
createSession(user.id, cookies);
|
||||||
|
} catch (cause) {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'SETUP_CLOSED') redirect(303, '/login');
|
||||||
|
return fail(403, {
|
||||||
|
error: 'Das Betreiber-Setup-Token ist ungültig.',
|
||||||
|
displayName,
|
||||||
|
email
|
||||||
|
});
|
||||||
|
}
|
||||||
|
redirect(303, '/fundus');
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { PageProps } from './$types';
|
||||||
|
let { data, form }: PageProps = $props();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head><title>Erstadmin einrichten | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
|
<section class="auth-card">
|
||||||
|
<p class="eyebrow">Einmalige Einrichtung</p>
|
||||||
|
<h1>Ersten Barkeeper anlegen</h1>
|
||||||
|
<p>
|
||||||
|
Dieses Konto verwaltet Einladungen, Rollen und Sperren. Danach wird die Einrichtung geschlossen.
|
||||||
|
</p>
|
||||||
|
{#if !data.configured}
|
||||||
|
<div class="form-message error" role="alert">
|
||||||
|
Vor dem Start muss ein mindestens 32 Zeichen langes <code>SENDEWERK_SETUP_TOKEN</code>
|
||||||
|
konfiguriert werden.
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
<form class="auth-form" method="POST">
|
||||||
|
<label
|
||||||
|
>Betreiber-Setup-Token<input
|
||||||
|
name="setupToken"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
autocomplete="off"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Name<input
|
||||||
|
name="displayName"
|
||||||
|
required
|
||||||
|
maxlength="80"
|
||||||
|
value={form?.displayName ?? ''}
|
||||||
|
autocomplete="name"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>E-Mail<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
maxlength="254"
|
||||||
|
value={form?.email ?? ''}
|
||||||
|
autocomplete="email"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Passwort<input
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
minlength="12"
|
||||||
|
maxlength="256"
|
||||||
|
autocomplete="new-password"
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<p class="field-hint">
|
||||||
|
Mindestens 12 Zeichen. Das Passwort wird ausschließlich als Argon2id-Hash gespeichert.
|
||||||
|
</p>
|
||||||
|
<button class="primary-button" type="submit">Barkeeper anlegen</button>
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
@@ -1,5 +1,135 @@
|
|||||||
import { getTaxonomy } from '#lib/server/previews.js';
|
import { fail } from '@sveltejs/kit';
|
||||||
|
import type { Actions, PageServerLoad } from './$types';
|
||||||
|
import {
|
||||||
|
createTaxonomy,
|
||||||
|
deleteTaxonomy,
|
||||||
|
getTaxonomy,
|
||||||
|
type TaxonomyKind
|
||||||
|
} from '#lib/server/content.js';
|
||||||
|
import { getMailConfig } from '#lib/server/config.js';
|
||||||
|
import {
|
||||||
|
inviteUser,
|
||||||
|
isRole,
|
||||||
|
listOpenInvitations,
|
||||||
|
listUsers,
|
||||||
|
requireBarkeeper,
|
||||||
|
revokeInvitation,
|
||||||
|
setUserLocked,
|
||||||
|
setUserRole,
|
||||||
|
validEmail
|
||||||
|
} from '#lib/server/auth.js';
|
||||||
|
|
||||||
export function load() {
|
export const load: PageServerLoad = ({ locals }) => {
|
||||||
return { taxonomy: getTaxonomy() };
|
requireBarkeeper(locals.user);
|
||||||
|
return {
|
||||||
|
taxonomy: getTaxonomy(),
|
||||||
|
users: listUsers(),
|
||||||
|
invitations: listOpenInvitations(),
|
||||||
|
mailTransport: getMailConfig().transport
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
function actionError(cause: unknown): string {
|
||||||
|
const code = cause instanceof Error ? cause.message : '';
|
||||||
|
if (code === 'USER_EXISTS') return 'Für diese E-Mail existiert bereits ein Konto.';
|
||||||
|
if (code === 'SELF_LOCK') return 'Das eigene Konto kann nicht gesperrt werden.';
|
||||||
|
if (code === 'LAST_BARKEEPER') return 'Mindestens ein aktiver Barkeeper muss erhalten bleiben.';
|
||||||
|
if (code === 'NOT_FOUND') return 'Der Eintrag wurde nicht gefunden.';
|
||||||
|
if (code === 'TAXONOMY_EXISTS') return 'Dieser Name ist bereits vorhanden.';
|
||||||
|
if (code === 'TAXONOMY_IN_USE')
|
||||||
|
return 'Verwendete oder für Vorlagen benötigte Einträge können nicht entfernt werden.';
|
||||||
|
if (code === 'INVALID_COLOR') return 'Bitte eine gültige Farbe wählen.';
|
||||||
|
if (code === 'INVALID_TAXONOMY') return 'Bitte einen gültigen Namen eingeben.';
|
||||||
|
return 'Die Aktion konnte nicht ausgeführt werden.';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const actions = {
|
||||||
|
invite: async ({ locals, request }) => {
|
||||||
|
const actor = requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const email = String(data.get('email') || '').trim();
|
||||||
|
const role = String(data.get('role') || '');
|
||||||
|
if (!validEmail(email) || !isRole(role)) {
|
||||||
|
return fail(400, { intent: 'invite', email, error: 'E-Mail und Rolle bitte prüfen.' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const transport = await inviteUser(actor, email, role);
|
||||||
|
return {
|
||||||
|
intent: 'invite',
|
||||||
|
success:
|
||||||
|
transport === 'local'
|
||||||
|
? 'Einladung wurde in der lokalen Mail-Outbox abgelegt.'
|
||||||
|
: 'Einladung wurde versandt.'
|
||||||
|
};
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'invite', email, error: actionError(cause) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
role: async ({ locals, request }) => {
|
||||||
|
const actor = requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const userId = String(data.get('userId') || '');
|
||||||
|
const role = String(data.get('role') || '');
|
||||||
|
if (!userId || !isRole(role)) return fail(400, { intent: 'role', error: 'Ungültige Rolle.' });
|
||||||
|
try {
|
||||||
|
setUserRole(actor, userId, role);
|
||||||
|
return { intent: 'role', success: 'Rolle aktualisiert.' };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'role', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
lock: async ({ locals, request }) => {
|
||||||
|
const actor = requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
setUserLocked(actor, String(data.get('userId') || ''), true);
|
||||||
|
return { intent: 'lock', success: 'Konto gesperrt und bestehende Sitzungen beendet.' };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'lock', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
unlock: async ({ locals, request }) => {
|
||||||
|
const actor = requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
try {
|
||||||
|
setUserLocked(actor, String(data.get('userId') || ''), false);
|
||||||
|
return { intent: 'unlock', success: 'Konto entsperrt.' };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'unlock', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
revokeInvitation: async ({ locals, request }) => {
|
||||||
|
const actor = requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
revokeInvitation(actor, String(data.get('invitationId') || ''));
|
||||||
|
return { intent: 'revokeInvitation', success: 'Einladung widerrufen.' };
|
||||||
|
},
|
||||||
|
createTaxonomy: async ({ locals, request }) => {
|
||||||
|
requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const kind = String(data.get('kind') || '') as TaxonomyKind;
|
||||||
|
if (!['category', 'format', 'topic'].includes(kind)) {
|
||||||
|
return fail(400, { intent: 'taxonomy', error: 'Ungültige Taxonomieart.' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
createTaxonomy(kind, String(data.get('name') || ''), String(data.get('color') || ''));
|
||||||
|
return { intent: 'taxonomy', success: 'Eintrag angelegt.' };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'taxonomy', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
deleteTaxonomy: async ({ locals, request }) => {
|
||||||
|
requireBarkeeper(locals.user);
|
||||||
|
const data = await request.formData();
|
||||||
|
const kind = String(data.get('kind') || '') as TaxonomyKind;
|
||||||
|
if (!['category', 'format', 'topic'].includes(kind)) {
|
||||||
|
return fail(400, { intent: 'taxonomy', error: 'Ungültige Taxonomieart.' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
deleteTaxonomy(kind, String(data.get('taxonomyId') || ''));
|
||||||
|
return { intent: 'taxonomy', success: 'Eintrag entfernt.' };
|
||||||
|
} catch (cause) {
|
||||||
|
return fail(400, { intent: 'taxonomy', error: actionError(cause) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} satisfies Actions;
|
||||||
@@ -1,50 +1,203 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { PageData } from './$types';
|
import type { PageProps } from './$types';
|
||||||
let { data }: { data: PageData } = $props();
|
let { data, form }: PageProps = $props();
|
||||||
|
|
||||||
|
function confirmTaxonomyRemoval(event: SubmitEvent) {
|
||||||
|
if (!confirm('Eintrag wirklich entfernen?')) event.preventDefault();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head><title>Verwaltung | Sendewerk</title></svelte:head>
|
<svelte:head><title>Verwaltung | Sendewerk</title></svelte:head>
|
||||||
|
|
||||||
<div class="page-wrap narrow-page">
|
<div class="page-wrap narrow-page">
|
||||||
<header class="page-heading">
|
<header class="page-heading">
|
||||||
<p class="eyebrow">System & Struktur</p>
|
|
||||||
<h1>Verwaltung</h1>
|
<h1>Verwaltung</h1>
|
||||||
<p class="page-intro">
|
<p class="page-intro">Konten, Rollen und bestehende Taxonomie verwalten.</p>
|
||||||
Die bereits angelegte Taxonomie ist sichtbar; Bearbeitung und Benutzerverwaltung folgen mit
|
|
||||||
serverseitigen Rechten.
|
|
||||||
</p>
|
|
||||||
</header>
|
</header>
|
||||||
|
{#if form?.error}<div class="form-message error" role="alert">{form.error}</div>{/if}
|
||||||
|
{#if form?.success}<div class="form-message success" role="status">{form.success}</div>{/if}
|
||||||
|
|
||||||
|
<section class="quiet-panel account-panel">
|
||||||
|
<div class="panel-heading">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow">Konten & Rollen</p>
|
||||||
|
<h2>Redaktionszugänge</h2>
|
||||||
|
</div>
|
||||||
|
<span class="mail-mode"
|
||||||
|
>Mail: {data.mailTransport === 'local' ? 'lokale Outbox' : 'SMTP'}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
<div class="account-list">
|
||||||
|
{#each data.users as user (user.id)}
|
||||||
|
<article class="account-row">
|
||||||
|
<div><strong>{user.displayName}</strong><small>{user.email}</small></div>
|
||||||
|
<span class:locked={user.lockedAtUtc} class="account-status"
|
||||||
|
>{user.lockedAtUtc ? 'Gesperrt' : 'Aktiv'}</span
|
||||||
|
>
|
||||||
|
<form method="POST" action="?/role" class="inline-account-form">
|
||||||
|
<input type="hidden" name="userId" value={user.id} />
|
||||||
|
<label class="sr-only" for={`role-${user.id}`}>Rolle für {user.displayName}</label>
|
||||||
|
<select id={`role-${user.id}`} name="role">
|
||||||
|
<option value="barkeeper" selected={user.role === 'barkeeper'}>Barkeeper</option>
|
||||||
|
<option value="thekencrew" selected={user.role === 'thekencrew'}>Thekencrew</option>
|
||||||
|
</select>
|
||||||
|
<button class="text-button" type="submit">Rolle speichern</button>
|
||||||
|
</form>
|
||||||
|
<form method="POST" action={user.lockedAtUtc ? '?/unlock' : '?/lock'}>
|
||||||
|
<input type="hidden" name="userId" value={user.id} />
|
||||||
|
<button
|
||||||
|
class="secondary-button"
|
||||||
|
type="submit"
|
||||||
|
disabled={user.id === data.user?.id}
|
||||||
|
title={user.id === data.user?.id
|
||||||
|
? 'Das eigene Konto kann nicht gesperrt werden.'
|
||||||
|
: undefined}
|
||||||
|
>{user.lockedAtUtc
|
||||||
|
? 'Entsperren'
|
||||||
|
: user.id === data.user?.id
|
||||||
|
? 'Eigenes Konto'
|
||||||
|
: 'Sperren'}</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</article>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="management-grid">
|
||||||
|
<section class="quiet-panel invite-panel">
|
||||||
|
<p class="eyebrow">Einladung</p>
|
||||||
|
<h2>Neues Konto einladen</h2>
|
||||||
|
<form class="compact-form" method="POST" action="?/invite">
|
||||||
|
<label
|
||||||
|
>E-Mail<input
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
maxlength="254"
|
||||||
|
value={form?.intent === 'invite' ? (form.email ?? '') : ''}
|
||||||
|
/></label
|
||||||
|
>
|
||||||
|
<label
|
||||||
|
>Rolle<select name="role"
|
||||||
|
><option value="thekencrew">Thekencrew</option><option value="barkeeper"
|
||||||
|
>Barkeeper</option
|
||||||
|
></select
|
||||||
|
></label
|
||||||
|
>
|
||||||
|
<button class="primary-button" type="submit">Einladung erstellen</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
<section class="quiet-panel invite-panel">
|
||||||
|
<p class="eyebrow">Offene Einladungen</p>
|
||||||
|
<h2>Noch nicht angenommen</h2>
|
||||||
|
{#if data.invitations.length}
|
||||||
|
<div class="invitation-list">
|
||||||
|
{#each data.invitations as invitation (invitation.id)}
|
||||||
|
<div>
|
||||||
|
<span
|
||||||
|
><strong>{invitation.email}</strong><small
|
||||||
|
>{invitation.role === 'barkeeper' ? 'Barkeeper' : 'Thekencrew'}</small
|
||||||
|
></span
|
||||||
|
>
|
||||||
|
<form method="POST" action="?/revokeInvitation">
|
||||||
|
<input type="hidden" name="invitationId" value={invitation.id} /><button
|
||||||
|
class="text-button"
|
||||||
|
type="submit">Widerrufen</button
|
||||||
|
>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{:else}<p class="quiet-copy">Keine offenen Einladungen.</p>{/if}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2 class="section-heading">Taxonomie</h2>
|
||||||
<div class="settings-grid">
|
<div class="settings-grid">
|
||||||
<section class="quiet-panel taxonomy-panel">
|
<section class="quiet-panel taxonomy-panel">
|
||||||
<p class="eyebrow">Abschnittskategorien</p>
|
<p class="eyebrow">Abschnittskategorien</p>
|
||||||
<h2>Struktur im Ablauf</h2>
|
<h2>Struktur im Ablauf</h2>
|
||||||
<div class="taxonomy-list">
|
<div class="taxonomy-list editable-taxonomy">
|
||||||
{#each data.taxonomy.categories as category (category.id)}<span
|
{#each data.taxonomy.categories as category (category.id)}<span
|
||||||
><i style={`--tax-color: ${category.color}`}></i>{category.name}</span
|
><i style={`--tax-color: ${category.color}`}></i>{category.name}
|
||||||
|
<form method="POST" action="?/deleteTaxonomy" onsubmit={confirmTaxonomyRemoval}>
|
||||||
|
<input type="hidden" name="kind" value="category" /><input
|
||||||
|
type="hidden"
|
||||||
|
name="taxonomyId"
|
||||||
|
value={category.id}
|
||||||
|
/><button type="submit" aria-label={`${category.name} entfernen`}>×</button>
|
||||||
|
</form></span
|
||||||
>{/each}
|
>{/each}
|
||||||
</div>
|
</div>
|
||||||
|
<form class="taxonomy-form" method="POST" action="?/createTaxonomy">
|
||||||
|
<input type="hidden" name="kind" value="category" /><label
|
||||||
|
><span class="sr-only">Neue Abschnittskategorie</span><input
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
maxlength="80"
|
||||||
|
placeholder="Neue Kategorie"
|
||||||
|
/></label
|
||||||
|
><label class="color-field"
|
||||||
|
><span class="sr-only">Farbe</span><input
|
||||||
|
name="color"
|
||||||
|
type="color"
|
||||||
|
value="#67DDE8"
|
||||||
|
/></label
|
||||||
|
><button class="text-button" type="submit">Hinzufügen</button>
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
<section class="quiet-panel taxonomy-panel">
|
<section class="quiet-panel taxonomy-panel">
|
||||||
<p class="eyebrow">Formate</p>
|
<p class="eyebrow">Formate</p>
|
||||||
<h2>Form des Stücks</h2>
|
<h2>Form des Stücks</h2>
|
||||||
<div class="taxonomy-list">
|
<div class="taxonomy-list editable-taxonomy">
|
||||||
{#each data.taxonomy.formats as format (format.id)}<span>{format.name}</span>{/each}
|
{#each data.taxonomy.formats as format (format.id)}<span
|
||||||
|
>{format.name}
|
||||||
|
<form method="POST" action="?/deleteTaxonomy" onsubmit={confirmTaxonomyRemoval}>
|
||||||
|
<input type="hidden" name="kind" value="format" /><input
|
||||||
|
type="hidden"
|
||||||
|
name="taxonomyId"
|
||||||
|
value={format.id}
|
||||||
|
/><button type="submit" aria-label={`${format.name} entfernen`}>×</button>
|
||||||
|
</form></span
|
||||||
|
>{/each}
|
||||||
</div>
|
</div>
|
||||||
|
<form class="taxonomy-form" method="POST" action="?/createTaxonomy">
|
||||||
|
<input type="hidden" name="kind" value="format" /><label
|
||||||
|
><span class="sr-only">Neues Format</span><input
|
||||||
|
name="name"
|
||||||
|
required
|
||||||
|
maxlength="80"
|
||||||
|
placeholder="Neues Format"
|
||||||
|
/></label
|
||||||
|
><button class="text-button" type="submit">Hinzufügen</button>
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
<section class="quiet-panel taxonomy-panel">
|
<section class="quiet-panel taxonomy-panel">
|
||||||
<p class="eyebrow">Themen</p>
|
<p class="eyebrow">Themen</p>
|
||||||
<h2>Inhaltliche Zuordnung</h2>
|
<h2>Inhaltliche Zuordnung</h2>
|
||||||
<div class="taxonomy-list">
|
<div class="taxonomy-list editable-taxonomy">
|
||||||
{#each data.taxonomy.topics as topic (topic.id)}<span>{topic.name}</span>{/each}
|
{#each data.taxonomy.topics as topic (topic.id)}<span
|
||||||
|
>{topic.name}
|
||||||
|
<form method="POST" action="?/deleteTaxonomy" onsubmit={confirmTaxonomyRemoval}>
|
||||||
|
<input type="hidden" name="kind" value="topic" /><input
|
||||||
|
type="hidden"
|
||||||
|
name="taxonomyId"
|
||||||
|
value={topic.id}
|
||||||
|
/><button type="submit" aria-label={`${topic.name} entfernen`}>×</button>
|
||||||
|
</form></span
|
||||||
|
>{/each}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
<form class="taxonomy-form" method="POST" action="?/createTaxonomy">
|
||||||
<section class="quiet-panel planned-settings">
|
<input type="hidden" name="kind" value="topic" /><label
|
||||||
<p class="eyebrow">Etappe 2</p>
|
><span class="sr-only">Neues Thema</span><input
|
||||||
<h2>Konten & Rollen</h2>
|
name="name"
|
||||||
<p>
|
required
|
||||||
Barkeeper, Thekencrew und technische Zugänge werden erst mit vollständiger Authentifizierung
|
maxlength="80"
|
||||||
verwaltbar.
|
placeholder="Neues Thema"
|
||||||
</p>
|
/></label
|
||||||
|
><button class="text-button" type="submit">Hinzufügen</button>
|
||||||
|
</form>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -2,11 +2,20 @@
|
|||||||
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
mkdir -p /app/data/uploads
|
mkdir -p /app/data/uploads /app/data/mail-outbox
|
||||||
chown -R cloudron:cloudron /app/data
|
chown -R cloudron:cloudron /app/data
|
||||||
|
|
||||||
export SENDEWERK_DB_PATH="${SENDEWERK_DB_PATH:-/app/data/sendewerk.sqlite}"
|
export SENDEWERK_DB_PATH="${SENDEWERK_DB_PATH:-/app/data/sendewerk.sqlite}"
|
||||||
export SENDEWERK_UPLOAD_DIR="${SENDEWERK_UPLOAD_DIR:-/app/data/uploads}"
|
export SENDEWERK_UPLOAD_DIR="${SENDEWERK_UPLOAD_DIR:-/app/data/uploads}"
|
||||||
|
export SENDEWERK_MAIL_OUTBOX_DIR="${SENDEWERK_MAIL_OUTBOX_DIR:-/app/data/mail-outbox}"
|
||||||
|
export BODY_SIZE_LIMIT="${BODY_SIZE_LIMIT:-6M}"
|
||||||
|
export SENDEWERK_APP_ORIGIN="${SENDEWERK_APP_ORIGIN:-${CLOUDRON_APP_ORIGIN:-}}"
|
||||||
|
if [ -n "${CLOUDRON_APP_ORIGIN:-}" ]; then
|
||||||
|
export PROTOCOL_HEADER="${PROTOCOL_HEADER:-x-forwarded-proto}"
|
||||||
|
export HOST_HEADER="${HOST_HEADER:-x-forwarded-host}"
|
||||||
|
export ADDRESS_HEADER="${ADDRESS_HEADER:-x-forwarded-for}"
|
||||||
|
export XFF_DEPTH="${XFF_DEPTH:-1}"
|
||||||
|
fi
|
||||||
export HOST="${HOST:-0.0.0.0}"
|
export HOST="${HOST:-0.0.0.0}"
|
||||||
export PORT="${PORT:-3000}"
|
export PORT="${PORT:-3000}"
|
||||||
|
|
||||||
|
|||||||
+1205
-42
File diff suppressed because it is too large.
Load diff
+4
-1
@@ -9,7 +9,10 @@ export default defineConfig({
|
|||||||
runes: ({ filename }) =>
|
runes: ({ filename }) =>
|
||||||
filename.split(/[/\\]/).includes('node_modules') ? undefined : true
|
filename.split(/[/\\]/).includes('node_modules') ? undefined : true
|
||||||
},
|
},
|
||||||
adapter: adapter()
|
adapter: adapter(),
|
||||||
|
paths: {
|
||||||
|
origin: process.env.SENDEWERK_APP_ORIGIN
|
||||||
|
}
|
||||||
})
|
})
|
||||||
],
|
],
|
||||||
test: {
|
test: {
|
||||||
|
|||||||
Reference in new issue
Block a user