Fix watch tracking, video unlocking and access-control gaps
Deploy Vault CMS / deploy (push) Failing after 38s
Deploy Vault CMS / deploy (push) Failing after 38s
Watch progress and unlocking: - Player samples the playhead and reports the ranges actually played, so skipped sections earn no credit and early plays are not lost - Server merges ranges into compact segment rows; progress never regresses - Single 80% unlock rule enforced server-side (lib/watch-progress.ts); the Unlock button and automatic unlock now agree - Lock state and progress bar update live from each progress save - Playlist is derived from the video, so unlocks work for shared playlists and for links from watch history and liked videos - First/previous video decided by playlist position, not index numbers Access control: - Video API and HLS/MP4 routes require a signed-in viewer who is enrolled and has the video unlocked; thumbnails require sign-in - Enrolment sync reads course codes from the allow-list, not the request - /api/admin/meta is admin-only - Account status, role and levels are re-checked from the database during a session, so deactivated students lose access within a minute Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
+252
-350
@@ -27,6 +27,7 @@ import { Button } from '@/components/ui/button';
|
||||
import { HlsPlayer } from '@/components/hls';
|
||||
import { useSession } from 'next-auth/react';
|
||||
import Image from 'next/image';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
type VideoFromApi = {
|
||||
id: string;
|
||||
@@ -50,261 +51,256 @@ type VideoFromApi = {
|
||||
} | null;
|
||||
};
|
||||
|
||||
type ProgressResult = {
|
||||
progress?: { percent?: number };
|
||||
segments?: WatchSegment[];
|
||||
unlockedNext?: { id: string; title: string } | null;
|
||||
};
|
||||
|
||||
type TrackedVideo = { videoId: string; durationSec: number | null };
|
||||
|
||||
/**
|
||||
* Records which parts of a video were actually played and reports them to
|
||||
* /api/progress.
|
||||
*
|
||||
* It samples the <video> element on a timer rather than relying on media
|
||||
* events, so it keeps working when the element is swapped (one per video) or
|
||||
* when playback starts before anything else on the page has settled. A sample
|
||||
* only counts as watched when the playhead moved forward by no more than the
|
||||
* wall-clock time that passed, which excludes seeks and scrubbing.
|
||||
*/
|
||||
export function useWatchTracker(
|
||||
videoRef: React.RefObject<HTMLVideoElement | null>,
|
||||
opts: { sendIntervalMs?: number; commitIntervalSec?: number; debug?: boolean } = {}
|
||||
opts: {
|
||||
sendIntervalMs?: number;
|
||||
sampleIntervalMs?: number;
|
||||
onResult?: (videoId: string, result: ProgressResult) => void;
|
||||
} = {}
|
||||
) {
|
||||
const sendIntervalMs = opts.sendIntervalMs ?? 5000;
|
||||
const commitIntervalSec = opts.commitIntervalSec ?? 3;
|
||||
const debug = !!opts.debug;
|
||||
const sampleIntervalMs = opts.sampleIntervalMs ?? 500;
|
||||
|
||||
const rangesRef = React.useRef<Array<[number, number]>>([]);
|
||||
const lastTimeRef = React.useRef<number | null>(null);
|
||||
const currentRangeStartRef = React.useRef<number | null>(null);
|
||||
const sendTimerRef = React.useRef<number | null>(null);
|
||||
const commitTimerRef = React.useRef<number | null>(null);
|
||||
|
||||
// merging helper
|
||||
function mergeRanges(ranges: Array<[number, number]>) {
|
||||
if (!ranges.length) return [];
|
||||
ranges.sort((a, b) => a[0] - b[0]);
|
||||
const merged: Array<[number, number]> = [];
|
||||
for (const [s, e] of ranges) {
|
||||
if (!merged.length) merged.push([s, e]);
|
||||
else {
|
||||
const last = merged[merged.length - 1];
|
||||
if (s <= last[1] + 0.5) last[1] = Math.max(last[1], e);
|
||||
else merged.push([s, e]);
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
function addRange(s: number, e: number) {
|
||||
if (e <= s) return;
|
||||
if (debug) console.debug("[tracker] addRange", s, e);
|
||||
rangesRef.current.push([s, e]);
|
||||
rangesRef.current = mergeRanges(rangesRef.current);
|
||||
}
|
||||
|
||||
function getUniqueWatchedSec() {
|
||||
let sum = 0;
|
||||
for (const [a, b] of rangesRef.current) sum += Math.max(0, b - a);
|
||||
return Math.round(sum);
|
||||
}
|
||||
|
||||
// commit the "current" playing segment to ranges (useful while playing)
|
||||
function commitCurrentRange() {
|
||||
const el = videoRef.current;
|
||||
if (!el) return;
|
||||
const start = currentRangeStartRef.current;
|
||||
const now = el.currentTime;
|
||||
if (start === null) return;
|
||||
// only commit if we've moved forward at least 0.5s to avoid noise
|
||||
if (now - start >= 0.5) {
|
||||
addRange(start, now);
|
||||
// keep currentRangeStart open at 'now' so we continue accumulating
|
||||
currentRangeStartRef.current = now;
|
||||
}
|
||||
}
|
||||
|
||||
// send progress to server (same signature you had)
|
||||
async function sendProgress(args: { videoId: string; playlistId?: string; duration: number; extra?: Record<string, any> }) {
|
||||
const { videoId, playlistId, duration, extra } = args;
|
||||
const watchedSec = getUniqueWatchedSec();
|
||||
const el = videoRef.current;
|
||||
const lastPos = Math.floor(el?.currentTime ?? 0);
|
||||
|
||||
if (!duration || duration <= 0) return null;
|
||||
if (watchedSec === 0 && (el?.paused ?? true)) return null;
|
||||
|
||||
const payload = { videoId, playlistId, watchedSec, lastPos, duration, ...extra };
|
||||
try {
|
||||
if (debug) console.debug("[tracker] sendProgress", payload);
|
||||
const res = await fetch("/api/progress", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// If video not found, stop trying to track progress
|
||||
if (!res.ok) {
|
||||
if (res.status === 404) {
|
||||
console.warn(`[tracker] Video ${videoId} not found, stopping progress tracking`);
|
||||
stopAutoSend(); // Stop automatic progress tracking for deleted video
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return res.ok ? await res.json().catch(() => null) : null;
|
||||
} catch (err) {
|
||||
if (debug) console.warn("[tracker] sendProgress error", err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// start/stop auto-send
|
||||
function startAutoSend(args: { videoId: string; playlistId?: string; duration: number }) {
|
||||
stopAutoSend(); // clear existing
|
||||
|
||||
// immediate send (best-effort)
|
||||
sendProgress(args).catch(() => {});
|
||||
|
||||
// periodic send
|
||||
sendTimerRef.current = window.setInterval(() => {
|
||||
const watched = getUniqueWatchedSec();
|
||||
const el = videoRef.current;
|
||||
const isPlaying = !!(el && !el.paused && !el.ended);
|
||||
if (watched > 0 || isPlaying) {
|
||||
sendProgress(args).catch(() => {});
|
||||
}
|
||||
}, sendIntervalMs) as unknown as number;
|
||||
|
||||
// commit currently playing ranges periodically (so continuous play is captured)
|
||||
commitTimerRef.current = window.setInterval(() => {
|
||||
commitCurrentRange();
|
||||
}, commitIntervalSec * 1000) as unknown as number;
|
||||
|
||||
if (debug) console.debug("[tracker] startAutoSend", { sendIntervalMs, commitIntervalSec });
|
||||
}
|
||||
|
||||
function stopAutoSend(opts?: { sendFinal?: boolean; videoId?: string; playlistId?: string; duration?: number }) {
|
||||
if (sendTimerRef.current) {
|
||||
window.clearInterval(sendTimerRef.current);
|
||||
sendTimerRef.current = null;
|
||||
}
|
||||
if (commitTimerRef.current) {
|
||||
window.clearInterval(commitTimerRef.current);
|
||||
commitTimerRef.current = null;
|
||||
}
|
||||
if (opts?.sendFinal && opts.videoId && opts.duration) {
|
||||
sendProgress({ videoId: opts.videoId, playlistId: opts.playlistId, duration: opts.duration }).catch(() => {});
|
||||
}
|
||||
if (debug) console.debug("[tracker] stopAutoSend");
|
||||
}
|
||||
|
||||
// attach listeners to populate rangesRef
|
||||
const onResultRef = React.useRef(opts.onResult);
|
||||
React.useEffect(() => {
|
||||
onResultRef.current = opts.onResult;
|
||||
});
|
||||
|
||||
const activeRef = React.useRef<TrackedVideo | null>(null);
|
||||
const rangesRef = React.useRef<Array<[number, number]>>([]);
|
||||
const lastSampleRef = React.useRef<{ el: HTMLVideoElement; time: number; wall: number } | null>(null);
|
||||
const lastPosRef = React.useRef(0);
|
||||
const elementDurationRef = React.useRef(0);
|
||||
const dirtyRef = React.useRef(false);
|
||||
|
||||
const reset = React.useCallback((next: TrackedVideo | null) => {
|
||||
activeRef.current = next;
|
||||
rangesRef.current = [];
|
||||
lastSampleRef.current = null;
|
||||
lastPosRef.current = 0;
|
||||
elementDurationRef.current = 0;
|
||||
dirtyRef.current = false;
|
||||
}, []);
|
||||
|
||||
const sample = React.useCallback(() => {
|
||||
const el = videoRef.current;
|
||||
if (!el) {
|
||||
if (debug) console.debug("[tracker] no video element to attach");
|
||||
if (!activeRef.current || !el || typeof el.currentTime !== 'number') {
|
||||
lastSampleRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
currentRangeStartRef.current = null;
|
||||
lastTimeRef.current = el.currentTime ?? 0;
|
||||
const prev = lastSampleRef.current;
|
||||
const now = el.currentTime;
|
||||
const wall = performance.now();
|
||||
lastSampleRef.current = { el, time: now, wall };
|
||||
|
||||
const onPlay = () => {
|
||||
currentRangeStartRef.current = el.currentTime;
|
||||
lastTimeRef.current = el.currentTime;
|
||||
if (debug) console.debug("[tracker] play", currentRangeStartRef.current);
|
||||
};
|
||||
// First sample of a new element: nothing to compare against yet.
|
||||
if (!prev || prev.el !== el) return;
|
||||
|
||||
const onPause = () => {
|
||||
if (currentRangeStartRef.current !== null) {
|
||||
addRange(currentRangeStartRef.current, el.currentTime);
|
||||
currentRangeStartRef.current = null;
|
||||
}
|
||||
if (debug) console.debug("[tracker] pause, ranges:", rangesRef.current);
|
||||
};
|
||||
lastPosRef.current = now;
|
||||
if (Number.isFinite(el.duration) && el.duration > 0) {
|
||||
elementDurationRef.current = el.duration;
|
||||
}
|
||||
if (el.seeking) return;
|
||||
|
||||
const onTimeUpdate = () => {
|
||||
const now = el.currentTime;
|
||||
const last = lastTimeRef.current ?? now;
|
||||
// detect seek (big jump)
|
||||
if (Math.abs(now - last) > 2.5) {
|
||||
if (currentRangeStartRef.current !== null) {
|
||||
addRange(currentRangeStartRef.current, last);
|
||||
const delta = now - prev.time;
|
||||
if (delta <= 0) return; // paused, or jumped backwards
|
||||
|
||||
// Real playback cannot outrun the clock (timers may fire late in
|
||||
// background tabs, hence wall-clock time rather than the interval).
|
||||
const elapsedSec = (wall - prev.wall) / 1000;
|
||||
const maxAdvance = elapsedSec * Math.max(1, el.playbackRate || 1) + 0.75;
|
||||
if (delta > maxAdvance) return; // jumped forwards
|
||||
|
||||
const ranges = rangesRef.current;
|
||||
const last = ranges[ranges.length - 1];
|
||||
if (last && Math.abs(last[1] - prev.time) < 0.01) {
|
||||
last[1] = now; // still in the same stretch of playback
|
||||
} else {
|
||||
ranges.push([prev.time, now]);
|
||||
}
|
||||
dirtyRef.current = true;
|
||||
}, [videoRef]);
|
||||
|
||||
const flush = React.useCallback(async (keepalive = false) => {
|
||||
const active = activeRef.current;
|
||||
if (!active || !dirtyRef.current || rangesRef.current.length === 0) return;
|
||||
|
||||
const duration = active.durationSec || Math.floor(elementDurationRef.current);
|
||||
if (!duration || duration <= 0) return; // metadata not loaded yet; try again next tick
|
||||
|
||||
// Everything played this session is resent each time; the server merges,
|
||||
// so a dropped request loses nothing.
|
||||
const ranges = rangesRef.current.map(([s, e]) => [s, e]);
|
||||
dirtyRef.current = false;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/progress', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
keepalive,
|
||||
body: JSON.stringify({
|
||||
videoId: active.videoId,
|
||||
ranges,
|
||||
lastPos: Math.floor(lastPosRef.current),
|
||||
duration,
|
||||
}),
|
||||
});
|
||||
|
||||
const stillActive = activeRef.current?.videoId === active.videoId;
|
||||
if (!res.ok) {
|
||||
if (res.status === 404) {
|
||||
// Video was deleted: stop tracking it.
|
||||
if (stillActive) reset(null);
|
||||
} else if (stillActive) {
|
||||
dirtyRef.current = true;
|
||||
}
|
||||
currentRangeStartRef.current = now;
|
||||
if (debug) console.debug("[tracker] seek detected, start:", now);
|
||||
return;
|
||||
}
|
||||
lastTimeRef.current = now;
|
||||
// we do not addRange here to avoid flooding; commit timer handles mid-play commits
|
||||
};
|
||||
|
||||
const onEnded = () => {
|
||||
if (currentRangeStartRef.current !== null) {
|
||||
addRange(currentRangeStartRef.current, el.duration ?? lastTimeRef.current ?? 0);
|
||||
currentRangeStartRef.current = null;
|
||||
}
|
||||
if (debug) console.debug("[tracker] ended, ranges:", rangesRef.current);
|
||||
};
|
||||
const json = await res.json().catch(() => null);
|
||||
if (json) onResultRef.current?.(active.videoId, json);
|
||||
} catch {
|
||||
if (activeRef.current?.videoId === active.videoId) dirtyRef.current = true;
|
||||
}
|
||||
}, [reset]);
|
||||
|
||||
el.addEventListener("play", onPlay);
|
||||
el.addEventListener("pause", onPause);
|
||||
el.addEventListener("timeupdate", onTimeUpdate);
|
||||
el.addEventListener("ended", onEnded);
|
||||
/** Begin tracking a video. Anything recorded for a previous video is dropped. */
|
||||
const start = React.useCallback((video: TrackedVideo) => reset(video), [reset]);
|
||||
|
||||
/** Send what is left for the current video, then stop tracking it. */
|
||||
const stop = React.useCallback(() => {
|
||||
void flush(true);
|
||||
reset(null);
|
||||
}, [flush, reset]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const sampleTimer = window.setInterval(sample, sampleIntervalMs);
|
||||
const sendTimer = window.setInterval(() => void flush(), sendIntervalMs);
|
||||
|
||||
// Leaving or hiding the page: get the latest progress out while we can.
|
||||
const flushNow = () => {
|
||||
sample();
|
||||
void flush(true);
|
||||
};
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === 'hidden') flushNow();
|
||||
};
|
||||
document.addEventListener('visibilitychange', onVisibility);
|
||||
window.addEventListener('pagehide', flushNow);
|
||||
|
||||
return () => {
|
||||
el.removeEventListener("play", onPlay);
|
||||
el.removeEventListener("pause", onPause);
|
||||
el.removeEventListener("timeupdate", onTimeUpdate);
|
||||
el.removeEventListener("ended", onEnded);
|
||||
stopAutoSend();
|
||||
window.clearInterval(sampleTimer);
|
||||
window.clearInterval(sendTimer);
|
||||
document.removeEventListener('visibilitychange', onVisibility);
|
||||
window.removeEventListener('pagehide', flushNow);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [videoRef.current]);
|
||||
}, [sample, flush, sampleIntervalMs, sendIntervalMs]);
|
||||
|
||||
return {
|
||||
getUniqueWatchedSec,
|
||||
addRange,
|
||||
sendProgress,
|
||||
startAutoSend,
|
||||
stopAutoSend,
|
||||
};
|
||||
return { start, stop };
|
||||
}
|
||||
|
||||
|
||||
export default function Page() {
|
||||
const search = useSearchParams();
|
||||
const router = useRouter();
|
||||
const playlistId = search.get('playlistId') ?? undefined;
|
||||
const playlistIdParam = search.get('playlistId') ?? undefined;
|
||||
const videoId = search.get('videoId') ?? undefined;
|
||||
|
||||
const { playlist, isLoading: playlistLoading } = usePlaylist(playlistId);
|
||||
const { video, next, isLoading: videoLoading } = useVideo(videoId);
|
||||
const { video, isLoading: videoLoading, error: videoError } = useVideo(videoId);
|
||||
// Links from watch history and liked videos carry no playlist; use the video's own.
|
||||
const { playlist, isLoading: playlistLoading } = usePlaylist(
|
||||
playlistIdParam ?? (video as any)?.playlistId ?? undefined
|
||||
);
|
||||
|
||||
// Segments state for current video and playlist videos
|
||||
const [currentSegments, setCurrentSegments] = React.useState<WatchSegment[]>([]);
|
||||
const [playlistSegments, setPlaylistSegments] = React.useState<Record<string, WatchSegment[]>>({});
|
||||
const [currentProgress, setCurrentProgress] = React.useState(0);
|
||||
|
||||
|
||||
// Per-user unlock state
|
||||
const [userUnlocks, setUserUnlocks] = React.useState<Set<string>>(new Set()); // Set of unlocked videoIds
|
||||
const [videoInstantAccess, setVideoInstantAccess] = React.useState<Record<string, boolean>>({}); // videoId -> instantAccess
|
||||
const [unlockingVideo, setUnlockingVideo] = React.useState<string | null>(null); // videoId being unlocked
|
||||
|
||||
// inside your videoplayer component
|
||||
const videoRef = React.useRef<HTMLVideoElement | null>(null);
|
||||
const tracker = useWatchTracker(videoRef, { sendIntervalMs: 5000 });
|
||||
const videoRef = React.useRef<HTMLVideoElement | null>(null);
|
||||
const trackedVideoIdRef = React.useRef<string | null>(null);
|
||||
const userUnlocksRef = React.useRef(userUnlocks);
|
||||
React.useEffect(() => {
|
||||
userUnlocksRef.current = userUnlocks;
|
||||
}, [userUnlocks]);
|
||||
|
||||
// Fetch segments for current video
|
||||
// Every progress update returns the server's view: percentage, merged
|
||||
// segments, and the next video if this one just unlocked it.
|
||||
const handleProgressResult = React.useCallback((id: string, result: ProgressResult) => {
|
||||
const segments = result.segments;
|
||||
if (segments) {
|
||||
setPlaylistSegments((prev) => ({ ...prev, [id]: segments }));
|
||||
}
|
||||
if (id === trackedVideoIdRef.current) {
|
||||
if (segments) setCurrentSegments(segments);
|
||||
if (typeof result.progress?.percent === 'number') setCurrentProgress(result.progress.percent);
|
||||
}
|
||||
const unlocked = result.unlockedNext;
|
||||
if (unlocked && !userUnlocksRef.current.has(unlocked.id)) {
|
||||
setUserUnlocks((prev) => new Set(prev).add(unlocked.id));
|
||||
toast.success(`Unlocked: ${unlocked.title}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const tracker = useWatchTracker(videoRef, { onResult: handleProgressResult });
|
||||
const { start: startTracking, stop: stopTracking } = tracker;
|
||||
|
||||
// Load saved progress for the current video. Live updates then arrive with
|
||||
// each progress save, so there is no need to poll.
|
||||
React.useEffect(() => {
|
||||
if (!videoId) return;
|
||||
let cancelled = false;
|
||||
|
||||
const fetchSegments = async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/progress/segments?videoId=${videoId}`);
|
||||
const [res, progressRes] = await Promise.all([
|
||||
fetch(`/api/progress/segments?videoId=${videoId}`),
|
||||
fetch(`/api/progress?videoId=${videoId}`),
|
||||
]);
|
||||
if (cancelled) return;
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setCurrentSegments(data.segments ?? []);
|
||||
if (!cancelled) setCurrentSegments(data.segments ?? []);
|
||||
}
|
||||
const progressRes = await fetch(`/api/progress?videoId=${videoId}`);
|
||||
if (progressRes.ok) {
|
||||
const data = await progressRes.json();
|
||||
setCurrentProgress(data.percent ?? 0);
|
||||
if (!cancelled) setCurrentProgress(data.percent ?? 0);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch segments:', err);
|
||||
}
|
||||
};
|
||||
|
||||
setCurrentSegments([]);
|
||||
setCurrentProgress(0);
|
||||
fetchSegments();
|
||||
// Refresh segments every 5 seconds
|
||||
const interval = setInterval(fetchSegments, 5000);
|
||||
return () => clearInterval(interval);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [videoId]);
|
||||
|
||||
// Fetch segments for all playlist videos
|
||||
@@ -313,10 +309,8 @@ React.useEffect(() => {
|
||||
|
||||
const fetchPlaylistSegments = async () => {
|
||||
const segments: Record<string, WatchSegment[]> = {};
|
||||
const instantAccess: Record<string, boolean> = {};
|
||||
|
||||
|
||||
for (const video of playlist.videos) {
|
||||
// Fetch segments
|
||||
try {
|
||||
const res = await fetch(`/api/progress/segments?videoId=${video.id}`);
|
||||
if (res.ok) {
|
||||
@@ -326,15 +320,13 @@ React.useEffect(() => {
|
||||
} catch (err) {
|
||||
console.error(`Failed to fetch segments for video ${video.id}:`, err);
|
||||
}
|
||||
|
||||
// Track instantAccess status from video object
|
||||
instantAccess[video.id] = (video as any).instantAccess ?? false;
|
||||
}
|
||||
|
||||
setPlaylistSegments(segments);
|
||||
setVideoInstantAccess(instantAccess);
|
||||
|
||||
// Keep anything newer that arrived from a progress save in the meantime.
|
||||
setPlaylistSegments((prev) => ({ ...segments, ...prev }));
|
||||
};
|
||||
|
||||
setPlaylistSegments({});
|
||||
fetchPlaylistSegments();
|
||||
}, [playlist?.videos]);
|
||||
|
||||
@@ -345,8 +337,9 @@ React.useEffect(() => {
|
||||
const res = await fetch('/api/user/unlocks');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const unlockedVideoIds = new Set((data.unlocks?.map((u: any) => u.videoId) ?? []) as string[]);
|
||||
setUserUnlocks(unlockedVideoIds);
|
||||
const unlockedVideoIds = (data.unlocks?.map((u: any) => u.videoId) ?? []) as string[];
|
||||
// Merge, in case a progress save unlocked something while this loaded.
|
||||
setUserUnlocks((prev) => new Set([...prev, ...unlockedVideoIds]));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch user unlocks:', err);
|
||||
@@ -356,55 +349,20 @@ React.useEffect(() => {
|
||||
fetchUserUnlocks();
|
||||
}, []);
|
||||
|
||||
// Track whichever video is loaded; switching videos flushes the old one first.
|
||||
const loadedVideoId = video?.id ? String(video.id) : null;
|
||||
const loadedVideoDuration: number | null = video?.durationSec ?? null;
|
||||
React.useEffect(() => {
|
||||
if (!video) return;
|
||||
if (!loadedVideoId) return;
|
||||
|
||||
let didCancel = false;
|
||||
let poll: number | null = null;
|
||||
|
||||
const startWhenReady = () => {
|
||||
if (didCancel) return;
|
||||
const el = videoRef.current;
|
||||
const duration = (video.durationSec ?? Math.floor(el?.duration ?? 0)) || 0;
|
||||
|
||||
if (el) {
|
||||
tracker.startAutoSend({
|
||||
videoId: String(video.id),
|
||||
playlistId: playlist?.id,
|
||||
duration,
|
||||
});
|
||||
} else {
|
||||
// poll until the video element mounts (should be quick)
|
||||
poll = window.setInterval(() => {
|
||||
if (videoRef.current) {
|
||||
if (poll) {
|
||||
window.clearInterval(poll);
|
||||
poll = null;
|
||||
}
|
||||
tracker.startAutoSend({
|
||||
videoId: String(video.id),
|
||||
playlistId: playlist?.id,
|
||||
duration: (video.durationSec ?? Math.floor(videoRef.current?.duration ?? 0)) || 0,
|
||||
});
|
||||
}
|
||||
}, 150) as unknown as number;
|
||||
}
|
||||
};
|
||||
|
||||
startWhenReady();
|
||||
trackedVideoIdRef.current = loadedVideoId;
|
||||
startTracking({ videoId: loadedVideoId, durationSec: loadedVideoDuration });
|
||||
|
||||
return () => {
|
||||
didCancel = true;
|
||||
if (poll) {
|
||||
window.clearInterval(poll);
|
||||
poll = null;
|
||||
}
|
||||
const duration = video?.durationSec ?? Math.floor(videoRef.current?.duration ?? 0);
|
||||
// send final snapshot
|
||||
tracker.stopAutoSend({ sendFinal: true, videoId: String(video?.id ?? ''), playlistId: playlist?.id, duration });
|
||||
stopTracking();
|
||||
trackedVideoIdRef.current = null;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [video?.id, playlist?.id]);
|
||||
}, [loadedVideoId, loadedVideoDuration, startTracking, stopTracking]);
|
||||
|
||||
|
||||
const current: VideoFromApi = (video as VideoFromApi) ?? {
|
||||
@@ -425,84 +383,40 @@ React.useEffect(() => {
|
||||
return `${mins}:${secs}`;
|
||||
};
|
||||
|
||||
// A video is open when it is the first in the playlist, marked instant
|
||||
// access, or unlocked for this user. The lecturer's lock overrides all three.
|
||||
const firstVideoId: string | undefined = playlist?.videos?.[0]?.id;
|
||||
const isAccessible = (v: VideoFromApi) =>
|
||||
!v.locked &&
|
||||
(!!(v as any).instantAccess || v.id === firstVideoId || userUnlocks.has(v.id));
|
||||
|
||||
const openVideo = (v: VideoFromApi) => {
|
||||
router.push(`/videoplayer?playlistId=${playlist?.id}&videoId=${v.id}`);
|
||||
};
|
||||
|
||||
// The server decides whether the unlock is earned and explains when it is not.
|
||||
const handleUnlock = async (v: VideoFromApi) => {
|
||||
console.log('unlock request for', v.id);
|
||||
|
||||
// Prevent multiple unlock attempts
|
||||
if (unlockingVideo === v.id) return;
|
||||
|
||||
if (unlockingVideo === v.id || v.locked) return;
|
||||
|
||||
setUnlockingVideo(v.id);
|
||||
|
||||
try {
|
||||
// Can't unlock if globally locked
|
||||
if ((v as any).locked) {
|
||||
console.log('Video is globally locked, cannot unlock');
|
||||
return;
|
||||
}
|
||||
|
||||
// Can't unlock if already unlocked or has instant access
|
||||
if ((v as any).instantAccess || userUnlocks.has(v.id)) {
|
||||
console.log('Video already accessible');
|
||||
router.push(`/videoplayer?playlistId=${playlist?.id}&videoId=${v.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if previous video in sequence is completed
|
||||
if (!playlist?.videos) return;
|
||||
|
||||
const videoIndex = (v as any).index;
|
||||
if (videoIndex <= 0) {
|
||||
// First video should always be accessible
|
||||
router.push(`/videoplayer?playlistId=${playlist?.id}&videoId=${v.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Find previous video
|
||||
const previousVideo = playlist.videos.find((pv: any) => pv.index === videoIndex - 1);
|
||||
if (!previousVideo) {
|
||||
console.log('Previous video not found');
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if previous video is completed
|
||||
const progressRes = await fetch(`/api/progress?videoId=${previousVideo.id}`);
|
||||
if (!progressRes.ok) {
|
||||
console.error('Failed to fetch previous video progress');
|
||||
alert('Error checking unlock requirements. Please try again.');
|
||||
return;
|
||||
}
|
||||
|
||||
const progressData = await progressRes.json();
|
||||
const isCompleted = progressData.percent >= 90; // Consider 90% as completed
|
||||
|
||||
if (!isCompleted) {
|
||||
console.log('Previous video not completed yet - need', Math.ceil(90 - progressData.percent), '% more');
|
||||
// TODO: Show toast notification explaining unlock requirements
|
||||
alert(`You need to complete ${Math.ceil(90 - progressData.percent)}% more of the previous video to unlock this one.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Previous video is completed, unlock this video
|
||||
const unlockRes = await fetch('/api/user/unlocks', {
|
||||
const res = await fetch('/api/user/unlocks', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ videoId: v.id }),
|
||||
});
|
||||
|
||||
if (unlockRes.ok) {
|
||||
// Update local state
|
||||
setUserUnlocks(prev => new Set(prev).add(v.id));
|
||||
console.log('Video unlocked successfully');
|
||||
// Redirect to the unlocked video
|
||||
router.push(`/videoplayer?playlistId=${playlist?.id}&videoId=${v.id}`);
|
||||
} else {
|
||||
const errorData = await unlockRes.json().catch(() => ({ error: 'Unknown error' }));
|
||||
console.error('Failed to unlock video:', errorData.error);
|
||||
alert(`Failed to unlock video: ${errorData.error}`);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
if (!res.ok) {
|
||||
toast.error(data?.error ?? 'Could not unlock this video. Please try again.');
|
||||
return;
|
||||
}
|
||||
|
||||
setUserUnlocks((prev) => new Set(prev).add(v.id));
|
||||
openVideo(v);
|
||||
} catch (err) {
|
||||
console.error('Error checking unlock conditions:', err);
|
||||
alert('Error checking if video can be unlocked. Please try again.');
|
||||
console.error('Error unlocking video:', err);
|
||||
toast.error('Could not unlock this video. Please try again.');
|
||||
} finally {
|
||||
setUnlockingVideo(null);
|
||||
}
|
||||
@@ -585,7 +499,11 @@ React.useEffect(() => {
|
||||
ref={videoRef}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-80">Video not available</div>
|
||||
<div className="flex items-center justify-center h-80 px-6 text-center">
|
||||
{videoError?.message && !/^HTTP \d+$/.test(videoError.message)
|
||||
? videoError.message
|
||||
: 'Video not available'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -698,7 +616,7 @@ React.useEffect(() => {
|
||||
) : (
|
||||
playlist?.videos?.map((v: VideoFromApi) => {
|
||||
const active = String(v.id) === String(current.id);
|
||||
const watchedPercent = 0; // Replace with actual watched % from your state/API
|
||||
const accessible = isAccessible(v);
|
||||
return (
|
||||
<div
|
||||
key={v.id}
|
||||
@@ -707,29 +625,13 @@ React.useEffect(() => {
|
||||
active ? 'border-primary bg-muted' : 'border-transparent hover:border-border'
|
||||
}`}
|
||||
onClick={() => {
|
||||
// Check if video is accessible based on the logic:
|
||||
// 1. If locked at schema level, always deny
|
||||
if ((v as any).locked) return;
|
||||
// 2. If instantAccess, always allow
|
||||
if ((v as any).instantAccess) {
|
||||
router.push(`/videoplayer?playlistId=${playlist.id}&videoId=${v.id}`);
|
||||
return;
|
||||
}
|
||||
// 3. If first video (index 0), always allow
|
||||
if ((v as any).index === 0) {
|
||||
router.push(`/videoplayer?playlistId=${playlist.id}&videoId=${v.id}`);
|
||||
return;
|
||||
}
|
||||
// 4. Otherwise, check if user has unlocked it
|
||||
if (userUnlocks.has(v.id)) {
|
||||
router.push(`/videoplayer?playlistId=${playlist.id}&videoId=${v.id}`);
|
||||
}
|
||||
if (accessible) openVideo(v);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="relative w-20 h-12 shrink-0 overflow-hidden rounded">
|
||||
<img src={v.thumbnail ?? '/01.jpg'} alt={v.title} className="w-full h-full object-cover" loading="lazy" />
|
||||
{(v as any).locked || (!(v as any).instantAccess && (v as any).index !== 0 && !userUnlocks.has(v.id)) ? (
|
||||
{!accessible ? (
|
||||
<div className="absolute inset-0 bg-black/40 flex items-center justify-center">
|
||||
<Lock className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
@@ -742,28 +644,28 @@ React.useEffect(() => {
|
||||
<Badge>{fmt(v)}</Badge>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground truncate mt-1">
|
||||
{(v as any).locked ? 'Locked' : (v as any).instantAccess || (v as any).index === 0 ? 'Available' : userUnlocks.has(v.id) ? 'Available' : active ? 'Now playing' : 'Locked'}
|
||||
{active ? 'Now playing' : accessible ? 'Available' : 'Locked'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{(v as any).locked || (!(v as any).instantAccess && (v as any).index !== 0 && !userUnlocks.has(v.id)) ? (
|
||||
|
||||
{!accessible ? (
|
||||
<div className="ml-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant={(v as any).locked ? "secondary" : "default"}
|
||||
disabled={(v as any).locked || unlockingVideo === v.id}
|
||||
variant={v.locked ? "secondary" : "default"}
|
||||
disabled={v.locked || unlockingVideo === v.id}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleUnlock(v);
|
||||
}}
|
||||
>
|
||||
{unlockingVideo === v.id ? 'Unlocking...' : (v as any).locked ? 'Locked' : 'Unlock'}
|
||||
{unlockingVideo === v.id ? 'Unlocking...' : v.locked ? 'Locked' : 'Unlock'}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
|
||||
<SegmentedProgressBar
|
||||
segments={playlistSegments[v.id] ?? []}
|
||||
duration={v.durationSec ?? 1}
|
||||
|
||||
Reference in New Issue
Block a user