Spaces:
Running
feat(lessons): YouTube playlist playback embedded in-site — zero server load
Browse filesTHE CONVERSION: lesson videos now stream from the channel's YouTube playlist
INSIDE the site's own player screen — nothing uploaded to (or proxied by) our
server. Hybrid by design: legacy R2 lessons keep the protected player.
Server:
- src/lib/youtube-url.ts (shared, pure): extract YouTube id from every shape
(watch/shorts/youtu.be/embed/live/oembed/bare id), embed/watch/thumbnail
builders — 14 unit tests.
- video-protection.ts: YouTube branch BEFORE any R2 presigning (presigning a
youtube URL used to throw → misleading 503); returns kind=youtube + id +
youtube-nocookie embed URL. R2 path untouched (kind=r2).
- security.ts CSP (both blocks): frame-src youtube-nocookie/youtube +
script-src iframe_api hosts. Everything else stays locked down.
- admin-courses: youtubePlaylistVideos admin query reuses the watcher's
multi-source playlist pipeline for the import dialog.
Client:
- YouTubeLessonPlayer: embedded YT IFrame API player in the same aspect-video
slot, YT controls inside the frame, honest provenance strip, graceful
fallback (Open on YouTube) — with FULL watch-tracking parity: heartbeat 60s
(watchedSeconds+lastPosition), tab-hide pause+save, sendBeacon on unload,
auto-resume from saved position, ended → markWatched → certificate flow.
- CourseDetail: branches kind=youtube → embedded player, else legacy player.
- Admin: playlist-import dialog (thumbnail+title rows, one click fills the
lesson form), live YouTube-badge on pasted links, updated copy.
Local E2E (7 checks): YT lesson → embedded iframe in-site, no redirect,
provenance visible; R2 lesson → legacy player, no YT frame. 551 unit tests,
tsc, eslint all green. Also fixed vite dev buildId gating (dev white-page).
Files changed (13)
- api/admin-courses.ts+22
- api/lib/video-protection.ts+50
- api/lib/video-protection.youtube.test.tsAdded+79
- api/lib/youtube-watcher.ts+24
- api/middleware/security.ts+11-2
- scripts/youtube_lesson_local_e2e.pyAdded+174
- src/components/YouTubeLessonPlayer.tsxAdded+312
- src/lib/youtube-player-api.tsAdded+132
- src/lib/youtube-url.test.tsAdded+108
- src/lib/youtube-url.tsAdded+122
- src/pages/Admin.tsx+120-3
- src/pages/CourseDetail.tsx+20-1
- vite.config.ts+10-3
11 unmodified lines121314151617244 unmodified lines26226326426511 unmodified linesimport { getDb } from "./queries/connection";import { courses, lessons, enrollments, payments, wishlists, reviews } from "@db/schema";import { pushNotification } from "./lib/notification-broadcast.js";export const adminCoursesProcedures = {listCourses: adminQuery244 unmodified linesawait db.delete(lessons).where(eq(lessons.id, input.id));return { success: true };}),};11 unmodified lines12131415161718244 unmodified lines26326426526626726826927027127227327427527627727827928028128228328428528628711 unmodified linesimport { getDb } from "./queries/connection";import { courses, lessons, enrollments, payments, wishlists, reviews } from "@db/schema";import { pushNotification } from "./lib/notification-broadcast.js";import { fetchPlaylistVideosForImport, getPlaylistId } from "./lib/youtube-watcher.js";export const adminCoursesProcedures = {listCourses: adminQuery244 unmodified linesawait db.delete(lessons).where(eq(lessons.id, input.id));return { success: true };}),// ─── YouTube playlist import (lesson videos stream from the playlist) ───// The creator uploads lessons to the channel's YouTube playlist; the site// embeds them instead of hosting video files. This admin-only query lists// the playlist for the one-click "import into lesson" dialog. Playlist// fetches are throttled-prone (the watcher polls the same sources every// 15 min), so a failure surfaces as an honest empty result + error flag// instead of a hanging dialog.youtubePlaylistVideos: adminQuery.query(async () => {try {const items = await fetchPlaylistVideosForImport();return { playlistId: getPlaylistId(), items, error: null as string | null };} catch (err) {return {playlistId: getPlaylistId(),items: [],error: err instanceof Error ? err.message : "Playlist fetch failed",};}}),};
12 unmodified lines13141516171825 unmodified lines44454647484912 unmodified lines6263646566676869707112 unmodified lines84858687888919 unmodified lines10911011111211311412 unmodified linesimport { generateR2PresignedUrl } from "./r2";import { env } from "./env";import { logger } from "./logger.js";// ─── Configuration ───────────────────────────────────────────────────────────const VIDEO_URL_EXPIRY_SECONDS = 1800; // 30 minutes25 unmodified linesexpiresAt: string;/** Watermark token to identify leaker */watermarkToken: string;}// ─── Main Function ───────────────────────────────────────────────────────────12 unmodified lineshlsUrl: null as string | null,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),};if (!videoUrl) return defaultResult;// Check if the videoUrl already points to an HLS manifest (.m3u8)const isHlsSource = videoUrl.endsWith(".m3u8");12 unmodified lineshlsUrl: presignedUrl,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),};}19 unmodified lineshlsUrl,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),};} catch (err) {// ✅ SECURITY FIX (post-audit): FAIL CLOSED. The previous fallback returned12 unmodified lines1314151617181925 unmodified lines45464748495051525354555612 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611712 unmodified lines13013113213313413513613719 unmodified lines15715815916016116216316412 unmodified linesimport { generateR2PresignedUrl } from "./r2";import { env } from "./env";import { logger } from "./logger.js";import { buildYouTubeEmbedUrl, extractYouTubeId, isYouTubeVideoRef } from "../../src/lib/youtube-url";// ─── Configuration ───────────────────────────────────────────────────────────const VIDEO_URL_EXPIRY_SECONDS = 1800; // 30 minutes25 unmodified linesexpiresAt: string;/** Watermark token to identify leaker */watermarkToken: string;/** Source kind driving the frontend player branch: "youtube" renders the* embedded YouTube player (playback streams from YouTube — nothing from* our server); "r2" is the legacy self-hosted <video> path. */kind: "youtube" | "r2";/** 11-char YouTube video id when kind === "youtube", else null. */youtubeId: string | null;}// ─── Main Function ───────────────────────────────────────────────────────────12 unmodified lineshlsUrl: null as string | null,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),kind: "r2" as const,youtubeId: null as string | null,};if (!videoUrl) return defaultResult;// ─── Strategy 0: YouTube playlist video — ZERO bytes from our server ───// The lesson stores a YouTube link (watch/shorts/youtu.be/embed or a bare// id). Playback is handed to the embedded YouTube player on the client:// no R2 presigning, no proxying, no storage cost. The returned videoUrl is// the canonical watch link (kept for display/fallback) while youtubeId// drives the embed. MUST branch BEFORE any R2 call — presigning a YouTube// URL used to throw and fail-closed with a misleading 503.if (isYouTubeVideoRef(videoUrl)) {const youtubeId = extractYouTubeId(videoUrl) ?? "";const origin = env.FRONTEND_URL;let embedUrl: string;try {embedUrl = buildYouTubeEmbedUrl(youtubeId, origin);} catch (err) {// extractYouTubeId is the guard, so this is unreachable in practice —// but never let a broken link fail the whole procedure: log and surface// the legacy error path.logger.error("[VideoProtection] YouTube embed build failed", {lessonId,videoUrl: videoUrl.slice(0, 200),error: err instanceof Error ? err.message : String(err),});const trpcError = new Error("Video temporarily unavailable — please retry in a moment.") as Error & { status?: number };trpcError.status = 503;throw trpcError;}return {videoUrl: embedUrl,hlsUrl: null,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),kind: "youtube" as const,youtubeId,};}// Check if the videoUrl already points to an HLS manifest (.m3u8)const isHlsSource = videoUrl.endsWith(".m3u8");12 unmodified lineshlsUrl: presignedUrl,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),kind: "r2" as const,youtubeId: null,};}19 unmodified lineshlsUrl,expiresAt: new Date(Date.now() + VIDEO_URL_EXPIRY_SECONDS * 1000).toISOString(),watermarkToken: generateWatermarkToken(userId, username, lessonId),kind: "r2" as const,youtubeId: null,};} catch (err) {// ✅ SECURITY FIX (post-audit): FAIL CLOSED. The previous fallback returned
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879/** * Video protection — YouTube branch tests (hybrid playback conversion). * * The lesson videoUrl may now be a YouTube link from the channel's playlist. * getSecureVideoUrl MUST branch BEFORE any R2 presigning (presigning a * youtube.com URL used to throw → fail-closed 503 "Video temporarily * unavailable" — the exact regression the conversion had to prevent). * * These tests mock the R2 client so the R2 branch stays hermetic, and assert: * 1. YouTube refs (every supported shape) return kind="youtube" + the id * + an https://www.youtube-nocookie.com/embed/... URL — with NO R2 call. * 2. R2 keys still take the legacy path (kind="r2", presigned). * 3. Empty videoUrl returns the inert default (kind="r2", youtubeId=null). */import { beforeEach, describe, expect, it, vi } from "vitest";
const presignMock = vi.hoisted(() => vi.fn(async ({ objectKey }: { objectKey: string }) => `https://presigned.r2.test/${objectKey}?sig=abc`));
vi.mock("./r2", () => ({ generateR2PresignedUrl: presignMock, getR2ObjectMetadata: vi.fn(async () => ({ exists: false })),}));
vi.mock("./env", () => ({ env: { FRONTEND_URL: "https://ahmedelbaz.qzz.io", WATERMARK_SECRET: undefined },}));
vi.mock("./logger.js", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },}));
import { getSecureVideoUrl } from "./video-protection";
const base = { userId: 7, lessonId: 42, username: "tester",};
describe("getSecureVideoUrl — YouTube branch", () => { beforeEach(() => { presignMock.mockClear(); });
it.each([ ["https://www.youtube.com/watch?v=dQw4w9WgXcQ", "dQw4w9WgXcQ"], ["https://youtu.be/dQw4w9WgXcQ", "dQw4w9WgXcQ"], ["https://www.youtube.com/shorts/dQw4w9WgXcQ", "dQw4w9WgXcQ"], ["dQw4w9WgXcQ", "dQw4w9WgXcQ"], ])("branches %s → kind=youtube without touching R2", async (videoUrl, expectedId) => { const result = await getSecureVideoUrl({ ...base, videoUrl });
expect(result.kind).toBe("youtube"); expect(result.youtubeId).toBe(expectedId); expect(result.hlsUrl).toBeNull(); expect(result.videoUrl).toMatch(/^https:\/\/www\.youtube-nocookie\.com\/embed\//); expect(new URL(result.videoUrl).searchParams.get("origin")).toBeTruthy(); // The critical contract: ZERO R2 activity for YouTube refs. expect(presignMock).not.toHaveBeenCalled(); });
it("keeps the legacy R2 path intact for object keys", async () => { const result = await getSecureVideoUrl({ ...base, videoUrl: "etap/lesson01.mp4" });
expect(result.kind).toBe("r2"); expect(result.youtubeId).toBeNull(); expect(result.videoUrl).toBe("https://presigned.r2.test/etap/lesson01.mp4?sig=abc"); expect(presignMock).toHaveBeenCalledTimes(1); });
it("empty videoUrl returns the inert default", async () => { const result = await getSecureVideoUrl({ ...base, videoUrl: "" });
expect(result.kind).toBe("r2"); expect(result.youtubeId).toBeNull(); expect(result.videoUrl).toBe(""); expect(presignMock).not.toHaveBeenCalled(); });});215 unmodified lines216217218219220221215 unmodified linesreturn `https://www.youtube.com/watch?v=${videoId}&list=${PLAYLIST_ID}`;}/*** One detection pass. Returns the episodes that were announced this tick.*215 unmodified lines216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245215 unmodified linesreturn `https://www.youtube.com/watch?v=${videoId}&list=${PLAYLIST_ID}`;}/** The playlist id the watcher follows (exposed for the admin import dialog). */export function getPlaylistId(): string {return PLAYLIST_ID;}/*** Fetch the channel playlist for the ADMIN LESSON-IMPORT dialog.* Reuses the watcher's robust multi-source pipeline (InnerTube → HTML → RSS,* merged by union) so the dialog shows every video even when one source is* throttled. Read-only: it never touches watcher state or notifications.*/export async function fetchPlaylistVideosForImport(): Promise<Array<{ videoId: string; title: string; watchUrl: string; thumbnailUrl: string }>> {const { buildYouTubeThumbnailUrl } = await import("../../src/lib/youtube-url");const videos = await fetchAllSources();return videos.filter((v) => v.videoId).map((v) => ({videoId: v.videoId,title: v.title,watchUrl: watchUrl(v.videoId),thumbnailUrl: buildYouTubeThumbnailUrl(v.videoId),}));}/*** One detection pass. Returns the episodes that were announced this tick.*
41 unmodified lines424344454647484 unmodified lines53545556575820 unmodified lines798081828384854 unmodified lines90919293949541 unmodified linesconst cspDirectives = ["default-src 'self'",`script-src 'self' 'nonce-${nonce}' https://cdn.jsdelivr.net https://www.clarity.ms https://accounts.google.com https://oauth2.googleapis.com`,"worker-src 'self'","style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com","font-src 'self' https://fonts.gstatic.com",4 unmodified lines// were CSP-blocked: the player rendered but the browser refused to// fetch ("no supported sources") in production too."media-src 'self' blob: https:","connect-src 'self' https://api.openrouter.ai https://*.aivencloud.com https://www.clarity.ms https://www.googleapis.com https://accounts.google.com","frame-ancestors 'none'","base-uri 'self'",20 unmodified lines// nonce-based CSP but prevents the site from breaking on the custom domain.const cspDirectives = ["default-src 'self'","script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://www.clarity.ms https://accounts.google.com https://oauth2.googleapis.com","worker-src 'self'","style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com","font-src 'self' https://fonts.gstatic.com",4 unmodified lines// were CSP-blocked: the player rendered but the browser refused to// fetch ("no supported sources") in production too."media-src 'self' blob: https:","connect-src 'self' https://api.openrouter.ai https://*.aivencloud.com https://www.clarity.ms https://www.googleapis.com https://accounts.google.com","frame-ancestors 'none'","base-uri 'self'",41 unmodified lines424344454647484 unmodified lines53545556575859606162636420 unmodified lines858687888990914 unmodified lines9697989910010110210310441 unmodified linesconst cspDirectives = ["default-src 'self'",`script-src 'self' 'nonce-${nonce}' https://cdn.jsdelivr.net https://www.clarity.ms https://accounts.google.com https://oauth2.googleapis.com https://www.youtube.com https://s.ytimg.com`,"worker-src 'self'","style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com","font-src 'self' https://fonts.gstatic.com",4 unmodified lines// were CSP-blocked: the player rendered but the browser refused to// fetch ("no supported sources") in production too."media-src 'self' blob: https:",// 🎬 YOUTUBE-BASED LESSON PLAYBACK: lessons stream from the channel's// YouTube playlist INSIDE the site's own player screen — nothing is// hosted on our server. frame-src allows the embedded player, the// script hosts feed the IFrame API (www.youtube.com/iframe_api →// s.ytimg.com widget bundle). Everything else stays locked down."frame-src 'self' https://www.youtube-nocookie.com https://www.youtube.com","connect-src 'self' https://api.openrouter.ai https://*.aivencloud.com https://www.clarity.ms https://www.googleapis.com https://accounts.google.com","frame-ancestors 'none'","base-uri 'self'",20 unmodified lines// nonce-based CSP but prevents the site from breaking on the custom domain.const cspDirectives = ["default-src 'self'","script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://www.clarity.ms https://accounts.google.com https://oauth2.googleapis.com https://www.youtube.com https://s.ytimg.com","worker-src 'self'","style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com","font-src 'self' https://fonts.gstatic.com",4 unmodified lines// were CSP-blocked: the player rendered but the browser refused to// fetch ("no supported sources") in production too."media-src 'self' blob: https:",// 🎬 Same YouTube allowances for the CDN-cached fallback CSP (see the// nonce block above for the full rationale)."frame-src 'self' https://www.youtube-nocookie.com https://www.youtube.com","connect-src 'self' https://api.openrouter.ai https://*.aivencloud.com https://www.clarity.ms https://www.googleapis.com https://accounts.google.com","frame-ancestors 'none'","base-uri 'self'",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""LOCAL E2E — YouTube-hybrid lesson playback (the playlist conversion).
Runs the real vite frontend and intercepts tRPC to control the lesson data: Scenario YT — lesson videoUrl is a YouTube playlist link: lessonVideo returns kind="youtube" + youtubeId → the site must render the EMBEDDED YouTube player inside its own screen (iframe youtube-nocookie + site chrome), NOT a <video> tag, and NOT navigate the user away. Scenario R2 — lesson videoUrl is an R2 key: lessonVideo returns kind="r2" + presigned URL → the legacy ProtectedVideoPlayer (<video> element) must still render. Verifies the hybrid contract end-to-end at the UI level.
Run: DISPLAY=:99 python3 scripts/youtube_lesson_local_e2e.py(vite dev server must be running on 127.0.0.1:5173 — started by the caller.)"""import jsonimport reimport subprocessimport sysimport time
from playwright.sync_api import sync_playwright
BASE = "http://127.0.0.1:5173"COURSE_PATH = "/courses/etap-complete-course"OUT = "/home/z/my-project/work/elbaz-platform/scripts/shots_yt_e2e"YT_ID = "dQw4w9WgXcQ"USER_JSON = {"id": 54, "username": "yte2e01", "name": "YT E2E", "role": "user", "email": None}
COURSE_JSON = { "id": 1, "slug": "etap-complete-course", "titleAr": "كورس ETAP الشامل", "titleEn": "ETAP Complete Course", "descriptionAr": "وصف", "descriptionEn": "desc", "learningOutcomesAr": [], "learningOutcomesEn": [], "thumbnail": None, "price": "1999", "originalPrice": "2500", "isPremium": False, "isPublished": True, "rating": "4.8", "studentCount": 120, "durationHours": 40, "category": {"nameEn": "Power", "nameAr": "قوى كهربية"}, "lessons": [ {"id": 101, "courseId": 1, "titleAr": "درس يوتيوب", "titleEn": "YouTube lesson", "descriptionAr": "", "descriptionEn": "", "isFree": True, "durationMinutes": 15, "sortOrder": 1, "isPublished": True}, {"id": 102, "courseId": 1, "titleAr": "درس محلي R2", "titleEn": "R2 lesson", "descriptionAr": "", "descriptionEn": "", "isFree": True, "durationMinutes": 20, "sortOrder": 2, "isPublished": True}, ],}
ME_OK = {"result": {"data": {"json": USER_JSON}}}CHECK_ENROLL = {"result": {"data": {"json": {"enrolled": True, "isCompleted": False, "progress": 0}}}}
def lesson_video_response(kind: str): if kind == "youtube": payload = { "videoUrl": f"https://www.youtube-nocookie.com/embed/{YT_ID}?enablejsapi=1", "hlsUrl": None, "expiresAt": "2030-01-01T00:00:00.000Z", "watermarkToken": "tok", "kind": "youtube", "youtubeId": YT_ID, } else: payload = { "videoUrl": "https://presigned.r2.test/etap/lesson01.mp4?sig=abc", "hlsUrl": None, "expiresAt": "2030-01-01T00:00:00.000Z", "watermarkToken": "tok", "kind": "r2", "youtubeId": None, } return 200, {"result": {"data": {"json": payload}}}
def saved_position(): return 200, {"result": {"data": {"json": {"lastPosition": 0, "watchedSeconds": 0, "isCompleted": False}}}}
def envelope_for_get(name: str): if name == "auth.me": return 200, ME_OK if name == "course.checkEnrollment": return 200, CHECK_ENROLL if name.startswith("course.lessonVideo"): # query contains input=…&lessonId — route both lesson ids to their kind return None # handled in handler (needs lesson id) if name.startswith("course.getSavedPosition"): return saved_position() if name.startswith("course.bySlug"): return 200, {"result": {"data": {"json": COURSE_JSON}}} return None
fails, notes = [], []def check(name, cond, detail=""): print(f"[{'PASS' if cond else 'FAIL'}] {name}" + (f" — {detail}" if detail else "")) (notes if cond else fails).append((name, detail))
with sync_playwright() as p: browser = p.chromium.launch(headless=True)
for scenario, lesson_id, kind in (("YT", 101, "youtube"), ("R2", 102, "r2")): ctx = browser.new_context(viewport={"width": 1280, "height": 900}) ctx.add_cookies([{"name": "elbaz_auth_flag", "value": "1", "url": BASE}]) pg = ctx.new_page()
def handler(route): url = route.request.url method = route.request.method if "/api/trpc/" not in url: return route.continue_() path = url.split("/api/trpc/")[1].split("?")[0] if method == "GET": if path.startswith("course.lessonVideo"): st, body = lesson_video_response(kind) return route.fulfill(status=st, content_type="application/json", body=json.dumps(body)) packed = envelope_for_get(path) if packed: st, body = packed return route.fulfill(status=st, content_type="application/json", body=json.dumps(body)) return route.continue_()
pg.route("**/api/trpc/**", handler)
pg.goto(BASE + COURSE_PATH, wait_until="domcontentloaded", timeout=45_000) pg.wait_for_timeout(4_000) # Dev-only: the vite dev API env validation throws an error overlay that # blocks clicks — production serves the real API so this never happens. pg.evaluate("() => document.querySelector('vite-error-overlay')?.remove()") # Cookie consent banner (same handling as the production E2Es) try: pg.get_by_role("button", name=re.compile("accept|موافق|قبول", re.I)).click(timeout=2_000) except Exception: pass pg.evaluate("() => document.querySelector('[data-testid=cookie-consent-backdrop]')?.click()") pg.wait_for_timeout(500)
# Click the scenario's lesson (language mirrors the browser default — try both) lesson_texts = ("YouTube lesson", "درس يوتيوب") if kind == "youtube" else ("R2 lesson", "درس محلي R2") target = None for t in lesson_texts: loc = pg.get_by_text(t, exact=False) if loc.count() > 0: target = loc.first break if not target: check(f"{scenario}) lesson row visible", False, "neither AR nor EN title found") ctx.close() continue target.click() pg.wait_for_timeout(2_000) # Wait for the video area to resolve deadline = time.time() + 15 ready = False while time.time() < deadline: if pg.locator("[data-youtube-player]").count() > 0 or pg.locator("video[data-lesson-id], video").count() > 0: ready = True break pg.wait_for_timeout(500) check(f"{scenario}) video area rendered", ready)
if kind == "youtube": yt_host = pg.locator("[data-youtube-player] iframe[src*='youtube-nocookie.com']").count() check(f"{scenario}) embedded YouTube iframe present", yt_host > 0, f"iframes={pg.locator('iframe').count()}") still_here = COURSE_PATH in pg.url check(f"{scenario}) user stayed on the site (no redirect)", still_here, pg.url) pg.screenshot(path=f"{OUT}/{scenario}_youtube_player.png") chip = pg.get_by_text("يوتيوب", exact=False).count() + pg.get_by_text("YouTube", exact=False).count() check(f"{scenario}) provenance chip visible", chip > 0) else: legacy_video = pg.locator("video").count() no_yt_frame = pg.locator("[data-youtube-player]").count() check(f"{scenario}) legacy <video> player present", legacy_video > 0, f"videos={legacy_video}") check(f"{scenario}) YouTube player NOT rendered for R2 lesson", no_yt_frame == 0) pg.screenshot(path=f"{OUT}/{scenario}_r2_player.png")
ctx.close()
browser.close()
print("\n=== RESULT ===")if fails: print("FAILURES:") for f in fails: print(" -", f) sys.exit(1)print(f"ALL LOCAL E2E CHECKS PASSED ✓ ({len(notes)} checks)")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312/** * YouTubeLessonPlayer — embedded YouTube playback inside the site's player * screen. ═══════════════════════════════════════════════════════════════════ * * The lesson's video streams from the channel's YouTube playlist; NOTHING is * hosted on (or proxied through) our server. The viewer never leaves the * site: the iframe fills the same aspect-video slot the self-hosted player * used, with YouTube's own controls inside the frame. * * Watch-tracking parity with the R2 player (useWatchTracker contract): * PLAYING → heartbeat timer every 60s → course.heartbeat(watchedSeconds, lastPosition) * PAUSED → stop + final heartbeat * ENDED → stop + course.markWatched (once) → lesson completed → certificate * tab hide → pause the video + final heartbeat (integrity + bandwidth) * onReady → auto-resume from the saved position (same >5s rule) */import { useCallback, useEffect, useRef, useState } from "react";import { trpc } from "@/providers/trpc";import { trackEvent } from "@/lib/clarity";import { buildYouTubeWatchUrl } from "@/lib/youtube-url";import { loadYouTubeIframeApi, YT_STATE, type YTPlayer,} from "@/lib/youtube-player-api";
interface YouTubeLessonPlayerProps { readonly videoId: string; readonly lessonId?: number; readonly courseId?: number; readonly lessonTitle: string; readonly lang: "en" | "ar"; readonly isTrackingEnabled?: boolean; readonly heartbeatIntervalMs?: number; /** Fired when the video ends and the server marks the lesson complete. */ readonly onLessonCompleted?: () => void;}
export default function YouTubeLessonPlayer({ videoId, lessonId, courseId, lessonTitle, lang, isTrackingEnabled, heartbeatIntervalMs = 60_000, onLessonCompleted,}: YouTubeLessonPlayerProps) { const mountRef = useRef<HTMLDivElement>(null); const playerRef = useRef<YTPlayer | null>(null); const timerRef = useRef<ReturnType<typeof setInterval> | null>(null); // Same pattern as useWatchTracker: lazy-set inside effects/handlers (React // Compiler purity rule — no Date.now() in ref initializers). const lastTickRef = useRef(0); const lastPositionRef = useRef(0); const isPlayingRef = useRef(false); const lessonIdRef = useRef<number | undefined>(lessonId); const completedLessonRef = useRef<number | null>(null); const [ready, setReady] = useState(false); const [failed, setFailed] = useState(false);
useEffect(() => { lessonIdRef.current = lessonId; }, [lessonId]);
const onLessonCompletedRef = useRef(onLessonCompleted); useEffect(() => { onLessonCompletedRef.current = onLessonCompleted; }, [onLessonCompleted]);
// ── Heartbeat mutations (silent-fail, same contract as useWatchTracker) ── const heartbeatMutation = trpc.course.heartbeat.useMutation({ onError: (err) => console.warn("[YTPlayer] heartbeat failed:", err.message), }); const markWatchedMutation = trpc.course.markWatched.useMutation({ onSuccess: () => onLessonCompletedRef.current?.(), onError: (err) => console.warn("[YTPlayer] markWatched failed:", err.message), });
const { data: savedProgress } = trpc.course.getSavedPosition.useQuery( { lessonId: lessonId || 0 }, { enabled: !!isTrackingEnabled && !!lessonId && lessonId > 0, staleTime: 5 * 60 * 1000 }, );
const sendHeartbeat = useCallback(() => { if (!lessonIdRef.current) return; const player = playerRef.current; const currentPosition = Math.floor(player?.getCurrentTime() || 0); const now = Date.now(); const watchedSeconds = Math.floor((now - lastTickRef.current) / 1000); if (watchedSeconds < 1 && currentPosition === lastPositionRef.current) return;
lastPositionRef.current = currentPosition; lastTickRef.current = now; heartbeatMutation.mutate({ lessonId: lessonIdRef.current, watchedSeconds: Math.min(watchedSeconds, 300), // server caps at 5 min/beat lastPosition: currentPosition, }); }, [heartbeatMutation]);
const startTracking = useCallback(() => { if (timerRef.current || !lessonIdRef.current) return; isPlayingRef.current = true; lastTickRef.current = Date.now(); lastPositionRef.current = Math.floor(playerRef.current?.getCurrentTime() || 0); timerRef.current = setInterval(sendHeartbeat, heartbeatIntervalMs); }, [heartbeatIntervalMs, sendHeartbeat]);
const stopTracking = useCallback(() => { isPlayingRef.current = false; if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } sendHeartbeat(); }, [sendHeartbeat]);
// ── Player lifecycle: create once on mount, destroy on unmount ── // The parent mounts this component with key={videoId} — a new video always // remounts fresh (React's endorsed pattern), so no in-effect state resets. useEffect(() => { let cancelled = false;
void loadYouTubeIframeApi() .then((YT) => { if (cancelled || !mountRef.current) return; playerRef.current = new YT.Player(mountRef.current, { videoId, host: "https://www.youtube-nocookie.com", playerVars: { rel: 0, playsinline: 1, modestbranding: 1, cc_load_policy: 1, hl: "ar", // enablejsapi/origin are set automatically by the widget API // from this host config — no need to pass them here. }, events: { onReady: () => { if (cancelled) return; setReady(true); }, onStateChange: (event) => { if (cancelled) return; switch (event.data) { case YT_STATE.PLAYING: trackEvent("video_play", { lessonId: lessonIdRef.current || 0, courseId: courseId || 0, lessonTitle, source: "youtube", }); startTracking(); break; case YT_STATE.PAUSED: case YT_STATE.BUFFERING: if (event.data === YT_STATE.PAUSED) stopTracking(); break; case YT_STATE.ENDED: { stopTracking(); const id = lessonIdRef.current; if (id && completedLessonRef.current !== id) { completedLessonRef.current = id; markWatchedMutation.mutate({ lessonId: id }); } break; } default: break; } }, onError: () => { if (!cancelled) setFailed(true); }, }, }); }) .catch((err: unknown) => { if (!cancelled) { console.warn("[YTPlayer] API unavailable:", err instanceof Error ? err.message : err); setFailed(true); } }); return () => { cancelled = true; if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } try { playerRef.current?.destroy(); } catch { // already destroyed by a re-render race — nothing to do } playerRef.current = null; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [videoId]);
// Auto-resume from the saved position (same >5s rule as the R2 player). useEffect(() => { if (!ready || !savedProgress?.lastPosition) return; const resume = savedProgress.lastPosition; if (resume > 5) { playerRef.current?.seekTo(Math.max(0, resume - 3), true); } // Only on first ready per lesson — resumePosition is stable afterwards. // eslint-disable-next-line react-hooks/exhaustive-deps }, [ready, lessonId]);
// Tab hidden → pause + final heartbeat (same integrity rule as R2 path). useEffect(() => { const handleVisibilityChange = () => { if (document.hidden && isPlayingRef.current) { try { playerRef.current?.pauseVideo(); } catch { // player already gone — heartbeat below still runs } sendHeartbeat(); } }; document.addEventListener("visibilitychange", handleVisibilityChange); return () => document.removeEventListener("visibilitychange", handleVisibilityChange); }, [sendHeartbeat]);
// Page unload → sendBeacon final save (mirrors the R2 player path). useEffect(() => { const handleBeforeUnload = () => { if (!isPlayingRef.current || !lessonIdRef.current) return; const currentPosition = Math.floor(playerRef.current?.getCurrentTime() || 0); const watchedSeconds = Math.floor((Date.now() - lastTickRef.current) / 1000); if (watchedSeconds >= 1 || currentPosition !== lastPositionRef.current) { const blob = new Blob( [JSON.stringify({ lessonId: lessonIdRef.current, watchedSeconds: Math.min(watchedSeconds, 120), lastPosition: currentPosition, })], { type: "application/json" }, ); // eslint-disable-next-line @typescript-eslint/no-explicit-any const baseUrl = (globalThis as any).Capacitor?.isNativePlatform?.() ? (import.meta.env.VITE_API_URL || "https://ahmedelbaz.qzz.io") : ""; navigator.sendBeacon?.(`${baseUrl}/api/trpc/course.heartbeat`, blob); } }; globalThis.addEventListener("beforeunload", handleBeforeUnload); return () => globalThis.removeEventListener("beforeunload", handleBeforeUnload); }, []);
const watchLink = buildYouTubeWatchUrl(videoId);
return ( <div className="relative bg-black" role="application" aria-label={lang === "en" ? "Embedded YouTube lesson player" : "مشغل درس مدمج من يوتيوب"} data-youtube-player={videoId} > {/* Screen zone (16:9) — mount + overlays live INSIDE this relative box so a fallback never covers the provenance strip below. */} <div className="relative aspect-video w-full overflow-hidden"> {/* Mount target — the widget API replaces this div with the iframe. */} <div ref={mountRef} className="h-full w-full" />
{!ready && !failed && ( <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#0f172a] to-[#1e293b]"> <p className="text-sm text-[#94a3b8]"> {lang === "en" ? "Preparing the video..." : "بتجهّز الشاشة..."} </p> </div> )}
{failed && ( <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-gradient-to-br from-[#0f172a] to-[#1e293b] px-6 text-center"> <p className="text-sm text-[#94a3b8]"> {lang === "en" ? "The embedded player couldn't load here." : "مشغل يوتيوب ماتحمّلش هنا — افتح الفيديو مباشرة:"} </p> <a href={watchLink} target="_blank" rel="noopener noreferrer" className="rounded-lg bg-[rgba(6,182,212,0.15)] px-4 py-2 text-sm font-semibold text-[#22d3ee] transition-colors hover:bg-[rgba(6,182,212,0.25)]" > {lang === "en" ? "Open on YouTube" : "افتح الفيديو على يوتيوب"} </a> </div> )} </div>
{/* Honest provenance chip — the video plays from the channel's YouTube playlist inside the site; keeps the open-internet contract clear. */} <div className="flex items-center justify-between gap-2 bg-[rgba(13,20,32,0.85)] px-3 py-1.5"> <span className="truncate text-[11px] text-[#64748b]">{lessonTitle}</span> <a href={watchLink} target="_blank" rel="noopener noreferrer" className="shrink-0 text-[10px] font-medium text-[#64748b] transition-colors hover:text-[#22d3ee]" > {lang === "en" ? "▶ YouTube" : "▶ يوتيوب"} </a> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132/** * YouTube IFrame Player API loader — client-side singleton. * ═══════════════════════════════════════════════════════════════════════════ * * The embedded lesson player needs the official widget API so the site can * know play/pause/ended (heartbeat watch-time tracking + completion marking * — the same contract the self-hosted <video> player had). The API script is * loaded once per page from https://www.youtube.com/iframe_api (allowed by * CSP script-src) and resolves to a minimal typed surface — no extra npm dep. */
export interface YTPlayer { playVideo(): void; pauseVideo(): void; stopVideo(): void; destroy(): void; getCurrentTime(): number; getDuration(): number; seekTo(seconds: number, allowSeekAhead: boolean): void; getPlayerState(): number; loadVideoById(videoId: string): void;}
export interface YTPlayerEvent { target: YTPlayer; data: number;}
interface YTNamespace { Player: new ( element: HTMLElement | string, config: { videoId: string; host?: string; playerVars?: Record<string, string | number>; events?: { onReady?: (event: YTPlayerEvent) => void; onStateChange?: (event: YTPlayerEvent) => void; onError?: (event: YTPlayerEvent) => void; }; }, ) => YTPlayer; PlayerState: { UNSTARTED: number; ENDED: number; PLAYING: number; PAUSED: number; BUFFERING: number; CUED: number; };}
declare global { interface Window { YT?: YTNamespace; onYouTubeIframeAPIReady?: () => void; }}
/** YT.PlayerState codes we care about (stable public contract). */export const YT_STATE = { ENDED: 0, PLAYING: 1, PAUSED: 2, BUFFERING: 3,} as const;
const API_SRC = "https://www.youtube.com/iframe_api";
let loaderPromise: Promise<YTNamespace> | null = null;
/** * Load (or wait for) the IFrame API exactly once. Rejects after the timeout * so the player can render its fallback UI instead of hanging forever. */export function loadYouTubeIframeApi(timeoutMs = 20_000): Promise<YTNamespace> { if (loaderPromise) return loaderPromise;
loaderPromise = new Promise<YTNamespace>((resolve, reject) => { // Already present (another mount loaded it earlier)? if (typeof window !== "undefined" && window.YT?.Player) { resolve(window.YT); return; }
const timer = setTimeout(() => { // Do not cache the rejection — a retry (next mount) may succeed. loaderPromise = null; reject(new Error("YouTube IFrame API load timed out")); }, timeoutMs);
const settle = (ns: YTNamespace | undefined) => { clearTimeout(timer); if (ns?.Player) { resolve(ns); } else { loaderPromise = null; reject(new Error("YouTube IFrame API failed to initialize")); } };
if (typeof window === "undefined") { reject(new Error("YouTube IFrame API requires a browser")); return; }
const previous = window.onYouTubeIframeAPIReady; window.onYouTubeIframeAPIReady = () => { try { previous?.(); } catch { // A stale callback from another consumer must not break ours. } settle(window.YT); };
const existing = document.querySelector<HTMLScriptElement>(`script[src="${API_SRC}"]`); if (!existing) { const script = document.createElement("script"); script.src = API_SRC; script.async = true; script.addEventListener("error", () => { clearTimeout(timer); loaderPromise = null; reject(new Error("YouTube IFrame API script failed to load")); }); document.head.appendChild(script); } });
return loaderPromise;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import { describe, expect, it } from "vitest";import { buildYouTubeEmbedUrl, buildYouTubeThumbnailUrl, buildYouTubeWatchUrl, extractYouTubeId, isYouTubeVideoRef,} from "./youtube-url";
describe("extractYouTubeId", () => { const ID = "dQw4w9WgXcQ";
it("accepts a bare 11-char id", () => { expect(extractYouTubeId(ID)).toBe(ID); });
it("accepts watch?v= URLs", () => { expect(extractYouTubeId(`https://www.youtube.com/watch?v=${ID}`)).toBe(ID); expect(extractYouTubeId(`https://youtube.com/watch?v=${ID}&t=90s`)).toBe(ID); expect(extractYouTubeId(`https://m.youtube.com/watch?v=${ID}`)).toBe(ID); });
it("accepts youtu.be shortlinks (with and without scheme)", () => { expect(extractYouTubeId(`https://youtu.be/${ID}`)).toBe(ID); expect(extractYouTubeId(`https://youtu.be/${ID}?si=xyz`)).toBe(ID); expect(extractYouTubeId(`youtu.be/${ID}`)).toBe(ID); });
it("accepts shorts / embed / live / legacy v paths", () => { expect(extractYouTubeId(`https://www.youtube.com/shorts/${ID}`)).toBe(ID); expect(extractYouTubeId(`https://www.youtube.com/embed/${ID}`)).toBe(ID); expect(extractYouTubeId(`https://www.youtube.com/live/${ID}`)).toBe(ID); expect(extractYouTubeId(`https://www.youtube.com/v/${ID}`)).toBe(ID); expect(extractYouTubeId(`https://www.youtube-nocookie.com/embed/${ID}`)).toBe(ID); });
it("accepts the oEmbed endpoint whose url param carries a watch link", () => { const target = encodeURIComponent(`https://www.youtube.com/watch?v=${ID}`); expect(extractYouTubeId(`https://www.youtube.com/oembed?url=${target}`)).toBe(ID); });
it("accepts padded/uppercased surrounding whitespace", () => { expect(extractYouTubeId(` ${ID} `)).toBe(ID); });
it("rejects playlist-only links without a video", () => { expect(extractYouTubeId("https://www.youtube.com/playlist?list=PLabc123")).toBeNull(); });
it("rejects R2 object keys and arbitrary URLs", () => { expect(extractYouTubeId("etap/lesson01.mp4")).toBeNull(); expect(extractYouTubeId("https://acct.r2.cloudflarestorage.com/etap/lesson01.mp4?X-Amz-Signature=x")).toBeNull(); expect(extractYouTubeId("https://vimeo.com/123456789")).toBeNull(); });
it("rejects malformed ids (too short, bad charset, empty)", () => { expect(extractYouTubeId("short")).toBeNull(); expect(extractYouTubeId("https://www.youtube.com/watch?v=toolongid12345")).toBeNull(); expect(extractYouTubeId("https://www.youtube.com/watch?v=has!special!")).toBeNull(); expect(extractYouTubeId("")).toBeNull(); expect(extractYouTubeId(null)).toBeNull(); expect(extractYouTubeId(undefined)).toBeNull(); });});
describe("isYouTubeVideoRef", () => { it("is the boolean mirror of extractYouTubeId", () => { expect(isYouTubeVideoRef("https://youtu.be/dQw4w9WgXcQ")).toBe(true); expect(isYouTubeVideoRef("etap/lesson01.mp4")).toBe(false); expect(isYouTubeVideoRef("")).toBe(false); });});
describe("buildYouTubeEmbedUrl", () => { it("uses youtube-nocookie with jsapi, origin and safe params", () => { const url = new URL(buildYouTubeEmbedUrl("dQw4w9WgXcQ", "https://ahmedelbaz.qzz.io")); expect(url.origin).toBe("https://www.youtube-nocookie.com"); expect(url.pathname).toBe("/embed/dQw4w9WgXcQ"); expect(url.searchParams.get("enablejsapi")).toBe("1"); expect(url.searchParams.get("origin")).toBe("https://ahmedelbaz.qzz.io"); expect(url.searchParams.get("rel")).toBe("0"); expect(url.searchParams.get("playsinline")).toBe("1"); expect(url.searchParams.get("modestbranding")).toBe("1"); expect(url.searchParams.get("hl")).toBe("ar"); });
it("throws on an invalid id instead of building a broken frame", () => { expect(() => buildYouTubeEmbedUrl("not-an-id", "https://ahmedelbaz.qzz.io")).toThrow(); expect(() => buildYouTubeEmbedUrl("../../etc", "https://ahmedelbaz.qzz.io")).toThrow(); });});
describe("buildYouTubeWatchUrl", () => { it("builds the watch URL, with playlist when given", () => { expect(buildYouTubeWatchUrl("dQw4w9WgXcQ")).toBe("https://www.youtube.com/watch?v=dQw4w9WgXcQ"); const withList = new URL(buildYouTubeWatchUrl("dQw4w9WgXcQ", "PLeeb5_Qjhcgc")); expect(withList.searchParams.get("v")).toBe("dQw4w9WgXcQ"); expect(withList.searchParams.get("list")).toBe("PLeeb5_Qjhcgc"); });});
describe("buildYouTubeThumbnailUrl", () => { it("builds the public i.ytimg.com thumbnail and rejects bad ids", () => { expect(buildYouTubeThumbnailUrl("dQw4w9WgXcQ")).toBe("https://i.ytimg.com/vi/dQw4w9WgXcQ/mqdefault.jpg"); expect(buildYouTubeThumbnailUrl("dQw4w9WgXcQ", "hq")).toBe("https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg"); expect(() => buildYouTubeThumbnailUrl("bad")).toThrow(); });});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122/** * YouTube URL — pure parsing & builders, shared by SERVER and CLIENT. * ═══════════════════════════════════════════════════════════════════════════ * * The platform plays lesson videos from the channel's YouTube playlist inside * its own player screen (no video files hosted on our server). This module is * the single source of truth for "is this value a YouTube video reference and * which video" — used by: * - api/lib/video-protection.ts (server: branch R2 presign vs YouTube pass-through) * - src/pages/Admin.tsx (client: live hint + playlist import) * - src/components/YouTubeLessonPlayer.tsx (client: embed playback) * * Kept dependency-free (no Node APIs, no DOM) so tsx/Vite/vitest can all load it. */
/** YouTube video IDs are exactly 11 chars of [A-Za-z0-9_-]. */const VIDEO_ID_RE = /^[A-Za-z0-9_-]{11}$/;
/** Hosts that can carry a video id in their path or query. */const YT_HOST_RE = /(^|\.)(youtube\.com|youtube-nocookie\.com|youtu\.be)$/i;
/** * Extract an 11-char YouTube video id from ANY common shape: * https://www.youtube.com/watch?v=ID (watch page) * https://youtu.be/ID (share shortlink) * https://www.youtube.com/shorts/ID (Shorts) * https://www.youtube.com/embed/ID (embed path) * https://www.youtube.com/live/ID (live premiere replay) * https://www.youtube.com/v/ID (legacy /v/ player) * https://www.youtube.com/oembed?url=... (oEmbed endpoint) * bare "dQw4w9WgXcQ" (raw id, as admins paste it) * Returns null for playlist-only links, R2 keys, and anything else. */export function extractYouTubeId(value: string | null | undefined): string | null { if (typeof value !== "string") return null; const raw = value.trim(); if (!raw) return null;
// Bare id (what an admin pastes after copying the ?v= value). if (VIDEO_ID_RE.test(raw)) return raw;
let url: URL; try { // youtu.be links may be pasted without a scheme. url = new URL(raw.startsWith("http") ? raw : `https://${raw}`); } catch { return null; }
if (!YT_HOST_RE.test(url.hostname)) return null;
// Query forms first: watch?v=, /embed?v=, oembed?url=<encoded watch link>. const v = url.searchParams.get("v"); if (v && VIDEO_ID_RE.test(v)) return v; const oembedTarget = url.searchParams.get("url"); if (oembedTarget && extractYouTubeId(oembedTarget)) { return extractYouTubeId(oembedTarget); }
// Path forms: /shorts/ID, /embed/ID, /live/ID, /v/ID, youtu.be/ID. const parts = url.pathname.split("/").filter(Boolean); if (parts.length === 0) return null;
if (url.hostname === "youtu.be") { const id = parts[0] ?? ""; return VIDEO_ID_RE.test(id) ? id : null; }
const pathPrefixes = ["shorts", "embed", "live", "v"]; const [head, tail] = parts; if (head && tail && pathPrefixes.includes(head) && VIDEO_ID_RE.test(tail)) { return tail; }
// /watch/ID (rare legacy form) — pathname /watch/ID if (head === "watch" && tail && VIDEO_ID_RE.test(tail)) return tail;
return null;}
/** True when the value resolves to a playable YouTube video (not an R2 key). */export function isYouTubeVideoRef(value: string | null | undefined): boolean { return extractYouTubeId(value) !== null;}
/** * Build the privacy-enhanced embed URL for a video. `origin` is REQUIRED so * the widget API can scope its postMessage channel to our site (YouTube * rejects enablejsapi frames without a matching origin). * Params: rel=0 (same-channel suggestions only), playsinline (iOS), modest * branding, captions default on, no cookie tracking unless the user plays. */export function buildYouTubeEmbedUrl(videoId: string, origin: string): string { if (!VIDEO_ID_RE.test(videoId)) { throw new Error(`Invalid YouTube video id: ${JSON.stringify(videoId)}`); } const params = new URLSearchParams({ enablejsapi: "1", origin, rel: "0", playsinline: "1", modestbranding: "1", cc_load_policy: "1", hl: "ar", }); return `https://www.youtube-nocookie.com/embed/${videoId}?${params.toString()}`;}
/** Human-facing watch URL (used by the admin import dialog to store a link). */export function buildYouTubeWatchUrl(videoId: string, playlistId?: string): string { const params = new URLSearchParams({ v: videoId }); if (playlistId) params.set("list", playlistId); return `https://www.youtube.com/watch?${params.toString()}`;}
/** Thumbnail URL (no API key needed — public i.ytimg.com path). */export function buildYouTubeThumbnailUrl(videoId: string, quality: "mq" | "hq" = "mq"): string { if (!VIDEO_ID_RE.test(videoId)) { throw new Error(`Invalid YouTube video id: ${JSON.stringify(videoId)}`); } return `https://i.ytimg.com/vi/${videoId}/${quality}default.jpg`;}8 unmodified lines910111213147 unmodified lines22232425262728293031182 unmodified lines2142152162172182191177 unmodified lines139713981399140014011402140325 unmodified lines14291430143114321433143414354 unmodified lines144014411442144314441445144614477 unmodified lines1455145614571458145914608 unmodified linesLayoutDashboard, Users, BookOpen, Headphones, DollarSign, Phone, FileText, Palette, Tag, Megaphone, Bot, Bell,Plus, Pencil, Trash2, Save, Eye, Zap, TrendingUp, CheckCircle, ChevronLeft, ChevronRight,LogOut, ArrowUpRight, Shield, PlayCircle, Newspaper, X, Menu, MessageSquareText, ThumbsUp, ThumbsDown, Download,} from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";7 unmodified linesimport { toast } from "sonner";import { AiProvidersPanel } from "@/components/admin/AiProvidersPanel";import AdminNotificationPanel from "@/components/AdminNotificationPanel";import { bilingual } from "@/lib/i18n";interface SettingItem { id?: string; key: string; value: string; section: string; type?: string; }interface ThemeItem { id: string; name: string; primaryColor: string; secondaryColor: string; accentColor: string; bgColor: string; textColor: string; cardBgColor: string; borderColor: string; isActive: boolean; createdAt: string; }interface PromoItem { id: string; code: string; discount: number; type: "percentage" | "fixed"; maxUses: number; usedCount: number; status: "active" | "expired" | "used_up"; validFrom: string; validUntil: string; createdAt: string; }interface PromotionItem { id: string; titleEn: string; titleAr: string; subtitleEn: string; subtitleAr: string; discountText: string; ctaTextEn: string; ctaTextAr: string; ctaUrl: string; startDate: string; endDate: string; bgColor: string; textColor: string; buttonColor: string; position: "top" | "bottom"; showCountdown: boolean; isActive: boolean; createdAt: string; }interface CourseItem { id: number; slug: string; titleEn: string; titleAr: string; descriptionEn: string | null; descriptionAr: string | null; shortDescEn?: string | null; shortDescAr?: string | null; thumbnailUrl: string | null; price: number; currency: string; isFeatured: boolean; isPublished: boolean; level: string; category: number | null; studentCount: number; createdAt: Date; updatedAt: Date; }182 unmodified linesconst [showLessonForm, setShowLessonForm] = useState(false);const [editingLesson, setEditingLesson] = useState<LessonItem | null>(null);const [lessonForm, setLessonForm] = useState({ titleEn: "", titleAr: "", descriptionEn: "", descriptionAr: "", videoUrl: "", durationMinutes: 30, isFree: false, isPublished: true });const openLessonForm = (lesson?: LessonItem) => {if (lesson) {1177 unmodified lines<DialogContent className="bg-[#0d1420] border-border max-w-3xl max-h-[85vh] overflow-y-auto"><DialogHeader><DialogTitle className="text-foreground">{isRTL ? `دروس: ${lessonsCourse?.titleAr ?? ""}` : `Lessons: ${lessonsCourse?.titleEn ?? ""}`}</DialogTitle><DialogDescription className="text-text-muted">{(lessonsData?.items as LessonItem[] | undefined)?.length ?? 0} {isRTL ? "درس — أضف رابط الفيديو (R2 أو URL خارجي) لكل درس" : "lessons — add a video URL (R2 key or external URL) per lesson"}</DialogDescription></DialogHeader><div className="space-y-2 py-2">{((lessonsData?.items as LessonItem[] | undefined) ?? []).length === 0 && (25 unmodified lines<DialogContent className="bg-[#0d1420] border-border max-w-xl max-h-[85vh] overflow-y-auto"><DialogHeader><DialogTitle className="text-foreground">{editingLesson ? (isRTL ? "تعديل الدرس" : "Edit Lesson") : (isRTL ? "درس جديد" : "New Lesson")}</DialogTitle><DialogDescription className="text-text-muted">{isRTL ? "رابط الفيديو: مفتاح R2 (مثل etap/lesson01.mp4) أو رابط مباشر" : "Video URL: an R2 object key (e.g. etap/lesson01.mp4) or a direct URL"}</DialogDescription></DialogHeader><div className="grid gap-3 py-2"><div className="grid grid-cols-2 gap-3">4 unmodified lines<div className="space-y-1"><Label className="text-text-muted">{isRTL ? "الوصف (إنجليزي)" : "Description (EN)"}</Label><Textarea rows={2} value={lessonForm.descriptionEn} onChange={(e) => setLessonForm((f) => ({ ...f, descriptionEn: e.target.value }))} className="border-border bg-background text-foreground" /></div><div className="space-y-1"><Label className="text-text-muted">{isRTL ? "الوصف (عربي)" : "Description (AR)"}</Label><Textarea rows={2} value={lessonForm.descriptionAr} onChange={(e) => setLessonForm((f) => ({ ...f, descriptionAr: e.target.value }))} dir="rtl" className="border-border bg-background text-foreground" /></div></div><div className="grid grid-cols-2 gap-3"><div className="space-y-1"><Label className="text-text-muted">{isRTL ? "رابط الفيديو" : "Video URL"}</Label><Input value={lessonForm.videoUrl} onChange={(e) => setLessonForm((f) => ({ ...f, videoUrl: e.target.value }))} placeholder="etap/lesson01.mp4" className="border-border bg-background text-foreground" /></div><div className="space-y-1"><Label className="text-text-muted">{isRTL ? "المدة (دقائق)" : "Duration (min)"}</Label><Input type="number" min={0} max={1440} value={lessonForm.durationMinutes} onChange={(e) => setLessonForm((f) => ({ ...f, durationMinutes: Number(e.target.value) }))} className="border-border bg-background text-foreground" /></div></div><div className="flex items-center gap-6 pt-1">7 unmodified lines</DialogFooter></DialogContent></Dialog>{/* ═══════════════ ARTICLE FORM DIALOG ═══════════════ */}<Dialog open={showArticleForm} onOpenChange={setShowArticleForm}><DialogContent className="bg-[#0d1420] border-border max-w-2xl max-h-[85vh] overflow-y-auto">8 unmodified lines91011121314157 unmodified lines23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495182 unmodified lines2782792802812822832841177 unmodified lines146214631464146514661467146825 unmodified lines14941495149614971498149915004 unmodified lines150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215337 unmodified lines15411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615778 unmodified linesLayoutDashboard, Users, BookOpen, Headphones, DollarSign, Phone, FileText, Palette, Tag, Megaphone, Bot, Bell,Plus, Pencil, Trash2, Save, Eye, Zap, TrendingUp, CheckCircle, ChevronLeft, ChevronRight,LogOut, ArrowUpRight, Shield, PlayCircle, Newspaper, X, Menu, MessageSquareText, ThumbsUp, ThumbsDown, Download,Youtube, Loader2,} from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";7 unmodified linesimport { toast } from "sonner";import { AiProvidersPanel } from "@/components/admin/AiProvidersPanel";import AdminNotificationPanel from "@/components/AdminNotificationPanel";import { extractYouTubeId } from "@/lib/youtube-url";import { bilingual } from "@/lib/i18n";interface SettingItem { id?: string; key: string; value: string; section: string; type?: string; }interface ThemeItem { id: string; name: string; primaryColor: string; secondaryColor: string; accentColor: string; bgColor: string; textColor: string; cardBgColor: string; borderColor: string; isActive: boolean; createdAt: string; }/** Rows of the channel's YouTube playlist for the lesson-import dialog. */function PlaylistImportList({ isRTL, onPick }: { readonly isRTL: boolean; readonly onPick: (watchUrl: string) => void }) {const { data, isLoading, isError } = trpc.admin.youtubePlaylistVideos.useQuery(undefined, {staleTime: 10 * 60 * 1000,});if (isLoading) {return (<div className="flex items-center justify-center gap-2 py-10 text-text-muted"><Loader2 className="h-4 w-4 animate-spin" /><span className="text-sm">{isRTL ? "جاري جلب البلايليست..." : "Fetching the playlist..."}</span></div>);}if (isError || data?.error) {return (<p className="py-10 text-center text-sm text-destructive">{isRTL ? "تعذّر جلب البلايليست — جرّب تاني بعد شوية" : "Couldn't fetch the playlist — try again shortly"}</p>);}const items = data?.items ?? [];if (items.length === 0) {return (<p className="py-10 text-center text-sm text-text-muted">{isRTL ? "البلايليست فاضية أو مش متاحة حالياً" : "The playlist is empty or currently unavailable"}</p>);}return (<div className="max-h-[46vh] space-y-1.5 overflow-y-auto pr-1">{items.map((item: { videoId: string; title: string; watchUrl: string; thumbnailUrl: string }) => (<buttonkey={item.videoId}type="button"dir={isRTL ? "rtl" : "ltr"}onClick={() => onPick(item.watchUrl)}className="flex w-full items-center gap-3 rounded-lg border border-border bg-background p-2 text-start transition-colors hover:bg-[rgba(6,182,212,0.06)]"><imgsrc={item.thumbnailUrl}alt=""loading="lazy"className="h-11 w-20 shrink-0 rounded-md object-cover"onError={(e) => { (e.currentTarget as HTMLImageElement).style.visibility = "hidden"; }}/><span className="min-w-0 flex-1"><span className="block truncate text-[13px] font-medium text-foreground">{item.title}</span><span dir="ltr" className="block truncate font-mono text-[10px] text-text-muted">{item.videoId}</span></span><span className="shrink-0 rounded-md bg-[rgba(6,182,212,0.12)] px-2 py-1 text-[10px] font-bold text-[#22d3ee]">{isRTL ? "اختيار" : "Pick"}</span></button>))}</div>);}interface PromoItem { id: string; code: string; discount: number; type: "percentage" | "fixed"; maxUses: number; usedCount: number; status: "active" | "expired" | "used_up"; validFrom: string; validUntil: string; createdAt: string; }interface PromotionItem { id: string; titleEn: string; titleAr: string; subtitleEn: string; subtitleAr: string; discountText: string; ctaTextEn: string; ctaTextAr: string; ctaUrl: string; startDate: string; endDate: string; bgColor: string; textColor: string; buttonColor: string; position: "top" | "bottom"; showCountdown: boolean; isActive: boolean; createdAt: string; }interface CourseItem { id: number; slug: string; titleEn: string; titleAr: string; descriptionEn: string | null; descriptionAr: string | null; shortDescEn?: string | null; shortDescAr?: string | null; thumbnailUrl: string | null; price: number; currency: string; isFeatured: boolean; isPublished: boolean; level: string; category: number | null; studentCount: number; createdAt: Date; updatedAt: Date; }182 unmodified linesconst [showLessonForm, setShowLessonForm] = useState(false);const [editingLesson, setEditingLesson] = useState<LessonItem | null>(null);const [lessonForm, setLessonForm] = useState({ titleEn: "", titleAr: "", descriptionEn: "", descriptionAr: "", videoUrl: "", durationMinutes: 30, isFree: false, isPublished: true });const [showPlaylistImport, setShowPlaylistImport] = useState(false);const openLessonForm = (lesson?: LessonItem) => {if (lesson) {1177 unmodified lines<DialogContent className="bg-[#0d1420] border-border max-w-3xl max-h-[85vh] overflow-y-auto"><DialogHeader><DialogTitle className="text-foreground">{isRTL ? `دروس: ${lessonsCourse?.titleAr ?? ""}` : `Lessons: ${lessonsCourse?.titleEn ?? ""}`}</DialogTitle><DialogDescription className="text-text-muted">{(lessonsData?.items as LessonItem[] | undefined)?.length ?? 0} {isRTL ? "درس — الفيديو رابط يوتيوب من البلايليست (يُبث جوه الموقع) أو مفتاح R2" : "lessons — each video is a YouTube playlist link (streams in-site) or an R2 key"}</DialogDescription></DialogHeader><div className="space-y-2 py-2">{((lessonsData?.items as LessonItem[] | undefined) ?? []).length === 0 && (25 unmodified lines<DialogContent className="bg-[#0d1420] border-border max-w-xl max-h-[85vh] overflow-y-auto"><DialogHeader><DialogTitle className="text-foreground">{editingLesson ? (isRTL ? "تعديل الدرس" : "Edit Lesson") : (isRTL ? "درس جديد" : "New Lesson")}</DialogTitle><DialogDescription className="text-text-muted">{isRTL ? "رابط يوتيوب من بلايليست القناة (يُبث جوه الموقع) أو مفتاح R2 مثل etap/lesson01.mp4" : "A YouTube playlist link (streams in-site) or an R2 key like etap/lesson01.mp4"}</DialogDescription></DialogHeader><div className="grid gap-3 py-2"><div className="grid grid-cols-2 gap-3">4 unmodified lines<div className="space-y-1"><Label className="text-text-muted">{isRTL ? "الوصف (إنجليزي)" : "Description (EN)"}</Label><Textarea rows={2} value={lessonForm.descriptionEn} onChange={(e) => setLessonForm((f) => ({ ...f, descriptionEn: e.target.value }))} className="border-border bg-background text-foreground" /></div><div className="space-y-1"><Label className="text-text-muted">{isRTL ? "الوصف (عربي)" : "Description (AR)"}</Label><Textarea rows={2} value={lessonForm.descriptionAr} onChange={(e) => setLessonForm((f) => ({ ...f, descriptionAr: e.target.value }))} dir="rtl" className="border-border bg-background text-foreground" /></div></div><div className="space-y-1"><div className="flex items-center justify-between gap-2"><Label className="text-text-muted">{isRTL ? "رابط الفيديو" : "Video URL"}</Label><buttontype="button"onClick={() => setShowPlaylistImport(true)}className="inline-flex items-center gap-1 rounded-md bg-[rgba(255,59,48,0.08)] px-2 py-1 text-[11px] font-semibold text-[#ff5f57] transition-colors hover:bg-[rgba(255,59,48,0.16)]"><Youtube className="h-3.5 w-3.5" />{isRTL ? "استيراد من بلايليست اليوتيوب" : "Import from YouTube playlist"}</button></div><Input value={lessonForm.videoUrl} onChange={(e) => setLessonForm((f) => ({ ...f, videoUrl: e.target.value }))} placeholder={isRTL ? "https://www.youtube.com/watch?v=... أو etap/lesson01.mp4" : "https://www.youtube.com/watch?v=... or etap/lesson01.mp4"} dir={extractYouTubeId(lessonForm.videoUrl) ? "ltr" : undefined} className="border-border bg-background text-foreground" />{extractYouTubeId(lessonForm.videoUrl) ? (<p className="flex items-center gap-1 text-[11px] font-medium text-[#22d3ee]"><Youtube className="h-3 w-3" />{isRTL ? "يوتيوب ✓ — هيُبث جوه الموقع من البلايليست بدون تحميل على السيرفر" : "YouTube ✓ — streams inside the site from the playlist, nothing hosted here"}</p>) : lessonForm.videoUrl.trim() ? (<p className="text-[11px] text-text-muted">{isRTL ? "رابط مباشر / مفتاح R2 — هيُبث من مشغل المنصة المحمي" : "Direct link / R2 key — plays in the protected self-hosted player"}</p>) : null}</div><div className="grid grid-cols-2 gap-3"><div className="space-y-1"><Label className="text-text-muted">{isRTL ? "المدة (دقائق)" : "Duration (min)"}</Label><Input type="number" min={0} max={1440} value={lessonForm.durationMinutes} onChange={(e) => setLessonForm((f) => ({ ...f, durationMinutes: Number(e.target.value) }))} className="border-border bg-background text-foreground" /></div></div><div className="flex items-center gap-6 pt-1">7 unmodified lines</DialogFooter></DialogContent></Dialog>{/* ═══════════════ YOUTUBE PLAYLIST IMPORT DIALOG ═══════════════ */}{/* One-click lesson → playlist-video binding: lists the channel'splaylist (the same multi-source pipeline the notification watcheruses), and fills the lesson form with the chosen watch link. */}<Dialog open={showPlaylistImport} onOpenChange={setShowPlaylistImport}><DialogContent className="bg-[#0d1420] border-border max-w-xl max-h-[85vh] overflow-y-auto"><DialogHeader><DialogTitle className="flex items-center gap-2 text-foreground"><Youtube className="h-4 w-4 text-[#ff5f57]" />{isRTL ? "فيديوهات بلايليست القناة" : "Channel playlist videos"}</DialogTitle><DialogDescription className="text-text-muted">{isRTL? "اختار الفيديو ويتملّى رابطه في خانة الدرس — التشغيل هيبقى جوه الموقع من غير أي ثقل على السيرفر": "Pick a video and its link fills the lesson form — playback happens inside the site with zero server load"}</DialogDescription></DialogHeader><PlaylistImportListisRTL={isRTL}onPick={(watchUrl) => {setLessonForm((f) => ({ ...f, videoUrl: watchUrl }));setShowPlaylistImport(false);toast.success(isRTL ? "تم اختيار الفيديو — اضغط حفظ" : "Video selected — press Save");}}/><DialogFooter><Button variant="outline" onClick={() => setShowPlaylistImport(false)} className="border-border text-text-muted">{isRTL ? "إغلاق" : "Close"}</Button></DialogFooter></DialogContent></Dialog>{/* ═══════════════ ARTICLE FORM DIALOG ═══════════════ */}<Dialog open={showArticleForm} onOpenChange={setShowArticleForm}><DialogContent className="bg-[#0d1420] border-border max-w-2xl max-h-[85vh] overflow-y-auto">
1 unmodified line234567935 unmodified lines943944945946947948134 unmodified lines10831084108510861087108810897 unmodified lines1097109810991100110111021 unmodified lineimport { useTranslation } from "@/hooks/useTranslation";import { useAuth } from "@/hooks/useAuth";import { trpc } from "@/providers/trpc";import { useState, useRef, useEffect, useCallback, forwardRef, lazy, Suspense } from 'react';import { useWatchTracker } from "@/hooks/useWatchTracker";import { trackLearning, trackPlatform, trackEvent } from "@/lib/clarity";935 unmodified linesreturn isEnrolled;};const isVideoReady = activeLesson && !!activeLessonData && canAccessLesson(activeLessonData) && videoData?.videoUrl;// Payment method icons134 unmodified lines</div>)}{isVideoReady && (<ProtectedVideoPlayervideoUrl={videoData.videoUrl}hlsUrl={videoData.hlsUrl}7 unmodified lines/>)}{activeLesson && !!activeLessonData && canAccessLesson(activeLessonData) && !videoLoading && !videoData?.videoUrl && (isAuthenticated ? (<div className="flex aspect-video items-center justify-center bg-gradient-to-br from-[#0f172a] to-[#1e293b]">1 unmodified line2345678935 unmodified lines944945946947948949950951952953954134 unmodified lines10891090109110921093109410957 unmodified lines11031104110511061107110811091110111111121113111411151116111711181119112011211 unmodified lineimport { useTranslation } from "@/hooks/useTranslation";import { useAuth } from "@/hooks/useAuth";import { trpc } from "@/providers/trpc";import YouTubeLessonPlayer from "@/components/YouTubeLessonPlayer";import { useState, useRef, useEffect, useCallback, forwardRef, lazy, Suspense } from 'react';import { useWatchTracker } from "@/hooks/useWatchTracker";import { trackLearning, trackPlatform, trackEvent } from "@/lib/clarity";935 unmodified linesreturn isEnrolled;};// 🎬 YOUTUBE-HYBRID PLAYBACK: when the lesson's videoUrl is a YouTube link,// the API returns kind="youtube" + the 11-char id, and the video streams// from the channel's playlist INSIDE the site's player screen — zero bytes// from our server. Legacy R2 lessons keep the self-hosted player unchanged.const isYouTubeLesson = videoData?.kind === "youtube" && !!videoData?.youtubeId;const isVideoReady = activeLesson && !!activeLessonData && canAccessLesson(activeLessonData) && videoData?.videoUrl;// Payment method icons134 unmodified lines</div>)}{isVideoReady && !isYouTubeLesson && (<ProtectedVideoPlayervideoUrl={videoData.videoUrl}hlsUrl={videoData.hlsUrl}7 unmodified lines/>)}{isVideoReady && isYouTubeLesson && (<YouTubeLessonPlayerkey={videoData.youtubeId!}videoId={videoData.youtubeId!}lessonId={activeLesson || undefined}courseId={course?.id}lessonTitle={activeLessonTitle}lang={lang}isTrackingEnabled={isAuthenticated}onLessonCompleted={() => { void refetchEnrollment(); }}/>)}{activeLesson && !!activeLessonData && canAccessLesson(activeLessonData) && !videoLoading && !videoData?.videoUrl && (isAuthenticated ? (<div className="flex aspect-video items-center justify-center bg-gradient-to-br from-[#0f172a] to-[#1e293b]">
21 unmodified lines222324252627283 unmodified lines32333435363738394021 unmodified linesreturn {name: 'elbaz-build-id',apply: 'build',buildStart() {// Generate a unique build ID: timestamp (base36) + 8 random hex chars3 unmodified linesconsole.log(`[Build ID] ${buildId}`)},// Replace %%CACHE_BUST%% in index.html to bust Cloudflare/CDN cachestransformIndexHtml(html: string) {return html.replaceAll('%%CACHE_BUST%%', buildId)},async writeBundle() {21 unmodified lines2223242526273 unmodified lines313233343536373839404142434445464721 unmodified linesreturn {name: 'elbaz-build-id',buildStart() {// Generate a unique build ID: timestamp (base36) + 8 random hex chars3 unmodified linesconsole.log(`[Build ID] ${buildId}`)},// Replace %%CACHE_BUST%% in index.html to bust Cloudflare/CDN caches.// 🐛 DEV FIX: the whole plugin used to be gated by apply:'build', so the// dev server served the RAW %%CACHE_BUST%% placeholder in <script src> —// every module import then carried a bogus query and vite served the// UNTRANSPILLED TypeScript ("Unexpected identifier 'as'" → white page).// Production was unaffected; local UI testing (and `npm run dev`) was// broken. The html hook must run in BOTH modes — dev falls back to a// per-session id because buildStart may not have generated one yet.transformIndexHtml(html: string) {const id = buildId ?? `dev-${Date.now().toString(36)}`return html.replaceAll('%%CACHE_BUST%%', id)},async writeBundle() {