Kursvideos auf dem eigenen Server statt Bunny: Upload, Umwandlung zu verschlüsseltem HLS, geschützte Auslieferung
- Upload im Admin in 8-MB-Stücken direkt auf den Server (mit Wiederholung), Platzprüfung vorher - Umwandlung im Hintergrund mit ffmpeg (480p/720p/1080p, nie hochskaliert, Hochformat berücksichtigt), AES-128-verschlüsselte Segmente, immer nur ein Video gleichzeitig, niedrige Priorität; Original wird danach gelöscht - Auslieferung nur über /api/video mit signierten, nach Stunden ablaufenden Links; den Schlüssel bekommt nur der angemeldete Käufer (oder jeder bei Vorschau-Einheiten); keine Original-Datei abrufbar - Player mit <video> und hls.js (vom eigenen Server), Wasserzeichen, eigenes Vollbild, kein Download/Bild-im-Bild - Admin: Status "wartet / wird umgewandelt / bereit / Fehler" mit Fehlertext, belegter und freier Speicher, Video löschen; altes Video bleibt abspielbar, bis das neue fertig ist - Bunny-Assistent und -Code entfernt; neues Docker-Volume "videos", ffmpeg im Image Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
b3bc1ef596
commit
2fcbe88304
25 changed files with 548 additions and 407 deletions
|
|
@ -3,3 +3,4 @@ node_modules
|
||||||
.env
|
.env
|
||||||
uploads
|
uploads
|
||||||
.git
|
.git
|
||||||
|
videos
|
||||||
|
|
|
||||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -5,3 +5,4 @@ uploads/*
|
||||||
!uploads/.gitkeep
|
!uploads/.gitkeep
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
next-env.d.ts
|
next-env.d.ts
|
||||||
|
videos/
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,9 @@ RUN npx prisma generate && npm run build
|
||||||
|
|
||||||
FROM node:22-alpine AS run
|
FROM node:22-alpine AS run
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
RUN apk add --no-cache openssl && addgroup -S app && adduser -S app -G app
|
# ffmpeg wandelt die Kursvideos in HLS um
|
||||||
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0 UPLOAD_DIR=/app/uploads
|
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/standalone ./
|
||||||
COPY --from=build /app/.next/static ./.next/static
|
COPY --from=build /app/.next/static ./.next/static
|
||||||
COPY --from=build /app/public ./public
|
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=build /app/src/lib/payments/catalog.ts ./src/lib/payments/catalog.ts
|
||||||
COPY --from=deps /app/node_modules ./node_modules
|
COPY --from=deps /app/node_modules ./node_modules
|
||||||
COPY docker/entrypoint.sh /entrypoint.sh
|
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
|
USER app
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
ENTRYPOINT ["/entrypoint.sh"]
|
ENTRYPOINT ["/entrypoint.sh"]
|
||||||
|
|
|
||||||
|
|
@ -29,9 +29,12 @@ services:
|
||||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD in .env setzen}
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?ADMIN_PASSWORD in .env setzen}
|
||||||
volumes:
|
volumes:
|
||||||
- uploads:/app/uploads
|
- uploads:/app/uploads
|
||||||
|
# Kursvideos (umgewandelt und verschlüsselt), nie direkt erreichbar
|
||||||
|
- videos:/app/videos
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:3000:3000"
|
- "127.0.0.1:3000:3000"
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
db:
|
db:
|
||||||
uploads:
|
uploads:
|
||||||
|
videos:
|
||||||
|
|
|
||||||
7
package-lock.json
generated
7
package-lock.json
generated
|
|
@ -12,6 +12,7 @@
|
||||||
"@fontsource/jost": "^5.3.0",
|
"@fontsource/jost": "^5.3.0",
|
||||||
"@prisma/client": "6.19.3",
|
"@prisma/client": "6.19.3",
|
||||||
"bcryptjs": "3.0.3",
|
"bcryptjs": "3.0.3",
|
||||||
|
"hls.js": "1.7.3",
|
||||||
"next": "15.5.28",
|
"next": "15.5.28",
|
||||||
"react": "19.1.10",
|
"react": "19.1.10",
|
||||||
"react-dom": "19.1.10",
|
"react-dom": "19.1.10",
|
||||||
|
|
@ -1563,6 +1564,12 @@
|
||||||
"giget": "dist/cli.mjs"
|
"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": {
|
"node_modules/jiti": {
|
||||||
"version": "2.7.0",
|
"version": "2.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
|
||||||
|
|
|
||||||
|
|
@ -20,6 +20,7 @@
|
||||||
"@fontsource/jost": "^5.3.0",
|
"@fontsource/jost": "^5.3.0",
|
||||||
"@prisma/client": "6.19.3",
|
"@prisma/client": "6.19.3",
|
||||||
"bcryptjs": "3.0.3",
|
"bcryptjs": "3.0.3",
|
||||||
|
"hls.js": "1.7.3",
|
||||||
"next": "15.5.28",
|
"next": "15.5.28",
|
||||||
"react": "19.1.10",
|
"react": "19.1.10",
|
||||||
"react-dom": "19.1.10",
|
"react-dom": "19.1.10",
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "CourseLesson" ADD COLUMN "videoError" TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
|
@ -157,10 +157,11 @@ model CourseLesson {
|
||||||
chapter CourseChapter @relation(fields: [chapterId], references: [id], onDelete: Cascade)
|
chapter CourseChapter @relation(fields: [chapterId], references: [id], onDelete: Cascade)
|
||||||
title String
|
title String
|
||||||
description String @default("")
|
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("")
|
videoId String @default("")
|
||||||
// "none", "uploading", "processing", "ready", "error"
|
// Stand des letzten Uploads: "none", "queued", "processing", "ready", "error"
|
||||||
videoStatus String @default("none")
|
videoStatus String @default("none")
|
||||||
|
videoError String @default("")
|
||||||
// Länge in Sekunden
|
// Länge in Sekunden
|
||||||
duration Int @default(0)
|
duration Int @default(0)
|
||||||
// Kostenlose Vorschau auf der Produktseite
|
// Kostenlose Vorschau auf der Produktseite
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ import { notFound, redirect } from "next/navigation";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getCurrentUser } from "@/lib/auth";
|
import { getCurrentUser } from "@/lib/auth";
|
||||||
import { getCourseOutline, hasCourseAccess, isCourse } from "@/lib/courses";
|
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 { Alert } from "@/components/shop/Blocks";
|
||||||
import { CourseOutline } from "@/components/shop/CourseOutline";
|
import { CourseOutline } from "@/components/shop/CourseOutline";
|
||||||
import { LessonPlayer } from "@/components/shop/LessonPlayer";
|
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 (!product || !isCourse(product)) notFound();
|
||||||
if (!(await hasCourseAccess(user.id, product.id))) redirect(`/produkt/${slug}`);
|
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),
|
getCourseOutline(product.id),
|
||||||
db.lessonProgress.findMany({ where: { userId: user.id, lesson: { chapter: { productId: 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 byLesson = new Map(progress.map((p) => [p.lessonId, p]));
|
||||||
const done = new Set(progress.filter((p) => p.completed).map((p) => p.lessonId));
|
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
|
// 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 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 index = lesson ? lessons.indexOf(lesson) : -1;
|
||||||
const next = index >= 0 ? lessons[index + 1] : undefined;
|
const next = index >= 0 ? lessons[index + 1] : undefined;
|
||||||
const ready = isBunnyReady(bunny);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="sm-container sm-page sm-lesson">
|
<main className="sm-container sm-page sm-lesson">
|
||||||
|
|
@ -45,13 +44,11 @@ export default async function CoursePage({ params, searchParams }: { params: Pro
|
||||||
<div>
|
<div>
|
||||||
{!lesson ? (
|
{!lesson ? (
|
||||||
<Alert title="Hier kommen bald die Videos.">Dieser Kurs hat noch keine fertigen Einheiten. Schau bald wieder vorbei.</Alert>
|
<Alert title="Hier kommen bald die Videos.">Dieser Kurs hat noch keine fertigen Einheiten. Schau bald wieder vorbei.</Alert>
|
||||||
) : !ready ? (
|
|
||||||
<Alert kind="danger" title="Die Videos sind gerade nicht erreichbar.">Bitte versuche es später noch einmal oder melde dich bei uns.</Alert>
|
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<LessonPlayer
|
<LessonPlayer
|
||||||
lessonId={lesson.id}
|
lessonId={lesson.id}
|
||||||
src={embedUrl(bunny, lesson.videoId)}
|
src={await playbackUrl(lesson.videoId, user.id)}
|
||||||
title={lesson.title}
|
title={lesson.title}
|
||||||
email={user.email}
|
email={user.email}
|
||||||
startAt={byLesson.get(lesson.id)?.completed ? 0 : (byLesson.get(lesson.id)?.position ?? 0)}
|
startAt={byLesson.get(lesson.id)?.completed ? 0 : (byLesson.get(lesson.id)?.position ?? 0)}
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ import { CourseBuyBox } from "@/components/shop/CourseBuyBox";
|
||||||
import { CourseOutline } from "@/components/shop/CourseOutline";
|
import { CourseOutline } from "@/components/shop/CourseOutline";
|
||||||
import { CoursePlayer } from "@/components/shop/CoursePlayer";
|
import { CoursePlayer } from "@/components/shop/CoursePlayer";
|
||||||
import { getCourseOutline, hasCourseAccess, isCourse } from "@/lib/courses";
|
import { getCourseOutline, hasCourseAccess, isCourse } from "@/lib/courses";
|
||||||
import { embedUrl, getBunnyConfig, isBunnyReady } from "@/lib/bunny";
|
import { playbackUrl } from "@/lib/video";
|
||||||
|
|
||||||
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
|
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
|
||||||
const { slug } = await params;
|
const { slug } = await params;
|
||||||
|
|
@ -47,11 +47,11 @@ export default async function ProductPage({
|
||||||
]);
|
]);
|
||||||
const shippingNote = settings.appearance.trustItems[0];
|
const shippingNote = settings.appearance.trustItems[0];
|
||||||
const course = isCourse(product);
|
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);
|
const allLessons = outline.flatMap((c) => c.lessons);
|
||||||
// Vorschau: nur Einheiten, die als Vorschau markiert und bei Bunny fertig sind
|
// 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.videoStatus === "ready" && l.videoId) : undefined;
|
const previewLesson = vorschau ? allLessons.find((l) => l.id === vorschau && l.preview && l.videoId) : undefined;
|
||||||
const previewSrc = previewLesson && bunny && isBunnyReady(bunny) ? embedUrl(bunny, previewLesson.videoId, 2) : null;
|
const previewSrc = previewLesson ? await playbackUrl(previewLesson.videoId, "", 2) : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="sm-container" style={{ paddingTop: "var(--space-5)", paddingBottom: "var(--space-9)" }}>
|
<main className="sm-container" style={{ paddingTop: "var(--space-5)", paddingBottom: "var(--space-9)" }}>
|
||||||
|
|
|
||||||
|
|
@ -8,13 +8,7 @@ import { assertPermission, audit, can } from "@/lib/auth";
|
||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
import { parsePrice } from "@/lib/money";
|
import { parsePrice } from "@/lib/money";
|
||||||
import { slugify } from "@/lib/slug";
|
import { slugify } from "@/lib/slug";
|
||||||
import { deleteBunnyVideo, getBunnyConfig } from "@/lib/bunny";
|
import { deleteSource, deleteVideoFiles } from "@/lib/video";
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
type VariantInput = { id?: string; name: string; sku: string; price: string; stock: string };
|
type VariantInput = { id?: string; name: string; sku: string; price: string; stock: string };
|
||||||
|
|
||||||
|
|
@ -107,10 +101,13 @@ export async function deleteProduct(fd: FormData) {
|
||||||
revalidatePath("/", "layout");
|
revalidatePath("/", "layout");
|
||||||
redirect(`/admin/produkte/${id}?ausgeblendet=1`);
|
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 } });
|
const p = await db.product.delete({ where: { id } });
|
||||||
// Videos bei Bunny mit löschen, damit keine Kosten weiterlaufen
|
// Videodateien mit löschen, damit kein Speicher belegt bleibt
|
||||||
if (lessons.length) sendLater(() => deleteVideos(lessons.map((l) => l.videoId)));
|
for (const l of lessons) {
|
||||||
|
await deleteVideoFiles(l.videoId);
|
||||||
|
await deleteSource(l.id);
|
||||||
|
}
|
||||||
await audit(user, "Produkt gelöscht", p.name);
|
await audit(user, "Produkt gelöscht", p.name);
|
||||||
revalidatePath("/", "layout");
|
revalidatePath("/", "layout");
|
||||||
redirect("/admin/produkte");
|
redirect("/admin/produkte");
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,9 @@ import { z } from "zod";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { assertPermission, audit } from "@/lib/auth";
|
import { assertPermission, audit } from "@/lib/auth";
|
||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
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 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;
|
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");
|
revalidatePath("/", "layout");
|
||||||
};
|
};
|
||||||
|
|
||||||
async function dropVideo(videoId: string) {
|
/** Video-Dateien einer Einheit vom Server löschen (fertiges Video und ein evtl. wartender Upload). */
|
||||||
if (!videoId) return;
|
async function dropVideo(lesson: { id: string; videoId: string }) {
|
||||||
const c = await getBunnyConfig();
|
if (lesson.videoId) await deleteVideoFiles(lesson.videoId);
|
||||||
if (c.libraryId && c.apiKey) await deleteBunnyVideo(c, videoId).catch(() => undefined);
|
await deleteSource(lesson.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Kapitel ----------
|
// ---------- Kapitel ----------
|
||||||
|
|
@ -70,7 +70,7 @@ export async function deleteChapter(fd: FormData) {
|
||||||
const c = await db.courseChapter.findUnique({ where: { id }, include: { lessons: true } });
|
const c = await db.courseChapter.findUnique({ where: { id }, include: { lessons: true } });
|
||||||
if (!c) return;
|
if (!c) return;
|
||||||
await db.courseChapter.delete({ where: { id } });
|
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);
|
await audit(user, "Kurs-Kapitel gelöscht", c.title);
|
||||||
refresh(c.productId);
|
refresh(c.productId);
|
||||||
}
|
}
|
||||||
|
|
@ -91,15 +91,10 @@ export async function saveLesson(_prev: ActionResult, fd: FormData): Promise<Act
|
||||||
const id = str(fd, "id");
|
const id = str(fd, "id");
|
||||||
const title = str(fd, "title");
|
const title = str(fd, "title");
|
||||||
if (!title) return fail("Bitte gib der Einheit einen Titel.", { title: "Bitte eintragen" });
|
if (!title) return fail("Bitte gib der Einheit einen Titel.", { title: "Bitte eintragen" });
|
||||||
const l = await db.courseLesson.update({
|
await db.courseLesson.update({
|
||||||
where: { id },
|
where: { id },
|
||||||
data: { title, description: String(fd.get("description") ?? "").trim(), preview: fd.get("preview") === "on" },
|
data: { title, description: String(fd.get("description") ?? "").trim(), preview: fd.get("preview") === "on" },
|
||||||
});
|
});
|
||||||
if (l.videoId) {
|
|
||||||
// Titel bei Bunny mitziehen, damit man die Videos dort wiederfindet (Fehler egal)
|
|
||||||
const c = await getBunnyConfig();
|
|
||||||
if (isBunnyReady(c)) void fetch(`https://video.bunnycdn.com/library/${c.libraryId}/videos/${l.videoId}`, { method: "POST", headers: { AccessKey: c.apiKey, "Content-Type": "application/json" }, body: JSON.stringify({ title }) }).catch(() => undefined);
|
|
||||||
}
|
|
||||||
refresh(await productOfLesson(id));
|
refresh(await productOfLesson(id));
|
||||||
return ok();
|
return ok();
|
||||||
}
|
}
|
||||||
|
|
@ -125,60 +120,30 @@ export async function deleteLesson(fd: FormData) {
|
||||||
const productId = await productOfLesson(id);
|
const productId = await productOfLesson(id);
|
||||||
const l = await db.courseLesson.delete({ where: { id } }).catch(() => null);
|
const l = await db.courseLesson.delete({ where: { id } }).catch(() => null);
|
||||||
if (!l) return;
|
if (!l) return;
|
||||||
await dropVideo(l.videoId);
|
await dropVideo(l);
|
||||||
await audit(user, "Kurs-Einheit gelöscht", l.title);
|
await audit(user, "Kurs-Einheit gelöscht", l.title);
|
||||||
refresh(productId);
|
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. */
|
/** Stand der Videos eines Kurses, für die automatische Aktualisierung im Admin. */
|
||||||
export async function startVideoUpload(lessonId: string) {
|
export async function videoStates(productId: 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) {
|
|
||||||
await assertPermission("products.view");
|
await assertPermission("products.view");
|
||||||
const c = await getBunnyConfig();
|
const lessons = await db.courseLesson.findMany({ where: { chapter: { productId } }, select: { id: true, videoStatus: true } });
|
||||||
if (!c.libraryId || !c.apiKey) return 0;
|
return lessons.map((l) => `${l.id}:${l.videoStatus}`).sort().join(",");
|
||||||
const pending = await db.courseLesson.findMany({ where: { chapter: { productId }, videoId: { not: "" }, videoStatus: { in: ["uploading", "processing"] } } });
|
}
|
||||||
let changed = 0;
|
|
||||||
for (const l of pending) {
|
/** Video einer Einheit entfernen. */
|
||||||
try {
|
export async function removeVideo(fd: FormData) {
|
||||||
const v = await getBunnyVideo(c, l.videoId);
|
const user = await assertPermission("products.edit");
|
||||||
const status = l.videoStatus === "uploading" && v.status === 0 ? "uploading" : videoStatus(v.status);
|
const id = str(fd, "id");
|
||||||
if (status !== l.videoStatus || (v.length && v.length !== l.duration)) {
|
const l = await db.courseLesson.findUnique({ where: { id } });
|
||||||
await db.courseLesson.update({ where: { id: l.id }, data: { videoStatus: status, duration: Math.round(v.length || 0) } });
|
if (!l || l.videoStatus === "processing") return;
|
||||||
changed++;
|
await dropVideo(l);
|
||||||
}
|
await db.courseLesson.update({ where: { id }, data: { videoId: "", videoStatus: "none", videoError: "", duration: 0 } });
|
||||||
} catch {
|
await audit(user, "Kurs-Video entfernt", l.title);
|
||||||
// Video bei Bunny verschwunden: als Fehler markieren, damit es neu hochgeladen wird
|
refresh(await productOfLesson(id));
|
||||||
await db.courseLesson.update({ where: { id: l.id }, data: { videoStatus: "error" } });
|
|
||||||
changed++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (changed) refresh(productId);
|
|
||||||
return changed;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Zugänge ----------
|
// ---------- Zugänge ----------
|
||||||
|
|
|
||||||
|
|
@ -16,8 +16,7 @@ import { StatusPill } from "@/components/admin/IntegrationStatus";
|
||||||
import { MailServerFields } from "@/components/admin/MailServerFields";
|
import { MailServerFields } from "@/components/admin/MailServerFields";
|
||||||
import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config";
|
import { MAIL_PRESETS, getMailConfig } from "@/lib/mail/config";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { disconnect, retest, saveApple, saveBunny, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions";
|
import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, saveMail, savePaypal, saveStripe } from "../actions";
|
||||||
import { getBunnyConfig } from "@/lib/bunny";
|
|
||||||
|
|
||||||
function LastTest({ t }: { t: TestResult | null }) {
|
function LastTest({ t }: { t: TestResult | null }) {
|
||||||
if (!t) return 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 (
|
|
||||||
<AdminForm action={saveBunny} submitLabel="Speichern und testen">
|
|
||||||
<Card>
|
|
||||||
<Steps>
|
|
||||||
<Step n={1} title="Bunny-Konto anlegen" done={ok && has}>
|
|
||||||
<p>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.</p>
|
|
||||||
<OpenLink href="https://dash.bunny.net/auth/register">Bei Bunny registrieren</OpenLink>
|
|
||||||
</Step>
|
|
||||||
<Step n={2} title="Video-Bibliothek anlegen" done={ok && has}>
|
|
||||||
<p>Links auf „Stream“ und dann „Add Video Library“ klicken. Name z. B. „Sanamare Kurse“, bei den Regionen nur <strong>Europa</strong> wählen (Datenschutz). In der neuen Bibliothek unter „API“ steht die <strong>Video Library ID</strong>, eine Zahl.</p>
|
|
||||||
<OpenLink href="https://dash.bunny.net/stream">Stream öffnen</OpenLink>
|
|
||||||
<Field label="Bibliotheks-ID" name="libraryId" defaultValue={c.libraryId} inputMode="numeric" placeholder="z. B. 123456" autoComplete="off" />
|
|
||||||
</Step>
|
|
||||||
<Step n={3} title="API-Schlüssel kopieren" done={ok && has}>
|
|
||||||
<p>Auf derselben Seite („API“) steht der <strong>API Key</strong> der Bibliothek. Damit lädt der Shop die Videos direkt aus dem Admin zu Bunny hoch.</p>
|
|
||||||
<Field label="API-Schlüssel" name="apiKey" type="password" autoComplete="off" placeholder={c.apiKey ? mask(c.apiKey) : ""} hint={c.apiKey ? "Gespeichert. Nur ausfüllen, wenn du ihn ersetzen willst." : undefined} />
|
|
||||||
</Step>
|
|
||||||
<Step n={4} title="Videos schützen" done={ok && Boolean(c.tokenKey)}>
|
|
||||||
<p>In der Bibliothek unter „Security“:</p>
|
|
||||||
<ol>
|
|
||||||
<li><strong>Embed view token authentication</strong> einschalten. Dann spielen die Videos nur über den Shop, mit einem Link, der nach wenigen Stunden abläuft.</li>
|
|
||||||
<li>Den <strong>Token authentication key</strong> kopieren und unten einfügen.</li>
|
|
||||||
<li>Unter „Allowed referrers“ deine Shop-Adressen eintragen:</li>
|
|
||||||
</ol>
|
|
||||||
{siteOrigins().map((o) => <CopyValue key={o} label="Erlaubte Domain" value={new URL(o).host} />)}
|
|
||||||
<p>Außerdem „Block direct url file access“ einschalten und unter „Player“ das Herunterladen ausschalten.</p>
|
|
||||||
<Field label="Token-Schlüssel" name="tokenKey" type="password" autoComplete="off" placeholder={c.tokenKey ? mask(c.tokenKey) : ""} hint={c.tokenKey ? "Gespeichert. Nur ausfüllen, wenn du ihn ersetzen willst." : undefined} />
|
|
||||||
</Step>
|
|
||||||
<Step n={5} title="Optional: DRM gegen Bildschirmaufnahmen">
|
|
||||||
<p>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.</p>
|
|
||||||
<Switch name="drm" label="DRM ist bei Bunny gebucht und für die Bibliothek eingeschaltet" hint="Nur zur Anzeige im Admin. Verschlüsselt wird bei Bunny, sobald du DRM dort einschaltest." defaultChecked={c.drm} />
|
|
||||||
</Step>
|
|
||||||
<Step n={6} title="Speichern und testen">
|
|
||||||
<p>Ich prüfe Bibliothek und Schlüssel direkt bei Bunny. Danach legst du unter <a href="/admin/produkte/neu">Produkte</a> einen Kurs an (Art „Video-Kurs“) und lädst dort die Videos hoch.</p>
|
|
||||||
</Step>
|
|
||||||
</Steps>
|
|
||||||
</Card>
|
|
||||||
</AdminForm>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.ReactElement>> = {
|
const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.ReactElement>> = {
|
||||||
stripe: StripeWizard,
|
stripe: StripeWizard,
|
||||||
paypal: PaypalWizard,
|
paypal: PaypalWizard,
|
||||||
|
|
@ -353,5 +306,4 @@ const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.Reac
|
||||||
google: GoogleWizard,
|
google: GoogleWizard,
|
||||||
apple: AppleWizard,
|
apple: AppleWizard,
|
||||||
mail: MailWizard,
|
mail: MailWizard,
|
||||||
bunny: BunnyWizard,
|
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -7,10 +7,9 @@ import { getDhlConfig, saveDhlConfig, splitStreet } from "@/lib/dhl";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { getLoginProviders, saveLoginProviders } from "@/lib/social/config";
|
import { getLoginProviders, saveLoginProviders } from "@/lib/social/config";
|
||||||
import { isValidApplePrivateKey } from "@/lib/social/oauth";
|
import { isValidApplePrivateKey } from "@/lib/social/oauth";
|
||||||
import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testBunny, testDhlConnection, testLogin, testMail, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations";
|
import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testDhlConnection, testLogin, testMail, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations";
|
||||||
import { getMailConfig, saveMailConfig, type MailConfig } from "@/lib/mail/config";
|
import { getMailConfig, saveMailConfig, type MailConfig } from "@/lib/mail/config";
|
||||||
import { sendTestMail } from "@/lib/mail/send";
|
import { sendTestMail } from "@/lib/mail/send";
|
||||||
import { getBunnyConfig, isBunnyReady, saveBunnyConfig } from "@/lib/bunny";
|
|
||||||
|
|
||||||
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
||||||
// Leere Geheimfelder behalten den gespeicherten Wert
|
// Leere Geheimfelder behalten den gespeicherten Wert
|
||||||
|
|
@ -196,28 +195,7 @@ export async function saveMail(_prev: ActionResult, fd: FormData): Promise<Actio
|
||||||
return done({ ok: true, message: `Testmail an ${user.email} verschickt. Schau in dein Postfach (auch im Spam-Ordner).${next.enabled ? "" : " Der Versand an Kunden ist noch ausgeschaltet."}` });
|
return done({ ok: true, message: `Testmail an ${user.email} verschickt. Schau in dein Postfach (auch im Spam-Ordner).${next.enabled ? "" : " Der Versand an Kunden ist noch ausgeschaltet."}` });
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveBunny(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
const PERMS: Record<IntegrationKey, "payments.edit" | "shipping.edit" | "settings.edit" | "emails.edit"> = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit" };
|
||||||
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<IntegrationKey, "payments.edit" | "shipping.edit" | "settings.edit" | "emails.edit"> = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit", mail: "emails.edit", bunny: "settings.edit" };
|
|
||||||
|
|
||||||
export async function disconnect(fd: FormData) {
|
export async function disconnect(fd: FormData) {
|
||||||
const key = str(fd, "provider") as IntegrationKey;
|
const key = str(fd, "provider") as IntegrationKey;
|
||||||
|
|
@ -234,8 +212,6 @@ export async function disconnect(fd: FormData) {
|
||||||
} else if (key === "mail") {
|
} else if (key === "mail") {
|
||||||
const c = await getMailConfig();
|
const c = await getMailConfig();
|
||||||
await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false });
|
await saveMailConfig({ ...c, host: "", user: "", password: "", enabled: false });
|
||||||
} else if (key === "bunny") {
|
|
||||||
await saveBunnyConfig({ libraryId: "", apiKey: "", tokenKey: "", drm: false });
|
|
||||||
} else {
|
} else {
|
||||||
const c = await getLoginProviders();
|
const c = await getLoginProviders();
|
||||||
if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" };
|
if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" };
|
||||||
|
|
@ -251,6 +227,6 @@ export async function retest(_prev: ActionResult, fd: FormData): Promise<ActionR
|
||||||
const key = str(fd, "provider") as IntegrationKey;
|
const key = str(fd, "provider") as IntegrationKey;
|
||||||
if (!(key in PERMS)) return fail("Unbekannter Anbieter.");
|
if (!(key in PERMS)) return fail("Unbekannter Anbieter.");
|
||||||
await assertPermission(PERMS[key]);
|
await assertPermission(PERMS[key]);
|
||||||
const r = key === "stripe" ? await testStripe() : key === "paypal" ? await testPaypal() : key === "dhl" ? await testDhlConnection() : key === "mail" ? await testMail() : key === "bunny" ? await testBunny() : await testLogin(key);
|
const r = key === "stripe" ? await testStripe() : key === "paypal" ? await testPaypal() : key === "dhl" ? await testDhlConnection() : key === "mail" ? await testMail() : await testLogin(key);
|
||||||
return done(r);
|
return done(r);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
52
src/app/admin/video-upload/route.ts
Normal file
52
src/app/admin/video-upload/route.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import { db } from "@/lib/db";
|
||||||
|
import { can, getCurrentUser } from "@/lib/auth";
|
||||||
|
import { ensureDirs, partPath, processNextVideo, sourcePath, storageInfo, formatBytes } from "@/lib/video";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
// Video-Upload in Stücken: der Browser schickt die Datei der Reihe nach, jedes Stück mit seiner Position.
|
||||||
|
// So klappen auch Dateien mit mehreren GB, und ein abgebrochenes Stück wird einfach neu geschickt.
|
||||||
|
|
||||||
|
const MAX_CHUNK = 16 * 1024 * 1024;
|
||||||
|
const MAX_FILE = 20 * 1024 * 1024 * 1024;
|
||||||
|
|
||||||
|
const err = (message: string, status = 400) => 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 });
|
||||||
|
}
|
||||||
74
src/app/api/video/[...path]/route.ts
Normal file
74
src/app/api/video/[...path]/route.ts
Normal file
|
|
@ -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/<id>/master.m3u8 Liste der Qualitäten
|
||||||
|
// /api/video/<id>/<h>/index.m3u8 Liste der Teile einer Qualität
|
||||||
|
// /api/video/<id>/<h>/seg_0001.ts Videoteil (verschlüsselt)
|
||||||
|
// /api/video/<id>/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);
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { db } from "@/lib/db";
|
import { db } from "@/lib/db";
|
||||||
import { getBunnyConfig, isBunnyReady } from "@/lib/bunny";
|
import { formatBytes, storageInfo } from "@/lib/video";
|
||||||
import { formatDuration } from "@/lib/courses";
|
import { formatDuration } from "@/lib/courses";
|
||||||
import { dateFmt } from "@/lib/status";
|
import { dateFmt } from "@/lib/status";
|
||||||
import { Alert } from "@/components/shop/Blocks";
|
import { Alert } from "@/components/shop/Blocks";
|
||||||
|
|
@ -9,14 +9,14 @@ import { AdminForm, ConfirmButton } from "./AdminForm";
|
||||||
import { Card, Empty, Pill } from "./ui";
|
import { Card, Empty, Pill } from "./ui";
|
||||||
import { LessonForm } from "./LessonForm";
|
import { LessonForm } from "./LessonForm";
|
||||||
import { VideoStatusPoller, VideoUpload } from "./VideoUpload";
|
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<string, { tone: "neutral" | "gold" | "success" | "danger"; label: string }> = {
|
const STATUS: Record<string, { tone: "neutral" | "gold" | "success" | "danger"; label: string }> = {
|
||||||
none: { tone: "neutral", label: "Kein Video" },
|
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" },
|
processing: { tone: "gold", label: "Wird umgewandelt" },
|
||||||
ready: { tone: "success", label: "Bereit" },
|
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<void>; id: string; first: boolean; last: boolean }) {
|
function Move({ action, id, first, last }: { action: (fd: FormData) => Promise<void>; id: string; first: boolean; last: boolean }) {
|
||||||
|
|
@ -30,27 +30,27 @@ function Move({ action, id, first, last }: { action: (fd: FormData) => Promise<v
|
||||||
|
|
||||||
/** Kursinhalt (Kapitel, Einheiten, Videos) und Zugänge im Produkt. */
|
/** Kursinhalt (Kapitel, Einheiten, Videos) und Zugänge im Produkt. */
|
||||||
export async function CourseEditor({ productId, canEdit }: { productId: string; canEdit: boolean }) {
|
export async function CourseEditor({ productId, canEdit }: { productId: string; canEdit: boolean }) {
|
||||||
const [chapters, access, bunny] = await Promise.all([
|
const [chapters, access, storage] = await Promise.all([
|
||||||
db.courseChapter.findMany({ where: { productId }, orderBy: { sort: "asc" }, include: { lessons: { orderBy: { sort: "asc" } } } }),
|
db.courseChapter.findMany({ where: { productId }, orderBy: { sort: "asc" }, include: { lessons: { orderBy: { sort: "asc" } } } }),
|
||||||
db.courseAccess.findMany({ where: { productId }, orderBy: { createdAt: "desc" }, include: { user: { select: { email: true, firstName: true, lastName: true } }, order: { select: { id: true, number: true } } } }),
|
db.courseAccess.findMany({ where: { productId }, orderBy: { createdAt: "desc" }, include: { user: { select: { email: true, firstName: true, lastName: true } }, order: { select: { id: true, number: true } } } }),
|
||||||
getBunnyConfig(),
|
storageInfo().catch(() => null),
|
||||||
]);
|
]);
|
||||||
const ready = isBunnyReady(bunny);
|
|
||||||
const lessons = chapters.flatMap((c) => c.lessons);
|
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);
|
const total = lessons.reduce((s, l) => s + l.duration, 0);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ marginTop: "var(--space-6)" }}>
|
<div style={{ marginTop: "var(--space-6)" }}>
|
||||||
<VideoStatusPoller productId={productId} active={pending} />
|
<VideoStatusPoller productId={productId} active={pending} />
|
||||||
{!ready && (
|
{lowSpace && (
|
||||||
<div style={{ marginBottom: "var(--space-5)" }}>
|
<div style={{ marginBottom: "var(--space-5)" }}>
|
||||||
<Alert title="Für Videos fehlt noch Bunny Stream.">
|
<Alert kind="danger" title={`Auf dem Server ist nur noch ${formatBytes(storage.free)} frei.`}>
|
||||||
Richte zuerst unter <Link href="/admin/verbindungen/bunny">Verbindungen → Bunny Stream</Link> 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.
|
||||||
</Alert>
|
</Alert>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Card title="Kursinhalt" lead={`${lessons.length} ${lessons.length === 1 ? "Einheit" : "Einheiten"}${total ? `, Gesamtlänge ${formatDuration(total)}` : ""}. Kunden sehen nur Einheiten mit fertigem Video.`}>
|
<Card title="Kursinhalt" lead={`${lessons.length} ${lessons.length === 1 ? "Einheit" : "Einheiten"}${total ? `, Gesamtlänge ${formatDuration(total)}` : ""}. Kunden sehen nur Einheiten mit fertigem Video.${storage ? ` Videos belegen ${formatBytes(storage.used)}, frei auf dem Server: ${formatBytes(storage.free)}.` : ""}`}>
|
||||||
{chapters.length === 0 && <Empty title="Noch keine Kapitel" text="Lege ein erstes Kapitel an, z. B. „Grundlagen“, und darin die Einheiten mit je einem Video." />}
|
{chapters.length === 0 && <Empty title="Noch keine Kapitel" text="Lege ein erstes Kapitel an, z. B. „Grundlagen“, und darin die Einheiten mit je einem Video." />}
|
||||||
{chapters.map((c, ci) => (
|
{chapters.map((c, ci) => (
|
||||||
<section key={c.id} className="ad-chapter">
|
<section key={c.id} className="ad-chapter">
|
||||||
|
|
@ -79,6 +79,7 @@ export async function CourseEditor({ productId, canEdit }: { productId: string;
|
||||||
<strong>{li + 1}. {l.title}</strong>
|
<strong>{li + 1}. {l.title}</strong>
|
||||||
<span className="ad-lesson__meta">
|
<span className="ad-lesson__meta">
|
||||||
<Pill tone={st.tone}>{st.label}</Pill>
|
<Pill tone={st.tone}>{st.label}</Pill>
|
||||||
|
{l.videoId && l.videoStatus !== "ready" && <Pill tone="success">Altes Video läuft weiter</Pill>}
|
||||||
{l.duration > 0 && <span className="caption ad-muted">{formatDuration(l.duration)}</span>}
|
{l.duration > 0 && <span className="caption ad-muted">{formatDuration(l.duration)}</span>}
|
||||||
{l.preview && <Pill tone="gold">Vorschau</Pill>}
|
{l.preview && <Pill tone="gold">Vorschau</Pill>}
|
||||||
</span>
|
</span>
|
||||||
|
|
@ -89,11 +90,16 @@ export async function CourseEditor({ productId, canEdit }: { productId: string;
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{l.videoStatus === "error" && l.videoError && <p className="body-sm ad-err" style={{ margin: "var(--space-2) 0 0" }}>{l.videoError}</p>}
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<details className="ad-lesson__edit">
|
<details className="ad-lesson__edit" open={!l.videoId && l.videoStatus === "none" ? true : undefined}>
|
||||||
<summary>Bearbeiten und Video</summary>
|
<summary>Bearbeiten und Video</summary>
|
||||||
<LessonForm id={l.id} title={l.title} description={l.description} preview={l.preview} />
|
<LessonForm id={l.id} title={l.title} description={l.description} preview={l.preview} />
|
||||||
{ready && <VideoUpload lessonId={l.id} hasVideo={Boolean(l.videoId)} />}
|
<div className="ad-lesson__actions">
|
||||||
|
<VideoUpload lessonId={l.id} hasVideo={Boolean(l.videoId)} busy={l.videoStatus === "processing"} />
|
||||||
|
{l.videoId && l.videoStatus !== "processing" && <ConfirmButton action={removeVideo} hidden={{ id: l.id }} confirm="Video dieser Einheit löschen?" className="sm-btn sm-btn--ghost sm-btn--sm">Video löschen</ConfirmButton>}
|
||||||
|
<small className="ad-muted">MP4 oder MOV, gern in voller Qualität. Der Server wandelt es danach selbst um (dauert etwa so lang wie das Video).</small>
|
||||||
|
</div>
|
||||||
</details>
|
</details>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,60 +1,39 @@
|
||||||
"use client";
|
"use client";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useEffect, useRef, useState } from "react";
|
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).
|
// Lädt ein Video in Stücken auf den eigenen Server (/admin/video-upload). Bricht ein Stück ab,
|
||||||
// So geht die große Datei nicht über unseren Server.
|
// wird es wiederholt; der Server meldet, wo es weitergeht. Danach wandelt der Server es im Hintergrund um.
|
||||||
|
|
||||||
const CHUNK = 32 * 1024 * 1024;
|
const CHUNK = 8 * 1024 * 1024;
|
||||||
const b64 = (s: string) => btoa(unescape(encodeURIComponent(s)));
|
|
||||||
|
|
||||||
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<string, string>, body: Blob | null, onProgress?: (loaded: number) => void) {
|
function sendChunk(url: string, body: Blob, onProgress: (loaded: number) => void) {
|
||||||
return new Promise<XMLHttpRequest>((resolve, reject) => {
|
return new Promise<Reply>((resolve, reject) => {
|
||||||
const xhr = new XMLHttpRequest();
|
const xhr = new XMLHttpRequest();
|
||||||
xhr.open(method, url);
|
xhr.open("POST", url);
|
||||||
for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);
|
xhr.setRequestHeader("Content-Type", "application/octet-stream");
|
||||||
if (onProgress) xhr.upload.onprogress = (e) => onProgress(e.loaded);
|
xhr.upload.onprogress = (e) => onProgress(e.loaded);
|
||||||
xhr.onload = () => (xhr.status >= 200 && xhr.status < 300 ? resolve(xhr) : reject(new Error(`HTTP ${xhr.status}`)));
|
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.onerror = () => reject(new Error("Netzwerkfehler"));
|
||||||
xhr.send(body);
|
xhr.send(body);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function tusUpload(file: File, sig: Sig, onProgress: (pct: number) => void) {
|
class FinalError extends Error {}
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 router = useRouter();
|
||||||
const input = useRef<HTMLInputElement>(null);
|
const input = useRef<HTMLInputElement>(null);
|
||||||
const [pct, setPct] = useState<number | null>(null);
|
const [pct, setPct] = useState<number | null>(null);
|
||||||
|
|
@ -67,40 +46,47 @@ export function VideoUpload({ lessonId, hasVideo }: { lessonId: string; hasVideo
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setPct(0);
|
setPct(0);
|
||||||
const sig = await startVideoUpload(lessonId);
|
|
||||||
if (!sig.ok) {
|
|
||||||
setPct(null);
|
|
||||||
setError(sig.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Seite während des Uploads nicht versehentlich verlassen
|
// Seite während des Uploads nicht versehentlich verlassen
|
||||||
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
||||||
window.addEventListener("beforeunload", warn);
|
window.addEventListener("beforeunload", warn);
|
||||||
try {
|
try {
|
||||||
await tusUpload(file, sig, (p) => setPct(Math.min(99, Math.floor(p))));
|
let offset = 0;
|
||||||
await finishVideoUpload(lessonId, false);
|
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);
|
setPct(null);
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await finishVideoUpload(lessonId, true);
|
|
||||||
setPct(null);
|
setPct(null);
|
||||||
setError(`Upload abgebrochen: ${e instanceof Error ? e.message : e}. Bitte noch einmal versuchen.`);
|
setError(`Upload abgebrochen: ${e instanceof Error ? e.message : e}`);
|
||||||
router.refresh();
|
|
||||||
} finally {
|
} finally {
|
||||||
window.removeEventListener("beforeunload", warn);
|
window.removeEventListener("beforeunload", warn);
|
||||||
|
if (input.current) input.current.value = "";
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<span className="ad-video-upload">
|
<span className="ad-video-upload">
|
||||||
<input ref={input} type="file" accept="video/*" hidden onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])} />
|
<input ref={input} type="file" accept="video/*,.mp4,.mov,.m4v" hidden onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])} />
|
||||||
{pct !== null ? (
|
{pct !== null ? (
|
||||||
<span className="ad-video-upload__progress" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
<span className="ad-video-upload__progress" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||||
<span className="ad-video-upload__track"><span style={{ width: `${pct}%` }} /></span>
|
<span className="ad-video-upload__track"><span style={{ width: `${pct}%` }} /></span>
|
||||||
<small>Lädt hoch … {pct} %. Seite bitte offen lassen.</small>
|
<small>Lädt hoch … {pct} %. Seite bitte offen lassen.</small>
|
||||||
</span>
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={() => input.current?.click()}>
|
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={() => input.current?.click()} disabled={busy}>
|
||||||
{hasVideo ? "Video ersetzen" : "Video hochladen"}
|
{hasVideo ? "Video ersetzen" : "Video hochladen"}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|
@ -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 }) {
|
export function VideoStatusPoller({ productId, active }: { productId: string; active: boolean }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
let stop = false;
|
let stop = false;
|
||||||
|
let last = "";
|
||||||
let timer: ReturnType<typeof setTimeout>;
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
const tick = async () => {
|
const tick = async () => {
|
||||||
const changed = await refreshVideos(productId).catch(() => 0);
|
const now = await videoStates(productId).catch(() => last);
|
||||||
if (stop) return;
|
if (stop) return;
|
||||||
if (changed) router.refresh();
|
if (last && now !== last) router.refresh();
|
||||||
timer = setTimeout(tick, 15000);
|
last = now;
|
||||||
|
timer = setTimeout(tick, 10000);
|
||||||
};
|
};
|
||||||
timer = setTimeout(tick, 5000);
|
void tick();
|
||||||
return () => {
|
return () => {
|
||||||
stop = true;
|
stop = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import Link from "next/link";
|
||||||
import { formatDuration } from "@/lib/courses";
|
import { formatDuration } from "@/lib/courses";
|
||||||
import { Icon } from "../Icon";
|
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[] };
|
type Chapter = { id: string; title: string; lessons: Lesson[] };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -20,7 +20,7 @@ export function CourseOutline({ chapters, hrefFor, current, done }: { chapters:
|
||||||
<ol>
|
<ol>
|
||||||
{c.lessons.map((l) => {
|
{c.lessons.map((l) => {
|
||||||
n++;
|
n++;
|
||||||
const href = l.videoStatus === "ready" ? hrefFor(l) : null;
|
const href = l.videoId ? hrefFor(l) : null;
|
||||||
const body = (
|
const body = (
|
||||||
<>
|
<>
|
||||||
<span className="sm-course__num" aria-hidden="true">{done?.has(l.id) ? <Icon name="check" size="sm" /> : n}</span>
|
<span className="sm-course__num" aria-hidden="true">{done?.has(l.id) ? <Icon name="check" size="sm" /> : n}</span>
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
"use client";
|
"use client";
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
// Bunny-Player im iframe. Gesteuert über das player.js-Protokoll (postMessage), das der Bunny-Player spricht.
|
// Player für die Kursvideos vom eigenen Server (HLS, verschlüsselt). Safari spielt HLS selbst,
|
||||||
// Das Vollbild läuft über unseren Rahmen, damit das Wasserzeichen auch dort über dem Video liegt.
|
// alle anderen Browser über hls.js. Vollbild läuft über unseren Rahmen, damit das Wasserzeichen sichtbar bleibt.
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
src: string;
|
src: string;
|
||||||
|
|
@ -16,10 +16,11 @@ type Props = {
|
||||||
const SAVE_EVERY = 15;
|
const SAVE_EVERY = 15;
|
||||||
|
|
||||||
export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }: Props) {
|
export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }: Props) {
|
||||||
const frame = useRef<HTMLIFrameElement>(null);
|
const video = useRef<HTMLVideoElement>(null);
|
||||||
const box = useRef<HTMLDivElement>(null);
|
const box = useRef<HTMLDivElement>(null);
|
||||||
const [pos, setPos] = useState({ x: 8, y: 10 });
|
const [pos, setPos] = useState({ x: 8, y: 10 });
|
||||||
const [full, setFull] = useState(false);
|
const [full, setFull] = useState(false);
|
||||||
|
const [error, setError] = useState("");
|
||||||
const lastSaved = useRef(0);
|
const lastSaved = useRef(0);
|
||||||
const report = useRef(onProgress);
|
const report = useRef(onProgress);
|
||||||
report.current = onProgress;
|
report.current = onProgress;
|
||||||
|
|
@ -39,41 +40,56 @@ export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }:
|
||||||
return () => document.removeEventListener("fullscreenchange", onFs);
|
return () => document.removeEventListener("fullscreenchange", onFs);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// player.js: auf "ready" warten, dann Zeit-Ereignisse abonnieren und ggf. an die letzte Stelle springen
|
// Video laden
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const target = () => frame.current?.contentWindow;
|
const el = video.current;
|
||||||
const send = (method: string, value?: unknown) => target()?.postMessage(JSON.stringify({ context: "player.js", version: "0.0.11", method, value }), "*");
|
if (!el) return;
|
||||||
let jumped = false;
|
setError("");
|
||||||
const onMessage = (e: MessageEvent) => {
|
let destroy = () => {};
|
||||||
if (e.source !== target()) return;
|
let cancelled = false;
|
||||||
let data: { context?: string; event?: string; value?: { seconds?: number; duration?: number } };
|
const jump = () => {
|
||||||
try {
|
if (startAt > 5 && el.duration && startAt < el.duration - 5) el.currentTime = startAt;
|
||||||
data = typeof e.data === "string" ? JSON.parse(e.data) : e.data;
|
};
|
||||||
} catch {
|
el.addEventListener("loadedmetadata", jump, { once: true });
|
||||||
return;
|
if (el.canPlayType("application/vnd.apple.mpegurl")) {
|
||||||
}
|
el.src = src;
|
||||||
if (data?.context !== "player.js") return;
|
} else {
|
||||||
if (data.event === "ready") {
|
void import("hls.js").then(({ default: Hls }) => {
|
||||||
send("addEventListener", "timeupdate");
|
if (cancelled) return;
|
||||||
send("addEventListener", "ended");
|
if (!Hls.isSupported()) {
|
||||||
if (startAt > 5 && !jumped) {
|
setError("Dieser Browser kann das Video leider nicht abspielen. Bitte nutze einen aktuellen Browser.");
|
||||||
jumped = true;
|
return;
|
||||||
send("setCurrentTime", startAt);
|
}
|
||||||
}
|
const hls = new Hls({ capLevelToPlayerSize: true });
|
||||||
} else if (data.event === "timeupdate" && data.value?.seconds != null) {
|
hls.on(Hls.Events.ERROR, (_e, data) => {
|
||||||
const s = Math.floor(data.value.seconds);
|
if (!data.fatal) return;
|
||||||
if (Math.abs(s - lastSaved.current) >= SAVE_EVERY) {
|
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) setError("Das Video lädt nicht. Ist die Seite schon länger offen? Dann bitte neu laden.");
|
||||||
lastSaved.current = s;
|
else hls.recoverMediaError();
|
||||||
report.current?.(s, Math.floor(data.value.duration ?? 0), false);
|
});
|
||||||
}
|
hls.loadSource(src);
|
||||||
} else if (data.event === "ended") {
|
hls.attachMedia(el);
|
||||||
report.current?.(0, 0, true);
|
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]);
|
}, [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 = () => {
|
const toggleFull = () => {
|
||||||
if (document.fullscreenElement) void document.exitFullscreen();
|
if (document.fullscreenElement) void document.exitFullscreen();
|
||||||
else void box.current?.requestFullscreen?.();
|
else void box.current?.requestFullscreen?.();
|
||||||
|
|
@ -81,14 +97,18 @@ export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }:
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`sm-player${full ? " is-full" : ""}`} ref={box} onContextMenu={(e) => e.preventDefault()}>
|
<div className={`sm-player${full ? " is-full" : ""}`} ref={box} onContextMenu={(e) => e.preventDefault()}>
|
||||||
<iframe
|
<video
|
||||||
ref={frame}
|
ref={video}
|
||||||
src={src}
|
|
||||||
title={title}
|
title={title}
|
||||||
loading="lazy"
|
controls
|
||||||
// Kein allowFullScreen und kein Bild-im-Bild: sonst liefe das Video ohne Wasserzeichen
|
playsInline
|
||||||
allow="accelerometer; gyroscope; autoplay; encrypted-media"
|
preload="metadata"
|
||||||
referrerPolicy="strict-origin-when-cross-origin"
|
// Kein Download, kein Bild-im-Bild, eigenes Vollbild (sonst wäre das Wasserzeichen weg)
|
||||||
|
controlsList="nodownload nofullscreen noremoteplayback"
|
||||||
|
disablePictureInPicture
|
||||||
|
disableRemotePlayback
|
||||||
|
onTimeUpdate={onTime}
|
||||||
|
onEnded={() => report.current?.(0, 0, true)}
|
||||||
/>
|
/>
|
||||||
{watermark && (
|
{watermark && (
|
||||||
<span className="sm-player__mark" style={{ left: `${pos.x}%`, top: `${pos.y}%` }} aria-hidden="true">
|
<span className="sm-player__mark" style={{ left: `${pos.x}%`, top: `${pos.y}%` }} aria-hidden="true">
|
||||||
|
|
@ -100,6 +120,7 @@ export function CoursePlayer({ src, title, watermark, startAt = 0, onProgress }:
|
||||||
{full ? <path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" /> : <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />}
|
{full ? <path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5" /> : <path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" />}
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
|
{error && <p className="sm-player__error" role="alert">{error}</p>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// Läuft einmal beim Start des Servers: Takt für Newsletter-Versand und Wieder-da-Erinnerungen.
|
// Läuft einmal beim Start des Servers: Takt für Newsletter-Versand, Wieder-da-Erinnerungen und Video-Umwandlung.
|
||||||
// Die Abfrage muss so geschrieben sein, damit der Edge-Build den Node-Teil weglässt.
|
// Die Abfrage muss so geschrieben sein, damit der Edge-Build den Node-Teil weglässt.
|
||||||
export async function register() {
|
export async function register() {
|
||||||
if (process.env.NEXT_RUNTIME === "nodejs") {
|
if (process.env.NEXT_RUNTIME === "nodejs") {
|
||||||
|
|
@ -6,5 +6,7 @@ export async function register() {
|
||||||
startNewsletterTimer();
|
startNewsletterTimer();
|
||||||
const { startStockAlertTimer } = await import("./lib/stock-alerts");
|
const { startStockAlertTimer } = await import("./lib/stock-alerts");
|
||||||
startStockAlertTimer();
|
startStockAlertTimer();
|
||||||
|
const { startVideoTimer } = await import("./lib/video");
|
||||||
|
startVideoTimer();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
import "server-only";
|
|
||||||
import { createHash } from "node:crypto";
|
|
||||||
import { db } from "./db";
|
|
||||||
|
|
||||||
// Bunny Stream: Videos für die Kurse. Hochgeladen wird direkt aus dem Browser zu Bunny (TUS),
|
|
||||||
// abgespielt im Bunny-Player per iframe mit signiertem, kurzlebigem Link.
|
|
||||||
|
|
||||||
export type BunnyConfig = {
|
|
||||||
libraryId: string;
|
|
||||||
apiKey: string;
|
|
||||||
// "Token Authentication Key" der Bibliothek (Security → Embed view token authentication)
|
|
||||||
tokenKey: string;
|
|
||||||
// MediaCage Enterprise DRM ist bei Bunny gebucht und für die Bibliothek eingeschaltet
|
|
||||||
drm: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULTS: BunnyConfig = { libraryId: "", apiKey: "", tokenKey: "", drm: false };
|
|
||||||
const KEY = "bunny_stream";
|
|
||||||
const API = "https://video.bunnycdn.com";
|
|
||||||
const EMBED = "https://iframe.mediadelivery.net/embed";
|
|
||||||
|
|
||||||
export async function getBunnyConfig(): Promise<BunnyConfig> {
|
|
||||||
const row = await db.setting.findUnique({ where: { key: KEY } });
|
|
||||||
return { ...DEFAULTS, ...((row?.value ?? {}) as Partial<BunnyConfig>) };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function saveBunnyConfig(value: BunnyConfig) {
|
|
||||||
await db.setting.upsert({ where: { key: KEY }, create: { key: KEY, value }, update: { value } });
|
|
||||||
}
|
|
||||||
|
|
||||||
export const isBunnyReady = (c: BunnyConfig) => Boolean(c.libraryId && c.apiKey && c.tokenKey);
|
|
||||||
|
|
||||||
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
|
|
||||||
|
|
||||||
async function api<T>(c: BunnyConfig, path: string, init?: { method?: string; body?: unknown }): Promise<T> {
|
|
||||||
const res = await fetch(`${API}/library/${encodeURIComponent(c.libraryId)}${path}`, {
|
|
||||||
method: init?.method ?? "GET",
|
|
||||||
headers: { AccessKey: c.apiKey, Accept: "application/json", ...(init?.body ? { "Content-Type": "application/json" } : {}) },
|
|
||||||
body: init?.body ? JSON.stringify(init.body) : undefined,
|
|
||||||
cache: "no-store",
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const text = await res.text().catch(() => "");
|
|
||||||
if (res.status === 401) throw new Error("Bunny lehnt den API-Schlüssel ab (Bibliotheks-ID oder Schlüssel passen nicht zusammen).");
|
|
||||||
if (res.status === 404) throw new Error("Bunny kennt diese Bibliothek oder dieses Video nicht.");
|
|
||||||
throw new Error(`Bunny meldet HTTP ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`);
|
|
||||||
}
|
|
||||||
return (res.status === 204 ? null : await res.json()) as T;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Prüft Bibliotheks-ID und API-Schlüssel, ohne etwas zu verändern. */
|
|
||||||
export async function testBunnyApi(c: BunnyConfig) {
|
|
||||||
const data = await api<{ totalItems: number }>(c, "/videos?page=1&itemsPerPage=1");
|
|
||||||
return data.totalItems ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
type BunnyVideo = { guid: string; status: number; length: number; title: string };
|
|
||||||
|
|
||||||
export async function createBunnyVideo(c: BunnyConfig, title: string) {
|
|
||||||
return api<BunnyVideo>(c, "/videos", { method: "POST", body: { title } });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getBunnyVideo(c: BunnyConfig, videoId: string) {
|
|
||||||
return api<BunnyVideo>(c, `/videos/${encodeURIComponent(videoId)}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function deleteBunnyVideo(c: BunnyConfig, videoId: string) {
|
|
||||||
await api(c, `/videos/${encodeURIComponent(videoId)}`, { method: "DELETE" });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Bunny-Status → unser Status. 4 = fertig, 5/6 = Fehler, alles andere läuft noch. */
|
|
||||||
export function videoStatus(bunnyStatus: number): "processing" | "ready" | "error" {
|
|
||||||
if (bunnyStatus === 4) return "ready";
|
|
||||||
if (bunnyStatus === 5 || bunnyStatus === 6) return "error";
|
|
||||||
return "processing";
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Signatur für den direkten Upload aus dem Browser (TUS), gültig für 24 Stunden. */
|
|
||||||
export function uploadSignature(c: BunnyConfig, videoId: string) {
|
|
||||||
const expires = Math.floor(Date.now() / 1000) + 24 * 3600;
|
|
||||||
return {
|
|
||||||
endpoint: `${API}/tusupload`,
|
|
||||||
libraryId: c.libraryId,
|
|
||||||
videoId,
|
|
||||||
expires,
|
|
||||||
signature: sha256(c.libraryId + c.apiKey + expires + videoId),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Signierter Player-Link. Läuft nach `hours` Stunden ab; danach muss die Seite neu geladen werden. */
|
|
||||||
export function embedUrl(c: BunnyConfig, videoId: string, hours = 6) {
|
|
||||||
const expires = Math.floor(Date.now() / 1000) + hours * 3600;
|
|
||||||
const token = sha256(c.tokenKey + videoId + expires);
|
|
||||||
const q = new URLSearchParams({ token, expires: String(expires), autoplay: "false", preload: "true", responsive: "true" });
|
|
||||||
return `${EMBED}/${encodeURIComponent(c.libraryId)}/${encodeURIComponent(videoId)}?${q}`;
|
|
||||||
}
|
|
||||||
|
|
@ -8,9 +8,8 @@ import { appleClientSecret } from "./social/oauth";
|
||||||
import type { Permission } from "./permissions";
|
import type { Permission } from "./permissions";
|
||||||
import { getMailConfig, type MailConfig } from "./mail/config";
|
import { getMailConfig, type MailConfig } from "./mail/config";
|
||||||
import { verifySmtp } from "./mail/smtp";
|
import { verifySmtp } from "./mail/smtp";
|
||||||
import { getBunnyConfig, isBunnyReady, testBunnyApi, type BunnyConfig } from "./bunny";
|
|
||||||
|
|
||||||
export type IntegrationKey = "stripe" | "paypal" | "dhl" | "google" | "apple" | "mail" | "bunny";
|
export type IntegrationKey = "stripe" | "paypal" | "dhl" | "google" | "apple" | "mail";
|
||||||
export type TestResult = { ok: boolean; message: string; at: string };
|
export type TestResult = { ok: boolean; message: string; at: string };
|
||||||
export type IntegrationStatus = { key: IntegrationKey; configured: boolean; mode: string; active: boolean; lastTest: TestResult | null };
|
export type IntegrationStatus = { key: IntegrationKey; configured: boolean; mode: string; active: boolean; lastTest: TestResult | null };
|
||||||
|
|
||||||
|
|
@ -21,7 +20,6 @@ export const INTEGRATIONS: { key: IntegrationKey; name: string; purpose: string;
|
||||||
{ key: "google", name: "Google", purpose: "„Mit Google anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 10 Minuten, zwei Werte" },
|
{ key: "google", name: "Google", purpose: "„Mit Google anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 10 Minuten, zwei Werte" },
|
||||||
{ key: "mail", name: "E-Mail-Versand", purpose: "Bestellbestätigungen, Rechnungen, Passwort vergessen und alle anderen Mails über dein Postfach", permission: "emails.edit", effort: "ca. 5 Minuten, Zugangsdaten deines Postfachs" },
|
{ key: "mail", name: "E-Mail-Versand", purpose: "Bestellbestätigungen, Rechnungen, Passwort vergessen und alle anderen Mails über dein Postfach", permission: "emails.edit", effort: "ca. 5 Minuten, Zugangsdaten deines Postfachs" },
|
||||||
{ key: "apple", name: "Apple", purpose: "„Mit Apple anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 15 Minuten, Apple-Developer-Konto nötig" },
|
{ key: "apple", name: "Apple", purpose: "„Mit Apple anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 15 Minuten, Apple-Developer-Konto nötig" },
|
||||||
{ key: "bunny", name: "Bunny Stream", purpose: "Videos für die Kurse: hochladen, geschützt abspielen, optional mit DRM", permission: "settings.edit", effort: "ca. 10 Minuten, Bunny-Konto nötig" },
|
|
||||||
];
|
];
|
||||||
|
|
||||||
const TESTS_KEY = "integration_tests";
|
const TESTS_KEY = "integration_tests";
|
||||||
|
|
@ -44,7 +42,7 @@ export async function forgetTest(key: IntegrationKey) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationStatus>> {
|
export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationStatus>> {
|
||||||
const [creds, dhl, login, mail, bunny, tests] = await Promise.all([getCredentials(), getDhlConfig(), getLoginProviders(), getMailConfig(), getBunnyConfig(), getLastTests()]);
|
const [creds, dhl, login, mail, tests] = await Promise.all([getCredentials(), getDhlConfig(), getLoginProviders(), getMailConfig(), getLastTests()]);
|
||||||
const s = (key: IntegrationKey, configured: boolean, mode: string, active: boolean): IntegrationStatus => ({ key, configured, mode, active, lastTest: configured ? (tests[key] ?? null) : null });
|
const s = (key: IntegrationKey, configured: boolean, mode: string, active: boolean): IntegrationStatus => ({ key, configured, mode, active, lastTest: configured ? (tests[key] ?? null) : null });
|
||||||
return {
|
return {
|
||||||
stripe: s("stripe", Boolean(creds.stripe.secretKey), creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live", Boolean(creds.stripe.secretKey)),
|
stripe: s("stripe", Boolean(creds.stripe.secretKey), creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live", Boolean(creds.stripe.secretKey)),
|
||||||
|
|
@ -53,7 +51,6 @@ export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationS
|
||||||
google: s("google", isConfigured("google", login), "", login.google.enabled),
|
google: s("google", isConfigured("google", login), "", login.google.enabled),
|
||||||
apple: s("apple", isConfigured("apple", login), "", login.apple.enabled),
|
apple: s("apple", isConfigured("apple", login), "", login.apple.enabled),
|
||||||
mail: s("mail", Boolean(mail.host && mail.fromEmail), mail.host, mail.enabled),
|
mail: s("mail", Boolean(mail.host && mail.fromEmail), mail.host, mail.enabled),
|
||||||
bunny: s("bunny", Boolean(bunny.libraryId && bunny.apiKey), bunny.drm ? "mit DRM" : "", isBunnyReady(bunny)),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -201,24 +198,3 @@ export async function testMail(c?: MailConfig) {
|
||||||
await remember("mail", r);
|
await remember("mail", r);
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------- Bunny Stream ----------
|
|
||||||
|
|
||||||
/** Prüft Bibliothek und API-Schlüssel direkt bei Bunny. */
|
|
||||||
export async function testBunny(c?: BunnyConfig) {
|
|
||||||
const config = c ?? (await getBunnyConfig());
|
|
||||||
let r: { ok: boolean; message: string };
|
|
||||||
if (!config.libraryId || !config.apiKey) r = { ok: false, message: "Es sind noch keine Zugangsdaten gespeichert." };
|
|
||||||
else {
|
|
||||||
try {
|
|
||||||
const count = await testBunnyApi(config);
|
|
||||||
r = config.tokenKey
|
|
||||||
? { ok: true, message: `Bunny Stream verbunden (Bibliothek ${config.libraryId}, ${count} ${count === 1 ? "Video" : "Videos"}).${config.drm ? " DRM ist eingeschaltet." : ""}` }
|
|
||||||
: { ok: false, message: "Bibliothek und API-Schlüssel passen, aber der Token-Schlüssel aus Schritt 4 fehlt noch. Ohne ihn lassen sich die Videos nicht geschützt abspielen." };
|
|
||||||
} catch (e) {
|
|
||||||
r = { ok: false, message: e instanceof Error ? e.message : String(e) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
await remember("bunny", r);
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
|
||||||
211
src/lib/video.ts
Normal file
211
src/lib/video.ts
Normal file
|
|
@ -0,0 +1,211 @@
|
||||||
|
import "server-only";
|
||||||
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||||
|
import { spawn } from "node:child_process";
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import { db } from "./db";
|
||||||
|
|
||||||
|
// Kursvideos auf dem eigenen Server: Upload → Umwandlung mit ffmpeg in HLS (mehrere Qualitäten,
|
||||||
|
// AES-128-verschlüsselt) → Auslieferung nur über /api/video mit signierten, kurzlebigen Links.
|
||||||
|
// Die Original-Datei wird nach der Umwandlung gelöscht und nie ausgeliefert.
|
||||||
|
|
||||||
|
export const VIDEO_ROOT = path.resolve(process.env.VIDEO_DIR ?? "./videos");
|
||||||
|
const INCOMING = path.join(VIDEO_ROOT, "incoming");
|
||||||
|
const HLS = path.join(VIDEO_ROOT, "hls");
|
||||||
|
const KEYS = path.join(VIDEO_ROOT, "keys");
|
||||||
|
|
||||||
|
export const ID = /^[a-z0-9]{16,40}$/;
|
||||||
|
export const sourcePath = (lessonId: string) => path.join(INCOMING, `${lessonId}.src`);
|
||||||
|
export const partPath = (lessonId: string) => path.join(INCOMING, `${lessonId}.part`);
|
||||||
|
export const hlsDir = (videoId: string) => path.join(HLS, videoId);
|
||||||
|
export const keyPath = (videoId: string) => path.join(KEYS, `${videoId}.key`);
|
||||||
|
|
||||||
|
export async function ensureDirs() {
|
||||||
|
await Promise.all([INCOMING, HLS, KEYS].map((d) => fs.mkdir(d, { recursive: true })));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Signierte Links ----------
|
||||||
|
|
||||||
|
let secret: string | null = null;
|
||||||
|
async function getSecret() {
|
||||||
|
if (secret) return secret;
|
||||||
|
const row = await db.setting.findUnique({ where: { key: "video_secret" } });
|
||||||
|
let value = (row?.value as { s?: string } | null)?.s;
|
||||||
|
if (!value) {
|
||||||
|
value = randomBytes(32).toString("hex");
|
||||||
|
await db.setting.upsert({ where: { key: "video_secret" }, create: { key: "video_secret", value: { s: value } }, update: {} });
|
||||||
|
value = ((await db.setting.findUnique({ where: { key: "video_secret" } }))?.value as { s: string }).s;
|
||||||
|
}
|
||||||
|
return (secret = value);
|
||||||
|
}
|
||||||
|
|
||||||
|
const mac = (s: string, data: string) => createHmac("sha256", s).update(data).digest("base64url");
|
||||||
|
|
||||||
|
/** Link zur Playlist. `userId` leer = Vorschau ohne Anmeldung. */
|
||||||
|
export async function playbackUrl(videoId: string, userId: string, hours = 4) {
|
||||||
|
const e = Math.floor(Date.now() / 1000) + hours * 3600;
|
||||||
|
const t = mac(await getSecret(), `${videoId}|${e}|${userId}`);
|
||||||
|
return `/api/video/${videoId}/master.m3u8?${new URLSearchParams({ e: String(e), u: userId, t })}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyLink(videoId: string, e: string, u: string, t: string) {
|
||||||
|
if (!/^\d+$/.test(e) || Number(e) < Date.now() / 1000) return false;
|
||||||
|
const expected = Buffer.from(mac(await getSecret(), `${videoId}|${e}|${u}`));
|
||||||
|
const given = Buffer.from(t);
|
||||||
|
return expected.length === given.length && timingSafeEqual(expected, given);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Speicher ----------
|
||||||
|
|
||||||
|
async function dirSize(dir: string): Promise<number> {
|
||||||
|
let total = 0;
|
||||||
|
const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
|
||||||
|
for (const e of entries) {
|
||||||
|
const p = path.join(dir, e.name);
|
||||||
|
if (e.isDirectory()) total += await dirSize(p);
|
||||||
|
else total += (await fs.stat(p).catch(() => ({ size: 0 }))).size;
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Freier Platz auf dem Laufwerk und Größe aller Kursvideos, in Bytes. */
|
||||||
|
export async function storageInfo() {
|
||||||
|
await ensureDirs();
|
||||||
|
const s = await fs.statfs(VIDEO_ROOT);
|
||||||
|
return { free: s.bavail * s.bsize, total: s.blocks * s.bsize, used: await dirSize(VIDEO_ROOT) };
|
||||||
|
}
|
||||||
|
|
||||||
|
export const formatBytes = (n: number) => (n >= 1e9 ? `${(n / 1e9).toFixed(1).replace(".", ",")} GB` : `${Math.round(n / 1e6)} MB`);
|
||||||
|
|
||||||
|
export async function deleteVideoFiles(videoId: string) {
|
||||||
|
if (!ID.test(videoId)) return;
|
||||||
|
await fs.rm(hlsDir(videoId), { recursive: true, force: true });
|
||||||
|
await fs.rm(keyPath(videoId), { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteSource(lessonId: string) {
|
||||||
|
await fs.rm(sourcePath(lessonId), { force: true });
|
||||||
|
await fs.rm(partPath(lessonId), { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Umwandlung ----------
|
||||||
|
|
||||||
|
function run(cmd: string, args: string[]) {
|
||||||
|
return new Promise<string>((resolve, reject) => {
|
||||||
|
const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
let out = "";
|
||||||
|
let err = "";
|
||||||
|
p.stdout.on("data", (d) => (out += d));
|
||||||
|
p.stderr.on("data", (d) => (err = (err + d).slice(-4000)));
|
||||||
|
p.on("error", reject);
|
||||||
|
p.on("close", (code) => (code === 0 ? resolve(out) : reject(new Error(err.trim().split("\n").slice(-3).join(" ") || `${cmd} beendet mit ${code}`))));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probe(file: string) {
|
||||||
|
const out = await run("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:format=duration", "-of", "json", file]);
|
||||||
|
const j = JSON.parse(out) as { streams?: { width: number; height: number }[]; format?: { duration?: string } };
|
||||||
|
const v = j.streams?.[0];
|
||||||
|
if (!v?.width || !v.height) throw new Error("In der Datei wurde keine Videospur gefunden.");
|
||||||
|
return { width: v.width, height: v.height, duration: Math.round(Number(j.format?.duration) || 0) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const LADDER = [
|
||||||
|
{ h: 480, crf: 23, audio: "96k" },
|
||||||
|
{ h: 720, crf: 22, audio: "128k" },
|
||||||
|
{ h: 1080, crf: 21, audio: "128k" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Wandelt eine hochgeladene Datei in verschlüsseltes HLS um. Gibt die neue Video-ID und die Länge zurück. */
|
||||||
|
export async function transcode(src: string) {
|
||||||
|
await ensureDirs();
|
||||||
|
const info = await probe(src);
|
||||||
|
// Quer- und Hochformat: maßgeblich ist die kürzere Seite; nie hochskalieren
|
||||||
|
const short = Math.min(info.width, info.height);
|
||||||
|
const steps = LADDER.filter((r) => r.h <= short);
|
||||||
|
if (!steps.length) steps.push({ h: short - (short % 2), crf: 22, audio: "128k" });
|
||||||
|
const videoId = randomBytes(12).toString("hex");
|
||||||
|
const out = hlsDir(videoId);
|
||||||
|
await fs.mkdir(out, { recursive: true });
|
||||||
|
await fs.writeFile(keyPath(videoId), randomBytes(16));
|
||||||
|
const keyinfo = path.join(out, "keyinfo");
|
||||||
|
// Zeile 1: Platzhalter, wird beim Ausliefern durch den signierten Schlüssel-Link ersetzt
|
||||||
|
await fs.writeFile(keyinfo, `KEY\n${keyPath(videoId)}\n${randomBytes(16).toString("hex")}\n`);
|
||||||
|
const portrait = info.height > info.width;
|
||||||
|
const variants: string[] = [];
|
||||||
|
try {
|
||||||
|
for (const r of steps) {
|
||||||
|
const dir = path.join(out, String(r.h));
|
||||||
|
await fs.mkdir(dir, { recursive: true });
|
||||||
|
const scale = portrait ? `scale=${r.h}:-2` : `scale=-2:${r.h}`;
|
||||||
|
await run("nice", [
|
||||||
|
"-n", "15", "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src,
|
||||||
|
"-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", String(r.crf), "-profile:v", "main", "-pix_fmt", "yuv420p",
|
||||||
|
"-g", "48", "-keyint_min", "48", "-sc_threshold", "0",
|
||||||
|
"-c:a", "aac", "-b:a", r.audio, "-ac", "2", "-threads", "2",
|
||||||
|
"-hls_time", "6", "-hls_playlist_type", "vod", "-hls_key_info_file", keyinfo,
|
||||||
|
"-hls_segment_filename", path.join(dir, "seg_%04d.ts"), path.join(dir, "index.m3u8"),
|
||||||
|
]);
|
||||||
|
const bytes = await dirSize(dir);
|
||||||
|
const bandwidth = Math.round((bytes * 8) / Math.max(info.duration, 1) * 1.1);
|
||||||
|
const w = portrait ? r.h : Math.round((info.width * r.h) / info.height / 2) * 2;
|
||||||
|
const h = portrait ? Math.round((info.height * r.h) / info.width / 2) * 2 : r.h;
|
||||||
|
variants.push(`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},RESOLUTION=${w}x${h}\n${r.h}/index.m3u8`);
|
||||||
|
}
|
||||||
|
await fs.writeFile(path.join(out, "master.m3u8"), `#EXTM3U\n#EXT-X-VERSION:3\n${variants.join("\n")}\n`);
|
||||||
|
await fs.rm(keyinfo, { force: true });
|
||||||
|
return { videoId, duration: info.duration };
|
||||||
|
} catch (e) {
|
||||||
|
await deleteVideoFiles(videoId);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Warteschlange ----------
|
||||||
|
|
||||||
|
const state = globalThis as unknown as { videoTimer?: NodeJS.Timeout; videoBusy?: boolean };
|
||||||
|
|
||||||
|
/** Wandelt das älteste wartende Video um. Immer nur eins gleichzeitig. */
|
||||||
|
export async function processNextVideo() {
|
||||||
|
if (state.videoBusy) return false;
|
||||||
|
const lesson = await db.courseLesson.findFirst({ where: { videoStatus: "queued" }, orderBy: { createdAt: "asc" } });
|
||||||
|
if (!lesson) return false;
|
||||||
|
state.videoBusy = true;
|
||||||
|
try {
|
||||||
|
await db.courseLesson.update({ where: { id: lesson.id }, data: { videoStatus: "processing", videoError: "" } });
|
||||||
|
const { videoId, duration } = await transcode(sourcePath(lesson.id));
|
||||||
|
// Einheit inzwischen gelöscht? Dann die neuen Dateien gleich wieder weg
|
||||||
|
const still = await db.courseLesson.findUnique({ where: { id: lesson.id } });
|
||||||
|
if (!still) {
|
||||||
|
await deleteVideoFiles(videoId);
|
||||||
|
} else {
|
||||||
|
await db.courseLesson.update({ where: { id: lesson.id }, data: { videoId, duration, videoStatus: "ready", videoError: "" } });
|
||||||
|
if (still.videoId && still.videoId !== videoId) await deleteVideoFiles(still.videoId);
|
||||||
|
}
|
||||||
|
await deleteSource(lesson.id);
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
console.error("Video-Umwandlung fehlgeschlagen", lesson.id, msg);
|
||||||
|
await db.courseLesson.update({ where: { id: lesson.id }, data: { videoStatus: "error", videoError: msg.slice(0, 500) } }).catch(() => undefined);
|
||||||
|
await deleteSource(lesson.id);
|
||||||
|
} finally {
|
||||||
|
state.videoBusy = false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startVideoTimer() {
|
||||||
|
if (state.videoTimer) return;
|
||||||
|
// Nach einem Neustart: abgebrochene Umwandlungen wieder einreihen, sofern die Datei noch da ist
|
||||||
|
void (async () => {
|
||||||
|
const stuck = await db.courseLesson.findMany({ where: { videoStatus: "processing" } }).catch(() => []);
|
||||||
|
for (const l of stuck) {
|
||||||
|
const has = await fs.stat(sourcePath(l.id)).then(() => true, () => false);
|
||||||
|
await db.courseLesson.update({ where: { id: l.id }, data: has ? { videoStatus: "queued" } : { videoStatus: "error", videoError: "Umwandlung durch Neustart abgebrochen, bitte neu hochladen." } });
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
state.videoTimer = setInterval(() => {
|
||||||
|
void processNextVideo().catch((e) => console.error("Video-Warteschlange", e));
|
||||||
|
}, 10_000);
|
||||||
|
state.videoTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
@ -276,10 +276,12 @@ button.sm-pdp__main { display: block; width: 100%; padding: 0; border: 0; cursor
|
||||||
|
|
||||||
/* ---------- Video-Kurse ---------- */
|
/* ---------- Video-Kurse ---------- */
|
||||||
.sm-player { position: relative; aspect-ratio: 16 / 9; background: #000; border-radius: var(--radius-md); overflow: hidden; user-select: none; -webkit-user-select: none; }
|
.sm-player { position: relative; aspect-ratio: 16 / 9; background: #000; border-radius: var(--radius-md); overflow: hidden; user-select: none; -webkit-user-select: none; }
|
||||||
.sm-player iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
|
.sm-player video { position: absolute; inset: 0; width: 100%; height: 100%; background: #000; }
|
||||||
|
.sm-player__error { position: absolute; inset: auto 0 0; z-index: 4; margin: 0; padding: var(--space-3) var(--space-4); background: rgb(0 0 0 / 0.75); color: #fff; font-size: 14px; }
|
||||||
.sm-player.is-full { border-radius: 0; aspect-ratio: auto; }
|
.sm-player.is-full { border-radius: 0; aspect-ratio: auto; }
|
||||||
.sm-player__mark { position: absolute; z-index: 2; pointer-events: none; font-size: 13px; line-height: 18px; color: rgb(255 255 255 / 0.42); text-shadow: 0 0 2px rgb(0 0 0 / 0.5); white-space: nowrap; transition: left 1.6s ease, top 1.6s ease; }
|
.sm-player__mark { position: absolute; z-index: 2; pointer-events: none; font-size: 13px; line-height: 18px; color: rgb(255 255 255 / 0.42); text-shadow: 0 0 2px rgb(0 0 0 / 0.5); white-space: nowrap; transition: left 1.6s ease, top 1.6s ease; }
|
||||||
.sm-player.is-full .sm-player__mark { font-size: 18px; }
|
.sm-player.is-full .sm-player__mark { font-size: 18px; }
|
||||||
|
.sm-player video::-webkit-media-controls-fullscreen-button { display: none; }
|
||||||
.sm-player__full { position: absolute; z-index: 3; top: 10px; right: 10px; display: grid; place-items: center; width: 36px; height: 36px; border: 0; border-radius: 50%; background: rgb(0 0 0 / 0.45); color: #fff; cursor: pointer; opacity: 0.75; }
|
.sm-player__full { position: absolute; z-index: 3; top: 10px; right: 10px; display: grid; place-items: center; width: 36px; height: 36px; border: 0; border-radius: 50%; background: rgb(0 0 0 / 0.45); color: #fff; cursor: pointer; opacity: 0.75; }
|
||||||
.sm-player__full:hover, .sm-player__full:focus-visible { opacity: 1; }
|
.sm-player__full:hover, .sm-player__full:focus-visible { opacity: 1; }
|
||||||
@media (prefers-reduced-motion: reduce) { .sm-player__mark { transition: none; } }
|
@media (prefers-reduced-motion: reduce) { .sm-player__mark { transition: none; } }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue