feat(streaming): add watch button to episode cards and episode details page

- Add play overlay on episode thumbnails in SeasonPage (click to stream directly)
- Add clickable watch overlay on episode still image in EpisodePage
- Fix StreamingDialog rendering via React portal (document.body) to prevent ancestor overflow/max-width clipping
- Fix EpisodePage JSX parse error (streaming dialog was outside root element)
- Fix watch buttons not working: use useEntry hook for full entry data with entryIds instead of library store (which lacks entryIds)
- Fix preventDefault called after guard check, causing link navigation when tmdb_id was missing
- Pass seasons via useEntrySeasons to StreamingDialog from both pages so episodes sidebar renders correctly
- Apply final UI polish: entry title in dialog top bar, season selector label, episode format "E1 Title", watched badge always-on, unreleased episodes greyed out
This commit is contained in:
Mohammed Abad committed 2026-05-25 04:25:45 +01:00
1 parent afc032ca1c
commit 022c9a271b
7 files changed
+708 -518

No files matched your search

@@ -0,0 +1,167 @@
import { useEffect, useRef, useState } from 'react';
import { getTmdbImageUrl } from '@/lib/api';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { CheckCircle2, PlayCircle, Tv } from 'lucide-react';
import type { Season } from '@/types';
interface EpisodesSidebarProps {
seasons: Season[];
currentSeason: number;
currentEpisode: number;
onEpisodeSelect: (season: number, episode: number) => void;
}
export function EpisodesSidebar({
seasons,
currentSeason,
currentEpisode,
onEpisodeSelect,
}: EpisodesSidebarProps) {
// The season the user is browsing (may differ from currently playing)
const [selectedSeason, setSelectedSeason] = useState(currentSeason);
// Sync sidebar season when the playing season changes (embed auto-advanced)
useEffect(() => {
setSelectedSeason(currentSeason);
}, [currentSeason]);
const activeEpisodeRef = useRef<HTMLButtonElement>(null);
// Auto-scroll to the currently playing episode
useEffect(() => {
if (activeEpisodeRef.current) {
activeEpisodeRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, [currentSeason, currentEpisode, selectedSeason]);
const browsingSeason = seasons.find((s) => s.season_number === selectedSeason);
const episodes = browsingSeason?.episodes
? [...browsingSeason.episodes].sort((a, b) => a.episode_number - b.episode_number)
: [];
const playableSeasons = seasons
.filter((s) => s.season_number > 0)
.sort((a, b) => a.season_number - b.season_number);
return (
<div className="w-80 xl:w-96 shrink-0 bg-zinc-950 border-l border-white/10 flex flex-col overflow-hidden">
{/* Season selector */}
<div className="p-3 border-b border-white/10 shrink-0">
<Select
value={String(selectedSeason)}
onValueChange={(v) => setSelectedSeason(Number(v))}
>
<SelectTrigger className="h-9 bg-white/5 border-white/10 text-white hover:bg-white/10 focus:ring-0 focus:ring-offset-0">
<SelectValue>
Season {selectedSeason}
</SelectValue>
</SelectTrigger>
<SelectContent className="bg-zinc-900 border-white/10">
{playableSeasons.map((season) => (
<SelectItem
key={season.id}
value={String(season.season_number)}
className="text-white focus:bg-white/10 focus:text-white"
>
Season {season.season_number}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Episode list */}
<div className="flex-1 overflow-y-auto py-2 px-2 space-y-1">
{episodes.length === 0 && (
<div className="flex items-center justify-center h-32 text-white/30 text-sm">
No episodes found
</div>
)}
{episodes.map((ep) => {
const isPlaying =
selectedSeason === currentSeason && ep.episode_number === currentEpisode;
const isWatched =
!!ep.date_first_seen ||
(ep.episodeSeens != null && ep.episodeSeens.length > 0);
const isUnreleased =
!!ep.air_date && new Date(ep.air_date) > new Date();
const stillUrl = ep.still_path
? getTmdbImageUrl(ep.still_path, 'w300')
: null;
return (
<button
key={ep.id}
ref={isPlaying ? activeEpisodeRef : undefined}
onClick={() => !isUnreleased && onEpisodeSelect(selectedSeason, ep.episode_number)}
disabled={isUnreleased}
className={`w-full flex gap-3 p-2 rounded-lg text-left transition-colors group ${
isUnreleased
? 'opacity-50 cursor-not-allowed'
: isPlaying
? 'bg-primary/15 ring-1 ring-primary/40'
: 'hover:bg-white/5'
}`}
>
{/* Thumbnail */}
<div className="relative w-24 h-13.5 shrink-0 rounded-md overflow-hidden bg-zinc-800 flex items-center justify-center">
{stillUrl ? (
<img
src={stillUrl}
alt={ep.name}
className={`w-full h-full object-cover ${
isUnreleased ? 'grayscale' : ''
}`}
loading="lazy"
/>
) : (
<Tv className="h-5 w-5 text-white/20" />
)}
{/* Playing indicator overlay */}
{isPlaying && (
<div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
<PlayCircle className="h-6 w-6 text-primary drop-shadow" />
</div>
)}
{/* Watched badge — always shown when watched */}
{isWatched && (
<div className="absolute top-1 right-1">
<CheckCircle2 className="h-4 w-4 text-green-400 drop-shadow" />
</div>
)}
</div>
{/* Episode info */}
<div className="flex-1 min-w-0 py-0.5">
<p
className={`text-sm font-medium leading-tight truncate ${
isPlaying ? 'text-primary' : isUnreleased ? 'text-white/30' : 'text-white/80 group-hover:text-white'
}`}
>
<span className={`font-bold mr-1 ${isPlaying ? 'text-primary' : 'text-white/50'}`}>
E{ep.episode_number}
</span>
{ep.name || `Episode ${ep.episode_number}`}
</p>
{ep.overview && (
<p className="text-xs text-white/40 mt-0.5 line-clamp-2 leading-relaxed">
{ep.overview}
</p>
)}
</div>
</button>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,376 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useStreamingStore } from '@/stores/useStreamingStore';
import {
isValidEventOrigin,
updateProgressFromEvent,
isConsideredWatched,
logWatchCompleted,
isValidEmbedUrl,
getEntryWatchProgress,
} from '@/lib/streaming';
import type { PlayerEvent } from '@/lib/streaming';
import { ServerSelector } from './ServerSelector';
import { EpisodesSidebar } from './EpisodesSidebar';
import { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt';
import { Button } from '@/components/ui/button';
import {
X,
List,
AlertTriangle,
RefreshCw,
} from 'lucide-react';
import type { Entry, Season } from '@/types';
interface StreamingDialogProps {
entry: Entry;
seasons?: Season[];
initialSeason?: number;
initialEpisode?: number;
isOpen: boolean;
onClose: () => void;
onMarkAsWatched?: (season?: number, episode?: number) => void;
}
export function StreamingDialog({
entry,
seasons,
initialSeason = 1,
initialEpisode = 1,
isOpen,
onClose,
onMarkAsWatched,
}: StreamingDialogProps) {
const {
currentStreamUrl,
isLoading,
error,
autoMarkWatched,
autoMarkPromptShown,
tryNextServer,
play,
closePlayer,
} = useStreamingStore();
const [currentSeason, setCurrentSeason] = useState(initialSeason);
const [currentEpisode, setCurrentEpisode] = useState(initialEpisode);
const [showSidebar, setShowSidebar] = useState(entry.is_tvseries);
const [iframeLoaded, setIframeLoaded] = useState(false);
const [showAutoMarkPrompt, setShowAutoMarkPrompt] = useState(false);
const markedAsWatched = useRef<Set<string>>(new Set());
const iframeRef = useRef<HTMLIFrameElement>(null);
// Refs so the message handler always has fresh values without re-subscribing
const currentSeasonRef = useRef(currentSeason);
const currentEpisodeRef = useRef(currentEpisode);
const autoMarkRef = useRef(autoMarkWatched);
const autoMarkPromptShownRef = useRef(autoMarkPromptShown);
const onMarkAsWatchedRef = useRef(onMarkAsWatched);
useEffect(() => { currentSeasonRef.current = currentSeason; }, [currentSeason]);
useEffect(() => { currentEpisodeRef.current = currentEpisode; }, [currentEpisode]);
useEffect(() => { autoMarkRef.current = autoMarkWatched; }, [autoMarkWatched]);
useEffect(() => { autoMarkPromptShownRef.current = autoMarkPromptShown; }, [autoMarkPromptShown]);
useEffect(() => { onMarkAsWatchedRef.current = onMarkAsWatched; }, [onMarkAsWatched]);
// Sync initial values when dialog opens
useEffect(() => {
if (isOpen) {
setCurrentSeason(initialSeason);
setCurrentEpisode(initialEpisode);
setIframeLoaded(false);
setShowSidebar(entry.is_tvseries);
}
}, [isOpen]);
// Keyboard shortcut: Escape to close
useEffect(() => {
if (!isOpen) return;
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
closePlayer();
onClose();
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [isOpen, onClose, closePlayer]);
// postMessage listener — handles episode sync + progress + auto-mark
useEffect(() => {
if (!isOpen) return;
const handler = (event: MessageEvent) => {
if (!isValidEventOrigin(event.origin)) return;
const season = currentSeasonRef.current;
const episode = currentEpisodeRef.current;
// VidLink MEDIA_DATA: sync current episode from embed navigation
if (event.data?.type === 'MEDIA_DATA') {
const allData = event.data.data;
const tmdbId = entry.entryIds?.tmdb_id;
if (tmdbId && allData?.[String(tmdbId)]) {
const d = allData[String(tmdbId)];
const s = d.last_season_watched ? parseInt(d.last_season_watched) : null;
const e = d.last_episode_watched ? parseInt(d.last_episode_watched) : null;
if (s && e && (s !== season || e !== episode)) {
setCurrentSeason(s);
setCurrentEpisode(e);
}
}
return;
}
// PLAYER_EVENT (VidLink + VidKing JSON)
let playerData: Record<string, unknown> | null = null;
if (event.data?.type === 'PLAYER_EVENT') {
playerData = event.data.data;
} else if (typeof event.data === 'string') {
try {
const parsed = JSON.parse(event.data);
if (parsed?.type === 'PLAYER_EVENT') playerData = parsed.data;
} catch { /* not JSON */ }
}
if (!playerData) return;
// Episode sync: update UI when embed navigates to a different episode
if (playerData.season && playerData.episode) {
const s = Number(playerData.season);
const e = Number(playerData.episode);
if (s !== season || e !== episode) {
setCurrentSeason(s);
setCurrentEpisode(e);
}
}
const playerEvent: PlayerEvent = {
event: playerData.event as PlayerEvent['event'],
currentTime: Number(playerData.currentTime) || 0,
duration: Number(playerData.duration) || 0,
mediaType: entry.is_tvseries ? 'tv' : 'movie',
tmdbId: entry.entryIds?.tmdb_id || 0,
season: playerData.season ? Number(playerData.season) : season,
episode: playerData.episode ? Number(playerData.episode) : episode,
progress: Number(playerData.progress) || undefined,
};
if (entry.entryIds?.tmdb_id) {
updateProgressFromEvent(playerEvent, entry.title, entry.poster_path || undefined);
}
const isFinished =
playerEvent.event === 'ended' ||
(playerEvent.event === 'timeupdate' &&
isConsideredWatched(
playerEvent.currentTime,
playerEvent.duration,
autoMarkRef.current.threshold
));
if (isFinished) {
const key = entry.is_tvseries
? `${playerEvent.tmdbId}-s${playerEvent.season}e${playerEvent.episode}`
: `${playerEvent.tmdbId}`;
if (!markedAsWatched.current.has(key)) {
logWatchCompleted({
tmdbId: playerEvent.tmdbId,
type: playerEvent.mediaType,
title: entry.title,
season: playerEvent.season,
episode: playerEvent.episode,
completedAt: Date.now(),
duration: playerEvent.duration,
});
if (autoMarkRef.current.enabled) {
onMarkAsWatchedRef.current?.(playerEvent.season, playerEvent.episode);
markedAsWatched.current.add(key);
} else if (!autoMarkPromptShownRef.current) {
setShowAutoMarkPrompt(true);
}
}
}
};
window.addEventListener('message', handler);
return () => window.removeEventListener('message', handler);
}, [isOpen, entry]);
const handleEpisodeSelect = useCallback(
(season: number, episode: number) => {
setCurrentSeason(season);
setCurrentEpisode(episode);
setIframeLoaded(false);
if (!entry.entryIds?.tmdb_id) return;
const watchProgress = getEntryWatchProgress(entry.entryIds.tmdb_id);
const epProgress = watchProgress?.showProgress?.[`s${season}e${episode}`];
play({
type: 'tv',
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season,
episode,
startAt: epProgress?.watched,
});
},
[entry, play]
);
// Current episode name for the top bar
const currentEpisodeName = (() => {
if (!entry.is_tvseries || !seasons) return null;
const s = seasons.find((s) => s.season_number === currentSeason);
const ep = s?.episodes?.find((e) => e.episode_number === currentEpisode);
return ep?.name ?? null;
})();
// Reset iframe on URL change
useEffect(() => {
setIframeLoaded(false);
}, [currentStreamUrl]);
if (!isOpen) return null;
return createPortal(
<div className="fixed inset-0 z-50 bg-black flex flex-col">
{/* Top bar */}
<div className="flex items-center justify-between h-12 px-3 shrink-0 bg-zinc-950/90 border-b border-white/10 gap-3">
{/* Left: server selector + current info */}
<div className="flex items-center gap-3 min-w-0">
<ServerSelector />
<div className="flex flex-col min-w-0 hidden sm:flex">
<span className="text-white/90 font-semibold text-sm leading-tight truncate">
{entry.title}
</span>
{entry.is_tvseries && (
<span className="text-white/50 text-xs leading-tight truncate">
S{String(currentSeason).padStart(2, '0')}E{String(currentEpisode).padStart(2, '0')}
{currentEpisodeName && ` — ${currentEpisodeName}`}
</span>
)}
</div>
</div>
{/* Right: episodes toggle + close */}
<div className="flex items-center gap-1 shrink-0">
{entry.is_tvseries && (
<Button
variant="ghost"
size="sm"
className={`h-8 gap-1.5 text-xs transition-colors ${
showSidebar
? 'text-white bg-white/10 hover:bg-white/15'
: 'text-white/60 hover:text-white hover:bg-white/10'
}`}
onClick={() => setShowSidebar((v) => !v)}
>
<List className="h-4 w-4" />
<span className="hidden sm:inline">Episodes</span>
</Button>
)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-white/60 hover:text-white hover:bg-white/10"
onClick={() => { closePlayer(); onClose(); }}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Main area */}
<div className="flex-1 flex overflow-hidden">
{/* Player */}
<div className="flex-1 relative bg-black min-w-0">
{/* Loading skeleton */}
{(isLoading || (!iframeLoaded && !error)) && (
<div className="absolute inset-0 z-10 flex items-center justify-center">
<div className="flex flex-col items-center gap-3">
<div className="h-10 w-10 rounded-full border-2 border-primary border-t-transparent animate-spin" />
<p className="text-white/50 text-sm">Loading stream…</p>
</div>
</div>
)}
{/* Error */}
{error && (
<div className="absolute inset-0 z-10 flex items-center justify-center">
<div className="flex flex-col items-center gap-4 max-w-sm text-center px-6">
<div className="h-14 w-14 rounded-full bg-destructive/10 flex items-center justify-center">
<AlertTriangle className="h-7 w-7 text-destructive" />
</div>
<div className="space-y-1">
<h3 className="text-white font-semibold">Stream Unavailable</h3>
<p className="text-white/50 text-sm">{error.message}</p>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={tryNextServer}
className="bg-white/5 border-white/20 text-white hover:bg-white/10"
>
<RefreshCw className="mr-1.5 h-3.5 w-3.5" />
Try Another Server
</Button>
<Button
variant="outline"
size="sm"
onClick={() => { closePlayer(); onClose(); }}
className="bg-white/5 border-white/20 text-white hover:bg-white/10"
>
Close
</Button>
</div>
</div>
</div>
)}
{/* Iframe */}
{currentStreamUrl && isValidEmbedUrl(currentStreamUrl) && (
<iframe
ref={iframeRef}
src={currentStreamUrl}
className="absolute inset-0 w-full h-full"
frameBorder="0"
allowFullScreen
allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
onLoad={() => setIframeLoaded(true)}
/>
)}
{/* Auto-mark prompt (bottom center of player) */}
{showAutoMarkPrompt && (
<AutoMarkWatchedPrompt
onAccept={() => {
useStreamingStore.getState().enableAutoMarkWatched();
setShowAutoMarkPrompt(false);
onMarkAsWatchedRef.current?.(currentSeason, currentEpisode);
}}
onDecline={() => {
useStreamingStore.getState().disableAutoMarkWatched();
setShowAutoMarkPrompt(false);
}}
/>
)}
</div>
{/* Episodes sidebar */}
{showSidebar && entry.is_tvseries && seasons && seasons.length > 0 && (
<EpisodesSidebar
seasons={seasons}
currentSeason={currentSeason}
currentEpisode={currentEpisode}
onEpisodeSelect={handleEpisodeSelect}
/>
)}
</div>
</div>,
document.body
);
}
@@ -1,383 +1,2 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useStreamingStore } from '@/stores/useStreamingStore';
import {
isValidEventOrigin,
updateProgressFromEvent,
isConsideredWatched,
logWatchCompleted,
isValidEmbedUrl,
} from '@/lib/streaming';
import type { PlayerEvent } from '@/lib/streaming';
import { ServerSelector } from './ServerSelector';
import { EpisodeNavigator } from './EpisodeNavigator';
import { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import {
X,
Maximize2,
Minimize2,
AlertTriangle,
RefreshCw,
SkipForward,
} from 'lucide-react';
import type { Entry, Season } from '@/types';
interface StreamingPlayerProps {
entry: Entry;
seasons?: Season[];
currentSeason?: number;
currentEpisode?: number;
onEpisodeChange?: (season: number, episode: number) => void;
onMarkAsWatched?: (season?: number, episode?: number) => void;
}
export function StreamingPlayer({
entry,
seasons,
currentSeason,
currentEpisode,
onEpisodeChange,
onMarkAsWatched,
}: StreamingPlayerProps) {
const {
currentStreamUrl,
isLoading,
error,
activeServer,
isPlayerOpen,
autoMarkWatched,
autoMarkPromptShown,
closePlayer,
tryNextServer,
play,
currentRequest,
} = useStreamingStore();
const iframeRef = useRef<HTMLIFrameElement>(null);
const [isFullscreen, setIsFullscreen] = useState(false);
const [iframeLoaded, setIframeLoaded] = useState(false);
const [showAutoMarkPrompt, setShowAutoMarkPrompt] = useState(false);
const [markedAsWatched, setMarkedAsWatched] = useState<Set<string>>(new Set());
const containerRef = useRef<HTMLDivElement>(null);
// Handle fullscreen
const toggleFullscreen = useCallback(() => {
if (!containerRef.current) return;
if (!document.fullscreenElement) {
containerRef.current.requestFullscreen().then(() => setIsFullscreen(true));
} else {
document.exitFullscreen().then(() => setIsFullscreen(false));
}
}, []);
// Listen for fullscreen change
useEffect(() => {
const handler = () => setIsFullscreen(!!document.fullscreenElement);
document.addEventListener('fullscreenchange', handler);
return () => document.removeEventListener('fullscreenchange', handler);
}, []);
// Keyboard shortcuts
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (!isPlayerOpen) return;
switch (e.key) {
case 'Escape':
if (isFullscreen) {
document.exitFullscreen();
} else {
closePlayer();
}
break;
case 'f':
case 'F':
if (!e.ctrlKey && !e.metaKey) {
toggleFullscreen();
}
break;
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, [isPlayerOpen, isFullscreen, closePlayer, toggleFullscreen]);
// Listen for player events from iframe
useEffect(() => {
const handler = (event: MessageEvent) => {
if (!isValidEventOrigin(event.origin)) return;
// Handle VidLink progress data
if (event.data?.type === 'MEDIA_DATA') {
// VidLink specific progress tracking
return;
}
// Handle player events from VidLink and VidKing
if (event.data?.type === 'PLAYER_EVENT') {
const data = event.data.data;
const playerEvent: PlayerEvent = {
event: data.event,
currentTime: data.currentTime || 0,
duration: data.duration || 0,
mediaType: entry.is_tvseries ? 'tv' : 'movie',
tmdbId: entry.entryIds?.tmdb_id || 0,
season: currentSeason,
episode: currentEpisode,
progress: data.progress,
};
// Update progress
updateProgressFromEvent(
playerEvent,
entry.title,
entry.poster_path || undefined
);
// Check for completion
if (playerEvent.event === 'ended' || isConsideredWatched(
playerEvent.currentTime,
playerEvent.duration,
autoMarkWatched.threshold
)) {
handleWatchCompleted(playerEvent);
}
}
// Handle VidKing string events
if (typeof event.data === 'string') {
try {
const parsed = JSON.parse(event.data);
if (parsed?.type === 'PLAYER_EVENT') {
const data = parsed.data;
if (data.event === 'ended') {
handleWatchCompleted({
event: 'ended',
currentTime: data.currentTime || data.timestamp || 0,
duration: data.duration || 0,
mediaType: entry.is_tvseries ? 'tv' : 'movie',
tmdbId: entry.entryIds?.tmdb_id || 0,
season: currentSeason,
episode: currentEpisode,
});
}
}
} catch {
// Not JSON, ignore
}
}
};
window.addEventListener('message', handler);
return () => window.removeEventListener('message', handler);
}, [entry, currentSeason, currentEpisode, autoMarkWatched]);
const handleWatchCompleted = useCallback(
(event: PlayerEvent) => {
const key = entry.is_tvseries
? `${event.tmdbId}-s${currentSeason}e${currentEpisode}`
: `${event.tmdbId}`;
// Don't mark the same thing twice in this session
if (markedAsWatched.has(key)) return;
// Log the watch event
logWatchCompleted({
tmdbId: event.tmdbId,
type: event.mediaType,
title: entry.title,
season: currentSeason,
episode: currentEpisode,
completedAt: Date.now(),
duration: event.duration,
});
if (autoMarkWatched.enabled) {
// Auto-mark as watched
onMarkAsWatched?.(currentSeason, currentEpisode);
setMarkedAsWatched((prev) => new Set(prev).add(key));
} else if (!autoMarkPromptShown) {
// Show the prompt
setShowAutoMarkPrompt(true);
}
},
[entry, currentSeason, currentEpisode, autoMarkWatched, autoMarkPromptShown, markedAsWatched, onMarkAsWatched]
);
// Handle next episode
const handleNextEpisode = useCallback(() => {
if (!entry.is_tvseries || !seasons || !currentSeason || !currentEpisode) return;
const season = seasons.find((s) => s.season_number === currentSeason);
if (!season?.episodes) return;
const nextEp = currentEpisode + 1;
const episodeExists = season.episodes.some((e) => e.episode_number === nextEp);
if (episodeExists) {
onEpisodeChange?.(currentSeason, nextEp);
} else {
// Try next season
const nextSeason = seasons.find((s) => s.season_number === currentSeason + 1);
if (nextSeason?.episodes?.length) {
onEpisodeChange?.(nextSeason.season_number, 1);
}
}
}, [entry, seasons, currentSeason, currentEpisode, onEpisodeChange]);
// Reset iframe loaded state when URL changes
useEffect(() => {
setIframeLoaded(false);
}, [currentStreamUrl]);
if (!isPlayerOpen) return null;
return (
<div
ref={containerRef}
className={`relative w-full bg-black rounded-xl overflow-hidden ${
isFullscreen ? 'fixed inset-0 z-100 rounded-none' : 'aspect-video'
}`}
>
{/* Top controls bar */}
<div className="absolute top-0 left-0 right-0 z-20 flex items-center justify-between p-3 bg-linear-to-b from-black/80 to-transparent opacity-0 hover:opacity-100 transition-opacity duration-200">
<div className="flex items-center gap-2">
<ServerSelector />
{entry.is_tvseries && seasons && currentSeason && currentEpisode && (
<span className="text-white/70 text-sm font-medium px-2">
S{currentSeason}:E{currentEpisode}
</span>
)}
</div>
<div className="flex items-center gap-1">
{entry.is_tvseries && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-white/80 hover:text-white hover:bg-white/10"
onClick={handleNextEpisode}
title="Next Episode"
>
<SkipForward className="h-4 w-4" />
</Button>
)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-white/80 hover:text-white hover:bg-white/10"
onClick={toggleFullscreen}
title={isFullscreen ? 'Exit Fullscreen (F)' : 'Fullscreen (F)'}
>
{isFullscreen ? (
<Minimize2 className="h-4 w-4" />
) : (
<Maximize2 className="h-4 w-4" />
)}
</Button>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-white/80 hover:text-white hover:bg-white/10"
onClick={closePlayer}
title="Close Player (Esc)"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Loading state */}
{(isLoading || !iframeLoaded) && !error && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-black">
<div className="flex flex-col items-center gap-3">
<div className="h-10 w-10 rounded-full border-2 border-primary border-t-transparent animate-spin" />
<p className="text-white/60 text-sm">Loading stream...</p>
</div>
</div>
)}
{/* Error state */}
{error && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-black/95">
<div className="flex flex-col items-center gap-4 max-w-sm text-center px-6">
<div className="h-14 w-14 rounded-full bg-destructive/10 flex items-center justify-center">
<AlertTriangle className="h-7 w-7 text-destructive" />
</div>
<div className="space-y-1">
<h3 className="text-white font-semibold">Stream Unavailable</h3>
<p className="text-white/60 text-sm">{error.message}</p>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={tryNextServer}
className="bg-white/5 border-white/20 text-white hover:bg-white/10"
>
<RefreshCw className="mr-1.5 h-3.5 w-3.5" />
Try Another Server
</Button>
<Button
variant="outline"
size="sm"
onClick={closePlayer}
className="bg-white/5 border-white/20 text-white hover:bg-white/10"
>
Close
</Button>
</div>
</div>
</div>
)}
{/* Video iframe */}
{currentStreamUrl && isValidEmbedUrl(currentStreamUrl) && (
<iframe
ref={iframeRef}
src={currentStreamUrl}
className="absolute inset-0 w-full h-full"
frameBorder="0"
allowFullScreen
allow="autoplay; fullscreen; picture-in-picture; encrypted-media"
onLoad={() => setIframeLoaded(true)}
onError={() => {
useStreamingStore.getState().setError({
server: activeServer!,
message: 'Failed to load stream. The server may be unavailable.',
code: 'UNAVAILABLE',
});
}}
/>
)}
{/* Episode navigator (bottom bar for TV) */}
{entry.is_tvseries && seasons && isPlayerOpen && !isFullscreen && (
<EpisodeNavigator
seasons={seasons}
currentSeason={currentSeason}
currentEpisode={currentEpisode}
onEpisodeChange={onEpisodeChange}
/>
)}
{/* Auto mark watched prompt */}
{showAutoMarkPrompt && (
<AutoMarkWatchedPrompt
onAccept={() => {
useStreamingStore.getState().enableAutoMarkWatched();
setShowAutoMarkPrompt(false);
// Mark the current one
onMarkAsWatched?.(currentSeason, currentEpisode);
}}
onDecline={() => {
useStreamingStore.getState().disableAutoMarkWatched();
setShowAutoMarkPrompt(false);
}}
/>
)}
</div>
);
}
// @deprecated - replaced by StreamingDialog
export {};
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useStreamingStore } from '@/stores/useStreamingStore';
import { getEntryWatchProgress } from '@/lib/streaming';
import { StreamingPlayer } from './StreamingPlayer';
import { StreamingDialog } from './StreamingDialog';
import { Button } from '@/components/ui/button';
import { Play, Tv } from 'lucide-react';
import { useCreateEntrySeen } from '@/hooks/useEntrySeen';
@@ -14,35 +14,29 @@ interface StreamingSectionProps {
}
export function StreamingSection({ entry, seasons }: StreamingSectionProps) {
const {
isPlayerOpen,
initialize,
play,
currentRequest,
} = useStreamingStore();
const { initialize, play } = useStreamingStore();
// Local state — prevents player from auto-opening when navigating between entries
const [isDialogOpen, setIsDialogOpen] = useState(false);
const createEntrySeen = useCreateEntrySeen();
const createEpisodeSeen = useCreateEpisodeSeen();
const [currentSeason, setCurrentSeason] = useState<number>(1);
const [currentEpisode, setCurrentEpisode] = useState<number>(1);
// Initialize streaming system
// Initialize streaming system once
useEffect(() => {
initialize();
}, [initialize]);
// Determine continue watching state
// Watch progress from localStorage
const watchProgress = useMemo(() => {
if (!entry.entryIds?.tmdb_id) return null;
return getEntryWatchProgress(entry.entryIds.tmdb_id);
}, [entry.entryIds?.tmdb_id]);
// For TV shows, figure out the "continue watching" episode
// Determine "continue watching" position for TV shows
const continueWatchingInfo = useMemo(() => {
if (!entry.is_tvseries) return null;
// Check local progress first
if (watchProgress?.lastSeasonWatched && watchProgress?.lastEpisodeWatched) {
return {
season: watchProgress.lastSeasonWatched,
@@ -51,72 +45,43 @@ export function StreamingSection({ entry, seasons }: StreamingSectionProps) {
};
}
// Check episode seen data from the library
if (entry.episodeSeens && entry.episodeSeens.length > 0) {
// Find the last watched episode
if (entry.episodeSeens && entry.episodeSeens.length > 0 && seasons) {
const sorted = [...entry.episodeSeens].sort(
(a, b) => new Date(b.date_seen).getTime() - new Date(a.date_seen).getTime()
);
const last = sorted[0];
// Find the episode in seasons to get season/episode numbers
if (seasons) {
for (const season of seasons) {
const ep = season.episodes?.find((e) => e.id === last.episode_id);
if (ep) {
// Suggest the next episode
const nextEp = ep.episode_number + 1;
const hasNext = season.episodes?.some((e) => e.episode_number === nextEp);
if (hasNext) {
return {
season: season.season_number,
episode: nextEp,
label: `Continue S${season.season_number}:E${nextEp}`,
};
}
// Try next season
const nextSeason = seasons.find((s) => s.season_number === season.season_number + 1);
if (nextSeason?.episodes?.length) {
return {
season: nextSeason.season_number,
episode: 1,
label: `Continue S${nextSeason.season_number}:E1`,
};
}
// No more episodes, show where they left off
return {
season: season.season_number,
episode: ep.episode_number,
label: `Rewatch S${season.season_number}:E${ep.episode_number}`,
};
for (const season of seasons) {
const ep = season.episodes?.find((e) => e.id === last.episode_id);
if (ep) {
const nextEp = ep.episode_number + 1;
if (season.episodes?.some((e) => e.episode_number === nextEp)) {
return { season: season.season_number, episode: nextEp, label: `Continue S${season.season_number}:E${nextEp}` };
}
const nextSeason = seasons.find((s) => s.season_number === season.season_number + 1);
if (nextSeason?.episodes?.length) {
return { season: nextSeason.season_number, episode: 1, label: `Continue S${nextSeason.season_number}:E1` };
}
return { season: season.season_number, episode: ep.episode_number, label: `Rewatch S${season.season_number}:E${ep.episode_number}` };
}
}
}
// Default to S1E1
return { season: 1, episode: 1, label: 'Start Watching' };
}, [entry, seasons, watchProgress]);
// Set initial episode from continue watching
useEffect(() => {
if (continueWatchingInfo) {
setCurrentSeason(continueWatchingInfo.season);
setCurrentEpisode(continueWatchingInfo.episode);
}
}, [continueWatchingInfo]);
const initialSeason = entry.is_tvseries ? (continueWatchingInfo?.season ?? 1) : 1;
const initialEpisode = entry.is_tvseries ? (continueWatchingInfo?.episode ?? 1) : 1;
const handlePlay = useCallback(() => {
const handleOpen = useCallback(() => {
if (!entry.entryIds?.tmdb_id) return;
const request = entry.is_tvseries
? {
type: 'tv' as const,
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: currentSeason,
episode: currentEpisode,
startAt: watchProgress?.showProgress?.[`s${currentSeason}e${currentEpisode}`]?.watched,
season: initialSeason,
episode: initialEpisode,
startAt: watchProgress?.showProgress?.[`s${initialSeason}e${initialEpisode}`]?.watched,
}
: {
type: 'movie' as const,
@@ -124,36 +89,18 @@ export function StreamingSection({ entry, seasons }: StreamingSectionProps) {
imdbId: entry.entryIds?.imdb_id || undefined,
startAt: watchProgress?.watched,
};
play(request);
}, [entry, currentSeason, currentEpisode, watchProgress, play]);
setIsDialogOpen(true);
}, [entry, initialSeason, initialEpisode, watchProgress, play]);
const handleEpisodeChange = useCallback(
(season: number, episode: number) => {
setCurrentSeason(season);
setCurrentEpisode(episode);
if (!entry.entryIds?.tmdb_id) return;
// Get progress for this specific episode
const epProgress = watchProgress?.showProgress?.[`s${season}e${episode}`];
play({
type: 'tv',
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season,
episode,
startAt: epProgress?.watched,
});
},
[entry, watchProgress, play]
);
const handleClose = useCallback(() => {
setIsDialogOpen(false);
useStreamingStore.getState().closePlayer();
}, []);
const handleMarkAsWatched = useCallback(
(season?: number, episode?: number) => {
if (entry.is_tvseries && season && episode && seasons) {
// Find the episode ID
const seasonData = seasons.find((s) => s.season_number === season);
const episodeData = seasonData?.episodes?.find((e) => e.episode_number === episode);
if (episodeData) {
@@ -166,7 +113,6 @@ export function StreamingSection({ entry, seasons }: StreamingSectionProps) {
});
}
} else {
// Movie
createEntrySeen.mutate({
entry_id: entry.id,
date_seen: new Date().toISOString().split('T')[0],
@@ -177,43 +123,38 @@ export function StreamingSection({ entry, seasons }: StreamingSectionProps) {
[entry, seasons, createEntrySeen, createEpisodeSeen]
);
// Don't show if no TMDB ID
if (!entry.entryIds?.tmdb_id) return null;
return (
<div className="space-y-3">
{/* Play button - shown when player is closed */}
{!isPlayerOpen && (
<Button
onClick={handlePlay}
size="lg"
className="w-full sm:w-auto gap-2 h-11 px-6 text-sm font-medium"
>
{entry.is_tvseries ? (
<>
<Tv className="h-4 w-4" />
{continueWatchingInfo?.label || 'Start Watching'}
</>
) : (
<>
<Play className="h-4 w-4 fill-current" />
{watchProgress && watchProgress.watched > 60 ? 'Continue Watching' : 'Watch Now'}
</>
)}
</Button>
)}
const buttonLabel = entry.is_tvseries
? (continueWatchingInfo?.label ?? 'Start Watching')
: watchProgress && watchProgress.watched > 60
? 'Continue Watching'
: 'Watch Now';
{/* Player */}
{isPlayerOpen && (
<StreamingPlayer
entry={entry}
seasons={seasons}
currentSeason={currentSeason}
currentEpisode={currentEpisode}
onEpisodeChange={handleEpisodeChange}
onMarkAsWatched={handleMarkAsWatched}
/>
)}
</div>
return (
<>
<Button
onClick={handleOpen}
size="lg"
className="w-full sm:w-auto gap-2 h-11 px-6 text-sm font-medium"
>
{entry.is_tvseries ? (
<Tv className="h-4 w-4" />
) : (
<Play className="h-4 w-4 fill-current" />
)}
{buttonLabel}
</Button>
<StreamingDialog
entry={entry}
seasons={seasons}
initialSeason={initialSeason}
initialEpisode={initialEpisode}
isOpen={isDialogOpen}
onClose={handleClose}
onMarkAsWatched={handleMarkAsWatched}
/>
</>
);
}
@@ -1,5 +1,7 @@
export { StreamingPlayer } from './StreamingPlayer';
export { StreamingDialog } from './StreamingDialog';
export { StreamingSection } from './StreamingSection';
export { ServerSelector } from './ServerSelector';
export { EpisodesSidebar } from './EpisodesSidebar';
export { EpisodeNavigator } from './EpisodeNavigator';
export { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt';