From 022c9a271b9189a84586e24b1dfc96cea881556b Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Mon, 25 May 2026 04:25:45 +0100 Subject: [PATCH] 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 --- .../components/streaming/EpisodesSidebar.tsx | 167 ++++++++ .../components/streaming/StreamingDialog.tsx | 376 +++++++++++++++++ .../components/streaming/StreamingPlayer.tsx | 385 +----------------- .../components/streaming/StreamingSection.tsx | 185 +++------ .../src/components/streaming/index.ts | 2 + react_frontend/src/pages/EpisodePage.tsx | 54 ++- react_frontend/src/pages/SeasonPage.tsx | 57 ++- 7 files changed, 708 insertions(+), 518 deletions(-) create mode 100644 react_frontend/src/components/streaming/EpisodesSidebar.tsx create mode 100644 react_frontend/src/components/streaming/StreamingDialog.tsx diff --git a/react_frontend/src/components/streaming/EpisodesSidebar.tsx b/react_frontend/src/components/streaming/EpisodesSidebar.tsx new file mode 100644 index 0000000..b8e4617 --- /dev/null +++ b/react_frontend/src/components/streaming/EpisodesSidebar.tsx @@ -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(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 ( +
+ {/* Season selector */} +
+ +
+ + {/* Episode list */} +
+ {episodes.length === 0 && ( +
+ No episodes found +
+ )} + + {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 ( + + ); + })} +
+
+ ); +} diff --git a/react_frontend/src/components/streaming/StreamingDialog.tsx b/react_frontend/src/components/streaming/StreamingDialog.tsx new file mode 100644 index 0000000..60bb505 --- /dev/null +++ b/react_frontend/src/components/streaming/StreamingDialog.tsx @@ -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>(new Set()); + const iframeRef = useRef(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 | 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( +
+ {/* Top bar */} +
+ {/* Left: server selector + current info */} +
+ +
+ + {entry.title} + + {entry.is_tvseries && ( + + S{String(currentSeason).padStart(2, '0')}E{String(currentEpisode).padStart(2, '0')} + {currentEpisodeName && ` — ${currentEpisodeName}`} + + )} +
+
+ + {/* Right: episodes toggle + close */} +
+ {entry.is_tvseries && ( + + )} + +
+
+ + {/* Main area */} +
+ {/* Player */} +
+ {/* Loading skeleton */} + {(isLoading || (!iframeLoaded && !error)) && ( +
+
+
+

Loading stream…

+
+
+ )} + + {/* Error */} + {error && ( +
+
+
+ +
+
+

Stream Unavailable

+

{error.message}

+
+
+ + +
+
+
+ )} + + {/* Iframe */} + {currentStreamUrl && isValidEmbedUrl(currentStreamUrl) && ( +