diff --git a/.dockerignore b/.dockerignore index caec329..2a9663c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,3 +3,4 @@ node_modules .env uploads .git +videos diff --git a/.gitignore b/.gitignore index 845d30c..32e3b4c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ uploads/* !uploads/.gitkeep *.tsbuildinfo next-env.d.ts +videos/ diff --git a/Dockerfile b/Dockerfile index d537409..827091b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -15,8 +15,9 @@ RUN npx prisma generate && npm run build FROM node:22-alpine AS run WORKDIR /app -RUN apk add --no-cache openssl && addgroup -S app && adduser -S app -G app -ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 UPLOAD_DIR=/app/uploads +# ffmpeg wandelt die Kursvideos in HLS um +RUN apk add --no-cache openssl ffmpeg && addgroup -S app && adduser -S app -G app +ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 UPLOAD_DIR=/app/uploads VIDEO_DIR=/app/videos COPY --from=build /app/.next/standalone ./ COPY --from=build /app/.next/static ./.next/static COPY --from=build /app/public ./public @@ -25,7 +26,7 @@ COPY --from=build /app/src/lib/permissions.ts ./src/lib/permissions.ts COPY --from=build /app/src/lib/payments/catalog.ts ./src/lib/payments/catalog.ts COPY --from=deps /app/node_modules ./node_modules COPY docker/entrypoint.sh /entrypoint.sh -RUN mkdir -p /app/uploads && chown -R app:app /app/uploads && chmod +x /entrypoint.sh +RUN mkdir -p /app/uploads /app/videos && chown -R app:app /app/uploads /app/videos && chmod +x /entrypoint.sh USER app EXPOSE 3000 ENTRYPOINT ["/entrypoint.sh"] diff --git a/docker-compose.yml b/docker-compose.yml index 2499a51..23cf0b2 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,9 +29,12 @@ services: ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD in .env setzen} volumes: - uploads:/app/uploads + # Kursvideos (umgewandelt und verschlüsselt), nie direkt erreichbar + - videos:/app/videos ports: - "127.0.0.1:3000:3000" volumes: db: uploads: + videos: diff --git a/package-lock.json b/package-lock.json index 56c7ac6..36ecf9c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@fontsource/jost": "^5.3.0", "@prisma/client": "6.19.3", "bcryptjs": "3.0.3", + "hls.js": "1.7.3", "next": "15.5.28", "react": "19.1.10", "react-dom": "19.1.10", @@ -1563,6 +1564,12 @@ "giget": "dist/cli.mjs" } }, + "node_modules/hls.js": { + "version": "1.7.3", + "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.3.tgz", + "integrity": "sha512-MsPlx6yVW4Qv4C7mEVou4/gk/5cN2dVxOTnrNjPSmyH2f0Ln+/UkG10Ax1PE6OvrmTVPKgQYozTtBaPOuCzq7A==", + "license": "Apache-2.0" + }, "node_modules/jiti": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", diff --git a/package.json b/package.json index d4875d6..ee3f800 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "@fontsource/jost": "^5.3.0", "@prisma/client": "6.19.3", "bcryptjs": "3.0.3", + "hls.js": "1.7.3", "next": "15.5.28", "react": "19.1.10", "react-dom": "19.1.10", diff --git a/prisma/migrations/20261020220000_video_error/migration.sql b/prisma/migrations/20261020220000_video_error/migration.sql new file mode 100644 index 0000000..9be35e4 --- /dev/null +++ b/prisma/migrations/20261020220000_video_error/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "CourseLesson" ADD COLUMN "videoError" TEXT NOT NULL DEFAULT ''; + diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 46814d7..3f0e840 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -157,10 +157,11 @@ model CourseLesson { chapter CourseChapter @relation(fields: [chapterId], references: [id], onDelete: Cascade) title String description String @default("") - // Video bei Bunny Stream (GUID); leer, solange noch nichts hochgeladen ist + // Ordner des fertig umgewandelten Videos (HLS); leer, solange es noch keins gibt videoId String @default("") - // "none", "uploading", "processing", "ready", "error" + // Stand des letzten Uploads: "none", "queued", "processing", "ready", "error" videoStatus String @default("none") + videoError String @default("") // Länge in Sekunden duration Int @default(0) // Kostenlose Vorschau auf der Produktseite diff --git a/src/app/(shop)/konto/kurse/[slug]/page.tsx b/src/app/(shop)/konto/kurse/[slug]/page.tsx index 51532b2..024b489 100644 --- a/src/app/(shop)/konto/kurse/[slug]/page.tsx +++ b/src/app/(shop)/konto/kurse/[slug]/page.tsx @@ -3,7 +3,7 @@ import { notFound, redirect } from "next/navigation"; import { db } from "@/lib/db"; import { getCurrentUser } from "@/lib/auth"; import { getCourseOutline, hasCourseAccess, isCourse } from "@/lib/courses"; -import { embedUrl, getBunnyConfig, isBunnyReady } from "@/lib/bunny"; +import { playbackUrl } from "@/lib/video"; import { Alert } from "@/components/shop/Blocks"; import { CourseOutline } from "@/components/shop/CourseOutline"; import { LessonPlayer } from "@/components/shop/LessonPlayer"; @@ -17,12 +17,12 @@ export default async function CoursePage({ params, searchParams }: { params: Pro if (!product || !isCourse(product)) notFound(); if (!(await hasCourseAccess(user.id, product.id))) redirect(`/produkt/${slug}`); - const [outline, progress, bunny] = await Promise.all([ + const [outline, progress] = await Promise.all([ getCourseOutline(product.id), db.lessonProgress.findMany({ where: { userId: user.id, lesson: { chapter: { productId: product.id } } } }), - getBunnyConfig(), ]); - const lessons = outline.flatMap((c) => c.lessons).filter((l) => l.videoStatus === "ready"); + // Abspielbar ist eine Einheit, sobald ein fertig umgewandeltes Video da ist + const lessons = outline.flatMap((c) => c.lessons).filter((l) => l.videoId); const byLesson = new Map(progress.map((p) => [p.lessonId, p])); const done = new Set(progress.filter((p) => p.completed).map((p) => p.lessonId)); // Gewählte Einheit, sonst die zuletzt angefangene, sonst die erste noch offene @@ -30,7 +30,6 @@ export default async function CoursePage({ params, searchParams }: { params: Pro const lesson = lessons.find((l) => l.id === einheit) ?? lessons.find((l) => l.id === lastStarted?.lessonId) ?? lessons.find((l) => !done.has(l.id)) ?? lessons[0]; const index = lesson ? lessons.indexOf(lesson) : -1; const next = index >= 0 ? lessons[index + 1] : undefined; - const ready = isBunnyReady(bunny); return (
@@ -45,13 +44,11 @@ export default async function CoursePage({ params, searchParams }: { params: Pro
{!lesson ? ( Dieser Kurs hat noch keine fertigen Einheiten. Schau bald wieder vorbei. - ) : !ready ? ( - Bitte versuche es später noch einmal oder melde dich bei uns. ) : ( <> }) { const { slug } = await params; @@ -47,11 +47,11 @@ export default async function ProductPage({ ]); const shippingNote = settings.appearance.trustItems[0]; const course = isCourse(product); - const [outline, owned, bunny] = course ? await Promise.all([getCourseOutline(product.id), hasCourseAccess(user?.id, product.id), getBunnyConfig()]) : [[], false, null]; + const [outline, owned] = course ? await Promise.all([getCourseOutline(product.id), hasCourseAccess(user?.id, product.id)]) : [[], false]; const allLessons = outline.flatMap((c) => c.lessons); - // Vorschau: nur Einheiten, die als Vorschau markiert und bei Bunny fertig sind - const previewLesson = vorschau ? allLessons.find((l) => l.id === vorschau && l.preview && l.videoStatus === "ready" && l.videoId) : undefined; - const previewSrc = previewLesson && bunny && isBunnyReady(bunny) ? embedUrl(bunny, previewLesson.videoId, 2) : null; + // Vorschau: nur Einheiten, die als Vorschau markiert sind und ein fertiges Video haben + const previewLesson = vorschau ? allLessons.find((l) => l.id === vorschau && l.preview && l.videoId) : undefined; + const previewSrc = previewLesson ? await playbackUrl(previewLesson.videoId, "", 2) : null; return (
diff --git a/src/app/admin/(panel)/produkte/actions.ts b/src/app/admin/(panel)/produkte/actions.ts index c3fe201..85963e2 100644 --- a/src/app/admin/(panel)/produkte/actions.ts +++ b/src/app/admin/(panel)/produkte/actions.ts @@ -8,13 +8,7 @@ import { assertPermission, audit, can } from "@/lib/auth"; import { fail, ok, type ActionResult } from "@/lib/action-result"; import { parsePrice } from "@/lib/money"; import { slugify } from "@/lib/slug"; -import { deleteBunnyVideo, getBunnyConfig } from "@/lib/bunny"; - -async function deleteVideos(ids: string[]) { - const c = await getBunnyConfig(); - if (!c.libraryId || !c.apiKey) return; - for (const id of ids) await deleteBunnyVideo(c, id).catch(() => undefined); -} +import { deleteSource, deleteVideoFiles } from "@/lib/video"; type VariantInput = { id?: string; name: string; sku: string; price: string; stock: string }; @@ -107,10 +101,13 @@ export async function deleteProduct(fd: FormData) { revalidatePath("/", "layout"); redirect(`/admin/produkte/${id}?ausgeblendet=1`); } - const lessons = await db.courseLesson.findMany({ where: { chapter: { productId: id }, videoId: { not: "" } }, select: { videoId: true } }); + const lessons = await db.courseLesson.findMany({ where: { chapter: { productId: id } }, select: { id: true, videoId: true } }); const p = await db.product.delete({ where: { id } }); - // Videos bei Bunny mit löschen, damit keine Kosten weiterlaufen - if (lessons.length) sendLater(() => deleteVideos(lessons.map((l) => l.videoId))); + // Videodateien mit löschen, damit kein Speicher belegt bleibt + for (const l of lessons) { + await deleteVideoFiles(l.videoId); + await deleteSource(l.id); + } await audit(user, "Produkt gelöscht", p.name); revalidatePath("/", "layout"); redirect("/admin/produkte"); diff --git a/src/app/admin/(panel)/produkte/kurs-actions.ts b/src/app/admin/(panel)/produkte/kurs-actions.ts index e80adfe..5cd9c92 100644 --- a/src/app/admin/(panel)/produkte/kurs-actions.ts +++ b/src/app/admin/(panel)/produkte/kurs-actions.ts @@ -4,9 +4,9 @@ import { z } from "zod"; import { db } from "@/lib/db"; import { assertPermission, audit } from "@/lib/auth"; import { fail, ok, type ActionResult } from "@/lib/action-result"; -import { createBunnyVideo, deleteBunnyVideo, getBunnyConfig, getBunnyVideo, isBunnyReady, uploadSignature, videoStatus } from "@/lib/bunny"; +import { deleteSource, deleteVideoFiles } from "@/lib/video"; -// Kursinhalt im Admin: Kapitel, Einheiten, Video-Upload zu Bunny und Zugänge. +// Kursinhalt im Admin: Kapitel, Einheiten, Videos und Zugänge. Der Upload selbst läuft über /admin/video-upload. const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim(); const who = (u: { firstName: string; lastName: string; email: string }) => [u.firstName, u.lastName].filter(Boolean).join(" ") || u.email; @@ -23,10 +23,10 @@ const refresh = (productId?: string | null) => { revalidatePath("/", "layout"); }; -async function dropVideo(videoId: string) { - if (!videoId) return; - const c = await getBunnyConfig(); - if (c.libraryId && c.apiKey) await deleteBunnyVideo(c, videoId).catch(() => undefined); +/** Video-Dateien einer Einheit vom Server löschen (fertiges Video und ein evtl. wartender Upload). */ +async function dropVideo(lesson: { id: string; videoId: string }) { + if (lesson.videoId) await deleteVideoFiles(lesson.videoId); + await deleteSource(lesson.id); } // ---------- Kapitel ---------- @@ -70,7 +70,7 @@ export async function deleteChapter(fd: FormData) { const c = await db.courseChapter.findUnique({ where: { id }, include: { lessons: true } }); if (!c) return; await db.courseChapter.delete({ where: { id } }); - for (const l of c.lessons) await dropVideo(l.videoId); + for (const l of c.lessons) await dropVideo(l); await audit(user, "Kurs-Kapitel gelöscht", c.title); refresh(c.productId); } @@ -91,15 +91,10 @@ export async function saveLesson(_prev: ActionResult, fd: FormData): Promise undefined); - } refresh(await productOfLesson(id)); return ok(); } @@ -125,60 +120,30 @@ export async function deleteLesson(fd: FormData) { const productId = await productOfLesson(id); const l = await db.courseLesson.delete({ where: { id } }).catch(() => null); if (!l) return; - await dropVideo(l.videoId); + await dropVideo(l); await audit(user, "Kurs-Einheit gelöscht", l.title); refresh(productId); } -// ---------- Video-Upload ---------- +// ---------- Video ---------- -/** Legt das Video bei Bunny an und gibt die Signatur für den direkten Upload aus dem Browser zurück. Ein altes Video wird ersetzt. */ -export async function startVideoUpload(lessonId: string) { - await assertPermission("products.edit"); - const c = await getBunnyConfig(); - if (!c.libraryId || !c.apiKey) return { ok: false as const, error: "Bunny Stream ist noch nicht eingerichtet (Verbindungen → Bunny Stream)." }; - const l = await db.courseLesson.findUnique({ where: { id: lessonId }, include: { chapter: { include: { product: { select: { name: true } } } } } }); - if (!l) return { ok: false as const, error: "Einheit nicht gefunden." }; - try { - const video = await createBunnyVideo(c, `${l.chapter.product.name} · ${l.title}`); - const old = l.videoId; - await db.courseLesson.update({ where: { id: lessonId }, data: { videoId: video.guid, videoStatus: "uploading", duration: 0 } }); - if (old) await dropVideo(old); - return { ok: true as const, ...uploadSignature(c, video.guid) }; - } catch (e) { - return { ok: false as const, error: e instanceof Error ? e.message : String(e) }; - } -} - -export async function finishVideoUpload(lessonId: string, failed: boolean) { - await assertPermission("products.edit"); - const l = await db.courseLesson.update({ where: { id: lessonId }, data: { videoStatus: failed ? "error" : "processing" } }); - refresh(await productOfLesson(l.id)); -} - -/** Fragt bei Bunny nach, welche Videos fertig umgewandelt sind, und übernimmt die Länge. */ -export async function refreshVideos(productId: string) { +/** Stand der Videos eines Kurses, für die automatische Aktualisierung im Admin. */ +export async function videoStates(productId: string) { await assertPermission("products.view"); - const c = await getBunnyConfig(); - if (!c.libraryId || !c.apiKey) return 0; - const pending = await db.courseLesson.findMany({ where: { chapter: { productId }, videoId: { not: "" }, videoStatus: { in: ["uploading", "processing"] } } }); - let changed = 0; - for (const l of pending) { - try { - const v = await getBunnyVideo(c, l.videoId); - const status = l.videoStatus === "uploading" && v.status === 0 ? "uploading" : videoStatus(v.status); - if (status !== l.videoStatus || (v.length && v.length !== l.duration)) { - await db.courseLesson.update({ where: { id: l.id }, data: { videoStatus: status, duration: Math.round(v.length || 0) } }); - changed++; - } - } catch { - // Video bei Bunny verschwunden: als Fehler markieren, damit es neu hochgeladen wird - await db.courseLesson.update({ where: { id: l.id }, data: { videoStatus: "error" } }); - changed++; - } - } - if (changed) refresh(productId); - return changed; + const lessons = await db.courseLesson.findMany({ where: { chapter: { productId } }, select: { id: true, videoStatus: true } }); + return lessons.map((l) => `${l.id}:${l.videoStatus}`).sort().join(","); +} + +/** Video einer Einheit entfernen. */ +export async function removeVideo(fd: FormData) { + const user = await assertPermission("products.edit"); + const id = str(fd, "id"); + const l = await db.courseLesson.findUnique({ where: { id } }); + if (!l || l.videoStatus === "processing") return; + await dropVideo(l); + await db.courseLesson.update({ where: { id }, data: { videoId: "", videoStatus: "none", videoError: "", duration: 0 } }); + await audit(user, "Kurs-Video entfernt", l.title); + refresh(await productOfLesson(id)); } // ---------- Zugänge ---------- diff --git a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx index d723804..d5b191f 100644 --- a/src/app/admin/(panel)/verbindungen/[provider]/page.tsx +++ b/src/app/admin/(panel)/verbindungen/[provider]/page.tsx @@ -16,8 +16,7 @@ import { StatusPill } from "@/components/admin/IntegrationStatus"; import { MailServerFields } from "@/components/admin/MailServerFields"; import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config"; import { getSettings } from "@/lib/settings"; -import { disconnect, retest, saveApple, saveBunny, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions"; -import { getBunnyConfig } from "@/lib/bunny"; +import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions"; function LastTest({ t }: { t: TestResult | null }) { if (!t) return null; @@ -300,52 +299,6 @@ async function MailWizard({ ok }: { ok: boolean }) { ); } -// ---------- Bunny Stream ---------- - -async function BunnyWizard({ ok }: { ok: boolean }) { - const c = await getBunnyConfig(); - const has = Boolean(c.libraryId && c.apiKey); - return ( - - - - -

Bunny speichert die Kursvideos und spielt sie in passender Qualität aus. Abgerechnet wird nach Verbrauch, für einen kleinen Shop meist nur wenige Euro im Monat. Die ersten 14 Tage sind kostenlos.

- Bei Bunny registrieren -
- -

Links auf „Stream“ und dann „Add Video Library“ klicken. Name z. B. „Sanamare Kurse“, bei den Regionen nur Europa wählen (Datenschutz). In der neuen Bibliothek unter „API“ steht die Video Library ID, eine Zahl.

- Stream öffnen - -
- -

Auf derselben Seite („API“) steht der API Key der Bibliothek. Damit lädt der Shop die Videos direkt aus dem Admin zu Bunny hoch.

- -
- -

In der Bibliothek unter „Security“:

-
    -
  1. Embed view token authentication einschalten. Dann spielen die Videos nur über den Shop, mit einem Link, der nach wenigen Stunden abläuft.
  2. -
  3. Den Token authentication key kopieren und unten einfügen.
  4. -
  5. Unter „Allowed referrers“ deine Shop-Adressen eintragen:
  6. -
- {siteOrigins().map((o) => )} -

Außerdem „Block direct url file access“ einschalten und unter „Player“ das Herunterladen ausschalten.

- -
- -

Mit „MediaCage Enterprise DRM“ (kostenpflichtig, unter „DRM“ in der Bibliothek) werden die Videos verschlüsselt. Bildschirmaufnahmen zeigen dann in Safari, Edge und auf den meisten Handys nur ein schwarzes Bild. Das Wasserzeichen mit der E-Mail des Kunden läuft immer, auch ohne DRM.

- -
- -

Ich prüfe Bibliothek und Schlüssel direkt bei Bunny. Danach legst du unter Produkte einen Kurs an (Art „Video-Kurs“) und lädst dort die Videos hoch.

-
-
-
-
- ); -} - const WIZARDS: Record Promise> = { stripe: StripeWizard, paypal: PaypalWizard, @@ -353,5 +306,4 @@ const WIZARDS: Record Promise String(fd.get(k) ?? "").trim(); // Leere Geheimfelder behalten den gespeicherten Wert @@ -196,28 +195,7 @@ export async function saveMail(_prev: ActionResult, fd: FormData): Promise { - const user = await assertPermission("settings.edit"); - const c = await getBunnyConfig(); - const next = { - libraryId: str(fd, "libraryId").replace(/D/g, ""), - apiKey: keep(str(fd, "apiKey"), c.apiKey), - tokenKey: keep(str(fd, "tokenKey"), c.tokenKey), - drm: fd.get("drm") === "on", - }; - if (!next.libraryId) return fail("Bitte trag die Bibliotheks-ID aus Schritt 2 ein (nur Ziffern).", { libraryId: "Bitte eintragen" }); - if (!next.apiKey) return fail("Bitte füge den API-Schlüssel aus Schritt 3 ein.", { apiKey: "Bitte einfügen" }); - const r = await testBunny(next); - // Eine funktionierende Verbindung nicht durch eine kaputte ersetzen, sonst laufen die Kurse nicht mehr. - // Bei der Ersteinrichtung trotzdem speichern, damit nichts neu eingetippt werden muss. - if (!r.ok && isBunnyReady(c)) return done({ ok: false, message: `${r.message} Nicht gespeichert, die bisherige Verbindung bleibt aktiv.` }); - await saveBunnyConfig(next); - if (!r.ok) return done(r); - await audit(user, "Bunny Stream eingerichtet", `Bibliothek ${next.libraryId}${next.drm ? ", DRM" : ""}`); - return done(r); -} - -const PERMS: Record = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit", bunny: "settings.edit" }; +const PERMS: Record = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit" }; export async function disconnect(fd: FormData) { const key = str(fd, "provider") as IntegrationKey; @@ -234,8 +212,6 @@ export async function disconnect(fd: FormData) { } else if (key === "mail") { const c = await getMailConfig(); await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false }); - } else if (key === "bunny") { - await saveBunnyConfig({ libraryId: "", apiKey: "", tokenKey: "", drm: false }); } else { const c = await getLoginProviders(); if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" }; @@ -251,6 +227,6 @@ export async function retest(_prev: ActionResult, fd: FormData): Promise Response.json({ error: message }, { status }); + +export async function POST(req: Request) { + const user = await getCurrentUser(); + if (!user || !can(user, "products.edit")) return err("Dafür fehlt dir das Recht.", 403); + const q = new URL(req.url).searchParams; + const lessonId = q.get("lesson") ?? ""; + const offset = Number(q.get("offset")); + const size = Number(q.get("size")); + if (!/^c[a-z0-9]{20,30}$/.test(lessonId)) return err("Ungültige Einheit."); + if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(size) || offset < 0 || size <= 0 || size > MAX_FILE) return err("Ungültige Angaben."); + const lesson = await db.courseLesson.findUnique({ where: { id: lessonId } }); + if (!lesson) return err("Einheit nicht gefunden.", 404); + await ensureDirs(); + const part = partPath(lessonId); + + if (lesson.videoStatus === "processing") return err("Für diese Einheit wird gerade ein Video umgewandelt. Bitte warte, bis es fertig ist.", 409); + if (offset === 0) { + // Platz prüfen: Original plus umgewandelte Fassungen brauchen grob das 2,5-Fache der Datei + const { free } = await storageInfo(); + if (free < size * 2.5) return err(`Auf dem Server ist nicht genug Platz: frei ${formatBytes(free)}, gebraucht etwa ${formatBytes(size * 2.5)}.`, 507); + await fs.rm(part, { force: true }); + } + const current = await fs.stat(part).then((s) => s.size, () => 0); + // Stück schon da (Wiederholung nach Netzfehler) oder Lücke: aktuellen Stand melden, der Browser macht dort weiter + if (offset !== current) return Response.json({ offset: current }); + + const body = Buffer.from(await req.arrayBuffer()); + if (body.length === 0 || body.length > MAX_CHUNK || offset + body.length > size) return err("Ungültiges Stück."); + await fs.appendFile(part, body); + const next = offset + body.length; + if (next < size) return Response.json({ offset: next }); + + // Fertig: zur Umwandlung einreihen. Ein vorhandenes Video bleibt abspielbar, bis das neue fertig ist. + await fs.rename(part, sourcePath(lessonId)); + await db.courseLesson.update({ where: { id: lessonId }, data: { videoStatus: "queued", videoError: "" } }); + void processNextVideo().catch(() => undefined); + return Response.json({ offset: next, done: true }); +} diff --git a/src/app/api/video/[...path]/route.ts b/src/app/api/video/[...path]/route.ts new file mode 100644 index 0000000..b5db5f2 --- /dev/null +++ b/src/app/api/video/[...path]/route.ts @@ -0,0 +1,74 @@ +import { createReadStream, promises as fs } from "node:fs"; +import path from "node:path"; +import { Readable } from "node:stream"; +import { db } from "@/lib/db"; +import { getCurrentUser } from "@/lib/auth"; +import { hasCourseAccess } from "@/lib/courses"; +import { ID, hlsDir, keyPath, verifyLink } from "@/lib/video"; + +export const dynamic = "force-dynamic"; + +// Auslieferung der Kursvideos. Jede Anfrage braucht einen gültigen, signierten Link (läuft nach Stunden ab). +// Der Schlüssel zum Entschlüsseln wird zusätzlich nur an angemeldete Käufer gegeben (oder bei Vorschau-Einheiten). +// /api/video//master.m3u8 Liste der Qualitäten +// /api/video///index.m3u8 Liste der Teile einer Qualität +// /api/video///seg_0001.ts Videoteil (verschlüsselt) +// /api/video//key Schlüssel + +const deny = (status = 403) => new Response(status === 404 ? "Nicht gefunden" : "Kein Zugriff", { status, headers: { "Cache-Control": "no-store" } }); + +export async function GET(req: Request, { params }: { params: Promise<{ path: string[] }> }) { + const parts = (await params).path; + const [videoId, ...rest] = parts; + if (!videoId || !ID.test(videoId)) return deny(404); + const q = new URL(req.url).searchParams; + const e = q.get("e") ?? ""; + const u = q.get("u") ?? ""; + const t = q.get("t") ?? ""; + if (!(await verifyLink(videoId, e, u, t))) return deny(); + const qs = new URLSearchParams({ e, u, t }).toString(); + const base = `/api/video/${videoId}`; + + // Schlüssel: nur für den Käufer, dem der Link ausgestellt wurde, oder für Vorschau-Einheiten + if (rest.length === 1 && rest[0] === "key") { + const lesson = await db.courseLesson.findFirst({ where: { videoId }, include: { chapter: { select: { productId: true } } } }); + if (!lesson) return deny(404); + if (u) { + // Nur die angemeldete Person, für die der Link ausgestellt wurde, mit Kurszugang (das Team darf zum Prüfen immer) + const user = await getCurrentUser(); + const allowed = Boolean(user && user.id === u && (user.role || (await hasCourseAccess(user.id, lesson.chapter.productId)))); + if (!allowed) return deny(); + } else if (!lesson.preview) return deny(); + const key = await fs.readFile(keyPath(videoId)).catch(() => null); + if (!key) return deny(404); + return new Response(new Uint8Array(key), { headers: { "Content-Type": "application/octet-stream", "Cache-Control": "no-store" } }); + } + + // Playlists: Verweise auf Teile und Schlüssel durch signierte Links ersetzen + if ((rest.length === 1 && rest[0] === "master.m3u8") || (rest.length === 2 && /^\d{3,4}$/.test(rest[0]) && rest[1] === "index.m3u8")) { + const file = path.join(hlsDir(videoId), ...rest); + const text = await fs.readFile(file, "utf8").catch(() => null); + if (text == null) return deny(404); + const dir = rest.length === 2 ? `${base}/${rest[0]}` : base; + const out = text + .split("\n") + .map((line) => { + if (line.startsWith("#EXT-X-KEY")) return line.replace(/URI="[^"]*"/, `URI="${base}/key?${qs}"`); + if (line && !line.startsWith("#")) return `${dir}/${line.trim()}?${qs}`; + return line; + }) + .join("\n"); + return new Response(out, { headers: { "Content-Type": "application/vnd.apple.mpegurl", "Cache-Control": "private, no-store" } }); + } + + // Videoteile + if (rest.length === 2 && /^\d{3,4}$/.test(rest[0]) && /^seg_\d{4,6}\.ts$/.test(rest[1])) { + const file = path.join(hlsDir(videoId), rest[0], rest[1]); + const stat = await fs.stat(file).catch(() => null); + if (!stat) return deny(404); + const stream = Readable.toWeb(createReadStream(file)) as ReadableStream; + return new Response(stream, { headers: { "Content-Type": "video/mp2t", "Content-Length": String(stat.size), "Cache-Control": "private, max-age=3600" } }); + } + + return deny(404); +} diff --git a/src/components/admin/CourseEditor.tsx b/src/components/admin/CourseEditor.tsx index c82abbc..146e1d1 100644 --- a/src/components/admin/CourseEditor.tsx +++ b/src/components/admin/CourseEditor.tsx @@ -1,6 +1,6 @@ import Link from "next/link"; import { db } from "@/lib/db"; -import { getBunnyConfig, isBunnyReady } from "@/lib/bunny"; +import { formatBytes, storageInfo } from "@/lib/video"; import { formatDuration } from "@/lib/courses"; import { dateFmt } from "@/lib/status"; import { Alert } from "@/components/shop/Blocks"; @@ -9,14 +9,14 @@ import { AdminForm, ConfirmButton } from "./AdminForm"; import { Card, Empty, Pill } from "./ui"; import { LessonForm } from "./LessonForm"; import { VideoStatusPoller, VideoUpload } from "./VideoUpload"; -import { addChapter, addLesson, deleteChapter, deleteLesson, grantAccess, moveChapter, moveLesson, renameChapter, revokeAccess } from "@/app/admin/(panel)/produkte/kurs-actions"; +import { addChapter, addLesson, deleteChapter, deleteLesson, grantAccess, moveChapter, moveLesson, removeVideo, renameChapter, revokeAccess } from "@/app/admin/(panel)/produkte/kurs-actions"; const STATUS: Record = { none: { tone: "neutral", label: "Kein Video" }, - uploading: { tone: "gold", label: "Wird hochgeladen" }, + queued: { tone: "gold", label: "Wartet auf Umwandlung" }, processing: { tone: "gold", label: "Wird umgewandelt" }, ready: { tone: "success", label: "Bereit" }, - error: { tone: "danger", label: "Fehler, bitte neu hochladen" }, + error: { tone: "danger", label: "Umwandlung fehlgeschlagen" }, }; function Move({ action, id, first, last }: { action: (fd: FormData) => Promise; id: string; first: boolean; last: boolean }) { @@ -30,27 +30,27 @@ function Move({ action, id, first, last }: { action: (fd: FormData) => Promise null), ]); - const ready = isBunnyReady(bunny); const lessons = chapters.flatMap((c) => c.lessons); - const pending = lessons.some((l) => l.videoStatus === "uploading" || l.videoStatus === "processing"); + const pending = lessons.some((l) => l.videoStatus === "queued" || l.videoStatus === "processing"); + const lowSpace = storage && storage.free < 5e9; const total = lessons.reduce((s, l) => s + l.duration, 0); return (
- {!ready && ( + {lowSpace && (
- - Richte zuerst unter Verbindungen → Bunny Stream die Video-Bibliothek ein. Kapitel und Einheiten kannst du schon anlegen. + + Für weitere Videos brauchst du mehr Speicher beim Server-Anbieter. Eine Stunde Video belegt umgewandelt etwa 1,5 bis 2,5 GB.
)} - + {chapters.length === 0 && } {chapters.map((c, ci) => (
@@ -79,6 +79,7 @@ export async function CourseEditor({ productId, canEdit }: { productId: string; {li + 1}. {l.title} {st.label} + {l.videoId && l.videoStatus !== "ready" && Altes Video läuft weiter} {l.duration > 0 && {formatDuration(l.duration)}} {l.preview && Vorschau} @@ -89,11 +90,16 @@ export async function CourseEditor({ productId, canEdit }: { productId: string; )}
+ {l.videoStatus === "error" && l.videoError &&

{l.videoError}

} {canEdit && ( -
+
Bearbeiten und Video - {ready && } +
+ + {l.videoId && l.videoStatus !== "processing" && } + MP4 oder MOV, gern in voller Qualität. Der Server wandelt es danach selbst um (dauert etwa so lang wie das Video). +
)}
diff --git a/src/components/admin/VideoUpload.tsx b/src/components/admin/VideoUpload.tsx index 61049de..7866c93 100644 --- a/src/components/admin/VideoUpload.tsx +++ b/src/components/admin/VideoUpload.tsx @@ -1,60 +1,39 @@ "use client"; import { useRouter } from "next/navigation"; import { useEffect, useRef, useState } from "react"; -import { finishVideoUpload, refreshVideos, startVideoUpload } from "@/app/admin/(panel)/produkte/kurs-actions"; +import { videoStates } from "@/app/admin/(panel)/produkte/kurs-actions"; -// Lädt ein Video direkt aus dem Browser zu Bunny hoch (TUS-Protokoll, in Stücken, mit Wiederholung). -// So geht die große Datei nicht über unseren Server. +// Lädt ein Video in Stücken auf den eigenen Server (/admin/video-upload). Bricht ein Stück ab, +// wird es wiederholt; der Server meldet, wo es weitergeht. Danach wandelt der Server es im Hintergrund um. -const CHUNK = 32 * 1024 * 1024; -const b64 = (s: string) => btoa(unescape(encodeURIComponent(s))); +const CHUNK = 8 * 1024 * 1024; -type Sig = { endpoint: string; libraryId: string; videoId: string; expires: number; signature: string }; +type Reply = { offset?: number; done?: boolean; error?: string }; -function send(method: string, url: string, headers: Record, body: Blob | null, onProgress?: (loaded: number) => void) { - return new Promise((resolve, reject) => { +function sendChunk(url: string, body: Blob, onProgress: (loaded: number) => void) { + return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); - xhr.open(method, url); - for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v); - if (onProgress) xhr.upload.onprogress = (e) => onProgress(e.loaded); - xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve(xhr) : reject(new Error(`HTTP ${xhr.status}`))); + xhr.open("POST", url); + xhr.setRequestHeader("Content-Type", "application/octet-stream"); + xhr.upload.onprogress = (e) => onProgress(e.loaded); + xhr.onload = () => { + let data: Reply = {}; + try { + data = JSON.parse(xhr.responseText); + } catch {} + if (xhr.status >= 200 && xhr.status < 300) resolve(data); + // Fehler, bei denen Wiederholen nichts bringt (kein Recht, kein Platz …) + else if ((xhr.status >= 400 && xhr.status < 500) || xhr.status === 507) resolve({ error: data.error ?? `Fehler ${xhr.status}` }); + else reject(new Error(data.error ?? `Fehler ${xhr.status}`)); + }; xhr.onerror = () => reject(new Error("Netzwerkfehler")); xhr.send(body); }); } -async function tusUpload(file: File, sig: Sig, onProgress: (pct: number) => void) { - const auth = { - AuthorizationSignature: sig.signature, - AuthorizationExpire: String(sig.expires), - VideoId: sig.videoId, - LibraryId: sig.libraryId, - "Tus-Resumable": "1.0.0", - }; - const created = await send("POST", sig.endpoint, { ...auth, "Upload-Length": String(file.size), "Upload-Metadata": `filetype ${b64(file.type || "video/mp4")},title ${b64(file.name)}` }, null); - const location = created.getResponseHeader("Location"); - if (!location) throw new Error("Bunny hat keine Upload-Adresse geliefert."); - const url = new URL(location, sig.endpoint).toString(); - let offset = 0; - let tries = 0; - while (offset < file.size) { - const chunk = file.slice(offset, offset + CHUNK); - try { - const res = await send("PATCH", url, { ...auth, "Upload-Offset": String(offset), "Content-Type": "application/offset+octet-stream" }, chunk, (loaded) => onProgress(((offset + loaded) / file.size) * 100)); - offset = Number(res.getResponseHeader("Upload-Offset") ?? offset + chunk.size); - tries = 0; - } catch (e) { - if (++tries > 4) throw e; - await new Promise((r) => setTimeout(r, 1500 * tries)); - // Nachfragen, wie viel schon angekommen ist, und dort weitermachen - const head = await send("HEAD", url, auth, null).catch(() => null); - offset = Number(head?.getResponseHeader("Upload-Offset") ?? offset); - } - onProgress((offset / file.size) * 100); - } -} +class FinalError extends Error {} -export function VideoUpload({ lessonId, hasVideo }: { lessonId: string; hasVideo: boolean }) { +export function VideoUpload({ lessonId, hasVideo, busy }: { lessonId: string; hasVideo: boolean; busy: boolean }) { const router = useRouter(); const input = useRef(null); const [pct, setPct] = useState(null); @@ -67,40 +46,47 @@ export function VideoUpload({ lessonId, hasVideo }: { lessonId: string; hasVideo return; } setPct(0); - const sig = await startVideoUpload(lessonId); - if (!sig.ok) { - setPct(null); - setError(sig.error); - return; - } // Seite während des Uploads nicht versehentlich verlassen const warn = (e: BeforeUnloadEvent) => e.preventDefault(); window.addEventListener("beforeunload", warn); try { - await tusUpload(file, sig, (p) => setPct(Math.min(99, Math.floor(p)))); - await finishVideoUpload(lessonId, false); + let offset = 0; + let tries = 0; + while (offset < file.size) { + const chunk = file.slice(offset, offset + CHUNK); + const url = `/admin/video-upload?${new URLSearchParams({ lesson: lessonId, offset: String(offset), size: String(file.size) })}`; + try { + const from = offset; + const r = await sendChunk(url, chunk, (loaded) => setPct(Math.min(99, Math.floor(((from + loaded) / file.size) * 100)))); + if (r.error) throw new FinalError(r.error); + offset = r.offset ?? offset + chunk.size; + tries = 0; + } catch (e) { + if (e instanceof FinalError || ++tries > 5) throw e; + await new Promise((res) => setTimeout(res, 1500 * tries)); + } + } setPct(null); router.refresh(); } catch (e) { - await finishVideoUpload(lessonId, true); setPct(null); - setError(`Upload abgebrochen: ${e instanceof Error ? e.message : e}. Bitte noch einmal versuchen.`); - router.refresh(); + setError(`Upload abgebrochen: ${e instanceof Error ? e.message : e}`); } finally { window.removeEventListener("beforeunload", warn); + if (input.current) input.current.value = ""; } }; return ( - e.target.files?.[0] && upload(e.target.files[0])} /> + e.target.files?.[0] && upload(e.target.files[0])} /> {pct !== null ? ( Lädt hoch … {pct} %. Seite bitte offen lassen. ) : ( - )} @@ -109,20 +95,22 @@ export function VideoUpload({ lessonId, hasVideo }: { lessonId: string; hasVideo ); } -/** Solange Videos bei Bunny umgewandelt werden: alle 15 Sekunden nachsehen. */ +/** Solange Videos warten oder umgewandelt werden: alle 10 Sekunden nachsehen und die Seite auffrischen, sobald sich etwas ändert. */ export function VideoStatusPoller({ productId, active }: { productId: string; active: boolean }) { const router = useRouter(); useEffect(() => { if (!active) return; let stop = false; + let last = ""; let timer: ReturnType; const tick = async () => { - const changed = await refreshVideos(productId).catch(() => 0); + const now = await videoStates(productId).catch(() => last); if (stop) return; - if (changed) router.refresh(); - timer = setTimeout(tick, 15000); + if (last && now !== last) router.refresh(); + last = now; + timer = setTimeout(tick, 10000); }; - timer = setTimeout(tick, 5000); + void tick(); return () => { stop = true; clearTimeout(timer); diff --git a/src/components/shop/CourseOutline.tsx b/src/components/shop/CourseOutline.tsx index b78fa52..755dec5 100644 --- a/src/components/shop/CourseOutline.tsx +++ b/src/components/shop/CourseOutline.tsx @@ -2,7 +2,7 @@ import Link from "next/link"; import { formatDuration } from "@/lib/courses"; import { Icon } from "../Icon"; -type Lesson = { id: string; title: string; description: string; duration: number; preview: boolean; videoStatus: string }; +type Lesson = { id: string; title: string; description: string; duration: number; preview: boolean; videoId: string }; type Chapter = { id: string; title: string; lessons: Lesson[] }; /** @@ -20,7 +20,7 @@ export function CourseOutline({ chapters, hrefFor, current, done }: { chapters:
    {c.lessons.map((l) => { n++; - const href = l.videoStatus === "ready" ? hrefFor(l) : null; + const href = l.videoId ? hrefFor(l) : null; const body = ( <> diff --git a/src/components/shop/CoursePlayer.tsx b/src/components/shop/CoursePlayer.tsx index fa45e17..3f6c7d1 100644 --- a/src/components/shop/CoursePlayer.tsx +++ b/src/components/shop/CoursePlayer.tsx @@ -1,8 +1,8 @@ "use client"; import { useEffect, useRef, useState } from "react"; -// Bunny-Player im iframe. Gesteuert über das player.js-Protokoll (postMessage), das der Bunny-Player spricht. -// Das Vollbild läuft über unseren Rahmen, damit das Wasserzeichen auch dort über dem Video liegt. +// Player für die Kursvideos vom eigenen Server (HLS, verschlüsselt). Safari spielt HLS selbst, +// alle anderen Browser über hls.js. Vollbild läuft über unseren Rahmen, damit das Wasserzeichen sichtbar bleibt. type Props = { src: string; @@ -16,10 +16,11 @@ type Props = { const SAVE_EVERY = 15; export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }: Props) { - const frame = useRef(null); + const video = useRef(null); const box = useRef(null); const [pos, setPos] = useState({ x: 8, y: 10 }); const [full, setFull] = useState(false); + const [error, setError] = useState(""); const lastSaved = useRef(0); const report = useRef(onProgress); report.current = onProgress; @@ -39,41 +40,56 @@ export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }: return () => document.removeEventListener("fullscreenchange", onFs); }, []); - // player.js: auf "ready" warten, dann Zeit-Ereignisse abonnieren und ggf. an die letzte Stelle springen + // Video laden useEffect(() => { - const target = () => frame.current?.contentWindow; - const send = (method: string, value?: unknown) => target()?.postMessage(JSON.stringify({ context: "player.js", version: "0.0.11", method, value }), "*"); - let jumped = false; - const onMessage = (e: MessageEvent) => { - if (e.source !== target()) return; - let data: { context?: string; event?: string; value?: { seconds?: number; duration?: number } }; - try { - data = typeof e.data === "string" ? JSON.parse(e.data) : e.data; - } catch { - return; - } - if (data?.context !== "player.js") return; - if (data.event === "ready") { - send("addEventListener", "timeupdate"); - send("addEventListener", "ended"); - if (startAt > 5 && !jumped) { - jumped = true; - send("setCurrentTime", startAt); - } - } else if (data.event === "timeupdate" && data.value?.seconds != null) { - const s = Math.floor(data.value.seconds); - if (Math.abs(s - lastSaved.current) >= SAVE_EVERY) { - lastSaved.current = s; - report.current?.(s, Math.floor(data.value.duration ?? 0), false); - } - } else if (data.event === "ended") { - report.current?.(0, 0, true); - } + const el = video.current; + if (!el) return; + setError(""); + let destroy = () => {}; + let cancelled = false; + const jump = () => { + if (startAt > 5 && el.duration && startAt < el.duration - 5) el.currentTime = startAt; + }; + el.addEventListener("loadedmetadata", jump, { once: true }); + if (el.canPlayType("application/vnd.apple.mpegurl")) { + el.src = src; + } else { + void import("hls.js").then(({ default: Hls }) => { + if (cancelled) return; + if (!Hls.isSupported()) { + setError("Dieser Browser kann das Video leider nicht abspielen. Bitte nutze einen aktuellen Browser."); + return; + } + const hls = new Hls({ capLevelToPlayerSize: true }); + hls.on(Hls.Events.ERROR, (_e, data) => { + if (!data.fatal) return; + if (data.type === Hls.ErrorTypes.NETWORK_ERROR) setError("Das Video lädt nicht. Ist die Seite schon länger offen? Dann bitte neu laden."); + else hls.recoverMediaError(); + }); + hls.loadSource(src); + hls.attachMedia(el); + destroy = () => hls.destroy(); + }); + } + return () => { + cancelled = true; + el.removeEventListener("loadedmetadata", jump); + destroy(); + el.removeAttribute("src"); + el.load(); }; - window.addEventListener("message", onMessage); - return () => window.removeEventListener("message", onMessage); }, [src, startAt]); + const onTime = () => { + const el = video.current; + if (!el) return; + const s = Math.floor(el.currentTime); + if (Math.abs(s - lastSaved.current) >= SAVE_EVERY) { + lastSaved.current = s; + report.current?.(s, Math.floor(el.duration || 0), false); + } + }; + const toggleFull = () => { if (document.fullscreenElement) void document.exitFullscreen(); else void box.current?.requestFullscreen?.(); @@ -81,14 +97,18 @@ export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }: return (
    e.preventDefault()}> -