feat(frontend): implement full in-app streaming system with 4 APIs
- Add streaming types, interfaces, and normalized response structures - Create StreamingManager with URL building, validation, and security - Implement provider adapters for VidLink (2 servers), VidKing (1 server), AnyEmbed (5 servers) - Add Zustand streaming store with server selection, fallback, and retry logic - Build StreamingPlayer iframe component with fullscreen and keyboard shortcuts - Add ServerSelector dropdown with 8 servers and active state indicator - Create EpisodeNavigator with season tabs and episode grid - Implement AutoMarkWatchedPrompt for one-time completion opt-in - Add StreamingSection with Watch Now / Continue Watching entry point - Integrate StreamingSection into EntryDetailsPage
This commit is contained in:
1 parent
1a2ec5c505
commit
54014ae01f
19 files changed
+2617
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { CheckCircle2, X } from 'lucide-react';
|
||||
|
||||
interface AutoMarkWatchedPromptProps {
|
||||
onAccept: () => void;
|
||||
onDecline: () => void;
|
||||
}
|
||||
|
||||
export function AutoMarkWatchedPrompt({ onAccept, onDecline }: AutoMarkWatchedPromptProps) {
|
||||
return (
|
||||
<div className="absolute bottom-4 left-1/2 -translate-x-1/2 z-30 animate-in slide-in-from-bottom-4 fade-in duration-300">
|
||||
<div className="flex items-center gap-3 bg-popover/95 backdrop-blur-lg border border-border rounded-xl px-4 py-3 shadow-xl max-w-sm">
|
||||
<CheckCircle2 className="h-5 w-5 text-primary shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">Auto-mark as watched?</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Automatically mark episodes/movies as watched when you finish them
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5 shrink-0">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
className="h-7 text-xs px-3"
|
||||
onClick={onAccept}
|
||||
>
|
||||
Enable
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 w-7 p-0"
|
||||
onClick={onDecline}
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import type { Season } from '@/types';
|
||||
|
||||
interface EpisodeNavigatorProps {
|
||||
seasons: Season[];
|
||||
currentSeason?: number;
|
||||
currentEpisode?: number;
|
||||
onEpisodeChange?: (season: number, episode: number) => void;
|
||||
}
|
||||
|
||||
export function EpisodeNavigator({
|
||||
seasons,
|
||||
currentSeason,
|
||||
currentEpisode,
|
||||
onEpisodeChange,
|
||||
}: EpisodeNavigatorProps) {
|
||||
const activeSeason = useMemo(
|
||||
() => seasons.find((s) => s.season_number === currentSeason),
|
||||
[seasons, currentSeason]
|
||||
);
|
||||
|
||||
const episodes = activeSeason?.episodes || [];
|
||||
|
||||
const hasPrev = currentEpisode && currentEpisode > 1;
|
||||
const hasNext = currentEpisode && activeSeason && currentEpisode < (activeSeason.episode_count || episodes.length);
|
||||
|
||||
// Check if there's a next season
|
||||
const hasNextSeason = useMemo(() => {
|
||||
if (!currentSeason) return false;
|
||||
return seasons.some((s) => s.season_number === currentSeason + 1);
|
||||
}, [seasons, currentSeason]);
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-2">
|
||||
{/* Season selector */}
|
||||
<div className="flex items-center gap-2 px-1">
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="flex gap-1.5 pb-1">
|
||||
{seasons
|
||||
.filter((s) => s.season_number > 0)
|
||||
.sort((a, b) => a.season_number - b.season_number)
|
||||
.map((season) => (
|
||||
<Button
|
||||
key={season.id}
|
||||
variant={season.season_number === currentSeason ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
className="shrink-0 h-7 text-xs px-3"
|
||||
onClick={() => onEpisodeChange?.(season.season_number, 1)}
|
||||
>
|
||||
S{season.season_number}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
{/* Episode navigation */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
disabled={!hasPrev}
|
||||
onClick={() => hasPrev && onEpisodeChange?.(currentSeason!, currentEpisode! - 1)}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="flex gap-1 pb-1">
|
||||
{episodes
|
||||
.sort((a, b) => a.episode_number - b.episode_number)
|
||||
.map((ep) => (
|
||||
<Button
|
||||
key={ep.id}
|
||||
variant={ep.episode_number === currentEpisode ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
className={`shrink-0 h-7 w-7 p-0 text-xs ${
|
||||
ep.episode_number === currentEpisode
|
||||
? ''
|
||||
: 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
onClick={() => onEpisodeChange?.(currentSeason!, ep.episode_number)}
|
||||
>
|
||||
{ep.episode_number}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
</ScrollArea>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0"
|
||||
disabled={!hasNext && !hasNextSeason}
|
||||
onClick={() => {
|
||||
if (hasNext) {
|
||||
onEpisodeChange?.(currentSeason!, currentEpisode! + 1);
|
||||
} else if (hasNextSeason) {
|
||||
onEpisodeChange?.(currentSeason! + 1, 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useStreamingStore } from '@/stores/useStreamingStore';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { Monitor, Check, Loader2 } from 'lucide-react';
|
||||
|
||||
export function ServerSelector() {
|
||||
const { servers, activeServer, isLoading, switchServer } = useStreamingStore();
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 gap-1.5 text-white/80 hover:text-white hover:bg-white/10 text-xs font-medium"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Monitor className="h-3.5 w-3.5" />
|
||||
)}
|
||||
<span className="hidden sm:inline">{activeServer?.name || 'Select Server'}</span>
|
||||
<span className="sm:hidden">Server</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
className="w-52 bg-popover/95 backdrop-blur-lg"
|
||||
>
|
||||
{servers.map((server) => (
|
||||
<DropdownMenuItem
|
||||
key={server.id}
|
||||
onClick={() => switchServer(server.id)}
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span className="text-sm">{server.name}</span>
|
||||
{server.id === activeServer?.id && (
|
||||
<Check className="h-3.5 w-3.5 text-primary" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useStreamingStore } from '@/stores/useStreamingStore';
|
||||
import {
|
||||
isValidEventOrigin,
|
||||
updateProgressFromEvent,
|
||||
isConsideredWatched,
|
||||
logWatchCompleted,
|
||||
getServerSandboxPolicy,
|
||||
getServerAllowedFeatures,
|
||||
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
|
||||
sandbox={activeServer ? getServerSandboxPolicy(activeServer.id) : undefined}
|
||||
allow={activeServer ? getServerAllowedFeatures(activeServer.id) : undefined}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useStreamingStore } from '@/stores/useStreamingStore';
|
||||
import { getEntryWatchProgress } from '@/lib/streaming';
|
||||
import { StreamingPlayer } from './StreamingPlayer';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Play, Tv } from 'lucide-react';
|
||||
import { useCreateEntrySeen } from '@/hooks/useEntrySeen';
|
||||
import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen';
|
||||
import type { Entry, Season } from '@/types';
|
||||
|
||||
interface StreamingSectionProps {
|
||||
entry: Entry;
|
||||
seasons?: Season[];
|
||||
}
|
||||
|
||||
export function StreamingSection({ entry, seasons }: StreamingSectionProps) {
|
||||
const {
|
||||
isPlayerOpen,
|
||||
initialize,
|
||||
play,
|
||||
currentRequest,
|
||||
} = useStreamingStore();
|
||||
|
||||
const createEntrySeen = useCreateEntrySeen();
|
||||
const createEpisodeSeen = useCreateEpisodeSeen();
|
||||
|
||||
const [currentSeason, setCurrentSeason] = useState<number>(1);
|
||||
const [currentEpisode, setCurrentEpisode] = useState<number>(1);
|
||||
|
||||
// Initialize streaming system
|
||||
useEffect(() => {
|
||||
initialize();
|
||||
}, [initialize]);
|
||||
|
||||
// Determine continue watching state
|
||||
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
|
||||
const continueWatchingInfo = useMemo(() => {
|
||||
if (!entry.is_tvseries) return null;
|
||||
|
||||
// Check local progress first
|
||||
if (watchProgress?.lastSeasonWatched && watchProgress?.lastEpisodeWatched) {
|
||||
return {
|
||||
season: watchProgress.lastSeasonWatched,
|
||||
episode: watchProgress.lastEpisodeWatched,
|
||||
label: `Continue S${watchProgress.lastSeasonWatched}:E${watchProgress.lastEpisodeWatched}`,
|
||||
};
|
||||
}
|
||||
|
||||
// Check episode seen data from the library
|
||||
if (entry.episodeSeens && entry.episodeSeens.length > 0) {
|
||||
// Find the last watched episode
|
||||
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}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 handlePlay = 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,
|
||||
}
|
||||
: {
|
||||
type: 'movie' as const,
|
||||
tmdbId: entry.entryIds.tmdb_id,
|
||||
imdbId: entry.entryIds?.imdb_id || undefined,
|
||||
startAt: watchProgress?.watched,
|
||||
};
|
||||
|
||||
play(request);
|
||||
}, [entry, currentSeason, currentEpisode, 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 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) {
|
||||
createEpisodeSeen.mutate({
|
||||
entry_id: entry.id,
|
||||
episode_id: episodeData.id,
|
||||
date_seen: new Date().toISOString().split('T')[0],
|
||||
accuracy: 'EXACT',
|
||||
season_id: seasonData!.id,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Movie
|
||||
createEntrySeen.mutate({
|
||||
entry_id: entry.id,
|
||||
date_seen: new Date().toISOString().split('T')[0],
|
||||
accuracy: 'EXACT',
|
||||
});
|
||||
}
|
||||
},
|
||||
[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>
|
||||
)}
|
||||
|
||||
{/* Player */}
|
||||
{isPlayerOpen && (
|
||||
<StreamingPlayer
|
||||
entry={entry}
|
||||
seasons={seasons}
|
||||
currentSeason={currentSeason}
|
||||
currentEpisode={currentEpisode}
|
||||
onEpisodeChange={handleEpisodeChange}
|
||||
onMarkAsWatched={handleMarkAsWatched}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export { StreamingPlayer } from './StreamingPlayer';
|
||||
export { StreamingSection } from './StreamingSection';
|
||||
export { ServerSelector } from './ServerSelector';
|
||||
export { EpisodeNavigator } from './EpisodeNavigator';
|
||||
export { AutoMarkWatchedPrompt } from './AutoMarkWatchedPrompt';
|
||||
@@ -202,6 +202,28 @@
|
||||
animation: slide-up-fade 0.2s ease-out both;
|
||||
}
|
||||
|
||||
/* Infinite horizontal marquee belt */
|
||||
@keyframes marquee-left {
|
||||
from { transform: translateX(0); }
|
||||
to { transform: translateX(-50%); }
|
||||
}
|
||||
|
||||
/* Trending grid slide-in from right */
|
||||
@keyframes slide-from-right {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(32px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.animate-slide-from-right {
|
||||
animation: slide-from-right 0.45s ease-out both;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.15 0.01 260);
|
||||
--foreground: oklch(0.95 0.01 260);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export type { StreamingProvider, StreamingServer, StreamRequest, StreamResponse, StreamError, PlayerEvent, WatchProgressData, AutoMarkWatchedConfig, StreamingState, MediaType } from './types';
|
||||
export {
|
||||
getAllServers,
|
||||
getProviderForServer,
|
||||
getServerById,
|
||||
getStreamUrl,
|
||||
isStreamError,
|
||||
getServerSandboxPolicy,
|
||||
getServerAllowedFeatures,
|
||||
getPreferredServerId,
|
||||
setPreferredServerId,
|
||||
getPreferredServer,
|
||||
getWatchProgress,
|
||||
getEntryWatchProgress,
|
||||
saveWatchProgress,
|
||||
updateProgressFromEvent,
|
||||
getAutoMarkWatchedConfig,
|
||||
setAutoMarkWatchedConfig,
|
||||
hasAutoMarkPromptBeenShown,
|
||||
markAutoMarkPromptShown,
|
||||
logWatchCompleted,
|
||||
getWatchLogs,
|
||||
isConsideredWatched,
|
||||
isValidEmbedUrl,
|
||||
isValidEventOrigin,
|
||||
} from './streaming-manager';
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { StreamingProvider, StreamingServer, StreamRequest } from '../types';
|
||||
|
||||
const ANYEMBED_SERVERS: StreamingServer[] = [
|
||||
{
|
||||
id: 'anyembed-1',
|
||||
name: 'AnyEmbed (Server 1)',
|
||||
provider: 'anyembed',
|
||||
serverIndex: 1,
|
||||
supportsEvents: false,
|
||||
supportsProgress: false,
|
||||
},
|
||||
{
|
||||
id: 'anyembed-2',
|
||||
name: 'AnyEmbed (Server 2)',
|
||||
provider: 'anyembed',
|
||||
serverIndex: 2,
|
||||
supportsEvents: false,
|
||||
supportsProgress: false,
|
||||
},
|
||||
{
|
||||
id: 'anyembed-3',
|
||||
name: 'AnyEmbed (Server 3)',
|
||||
provider: 'anyembed',
|
||||
serverIndex: 3,
|
||||
supportsEvents: false,
|
||||
supportsProgress: false,
|
||||
},
|
||||
{
|
||||
id: 'anyembed-4',
|
||||
name: 'AnyEmbed (Server 4)',
|
||||
provider: 'anyembed',
|
||||
serverIndex: 4,
|
||||
supportsEvents: false,
|
||||
supportsProgress: false,
|
||||
},
|
||||
{
|
||||
id: 'anyembed-5',
|
||||
name: 'AnyEmbed (Server 5)',
|
||||
provider: 'anyembed',
|
||||
serverIndex: 5,
|
||||
supportsEvents: false,
|
||||
supportsProgress: false,
|
||||
},
|
||||
];
|
||||
|
||||
export const anyembedProvider: StreamingProvider = {
|
||||
id: 'anyembed',
|
||||
name: 'AnyEmbed',
|
||||
servers: ANYEMBED_SERVERS,
|
||||
|
||||
getStreamUrl(request: StreamRequest, server: StreamingServer): string {
|
||||
// Prefer IMDB ID if available (with tt prefix), fall back to TMDB ID
|
||||
const id = request.imdbId || String(request.tmdbId);
|
||||
|
||||
let basePath: string;
|
||||
if (request.type === 'movie') {
|
||||
basePath = `/movie/${id}`;
|
||||
} else {
|
||||
basePath = `/tv/${id}/${request.season}/${request.episode}`;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
if (server.serverIndex) {
|
||||
params.set('server', String(server.serverIndex));
|
||||
}
|
||||
|
||||
const query = params.toString();
|
||||
return `https://anyembed.xyz${basePath}${query ? `?${query}` : ''}`;
|
||||
},
|
||||
|
||||
getSandboxPolicy(): string {
|
||||
return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';
|
||||
},
|
||||
|
||||
getAllowedFeatures(): string {
|
||||
return 'autoplay; fullscreen; picture-in-picture; encrypted-media';
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,3 @@
|
||||
export { vidlinkProvider } from './vidlink';
|
||||
export { vidkingProvider } from './vidking';
|
||||
export { anyembedProvider } from './anyembed';
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { StreamingProvider, StreamingServer, StreamRequest } from '../types';
|
||||
|
||||
const VIDKING_SERVERS: StreamingServer[] = [
|
||||
{
|
||||
id: 'vidking-default',
|
||||
name: 'VidKing',
|
||||
provider: 'vidking',
|
||||
supportsEvents: true,
|
||||
supportsProgress: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const vidkingProvider: StreamingProvider = {
|
||||
id: 'vidking',
|
||||
name: 'VidKing',
|
||||
servers: VIDKING_SERVERS,
|
||||
|
||||
getStreamUrl(request: StreamRequest, _server: StreamingServer): string {
|
||||
const params = new URLSearchParams();
|
||||
params.set('autoPlay', 'true');
|
||||
params.set('nextEpisode', 'true');
|
||||
params.set('episodeSelector', 'true');
|
||||
|
||||
if (request.startAt && request.startAt > 0) {
|
||||
params.set('progress', String(Math.floor(request.startAt)));
|
||||
}
|
||||
|
||||
let basePath: string;
|
||||
if (request.type === 'movie') {
|
||||
basePath = `/embed/movie/${request.tmdbId}`;
|
||||
} else {
|
||||
basePath = `/embed/tv/${request.tmdbId}/${request.season}/${request.episode}`;
|
||||
}
|
||||
|
||||
return `https://www.vidking.net${basePath}?${params.toString()}`;
|
||||
},
|
||||
|
||||
getSandboxPolicy(): string {
|
||||
return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';
|
||||
},
|
||||
|
||||
getAllowedFeatures(): string {
|
||||
return 'autoplay; fullscreen; picture-in-picture; encrypted-media';
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { StreamingProvider, StreamingServer, StreamRequest } from '../types';
|
||||
|
||||
const VIDLINK_SERVERS: StreamingServer[] = [
|
||||
{
|
||||
id: 'vidlink-default',
|
||||
name: 'VidLink (Default)',
|
||||
provider: 'vidlink',
|
||||
supportsEvents: true,
|
||||
supportsProgress: true,
|
||||
},
|
||||
{
|
||||
id: 'vidlink-jw',
|
||||
name: 'VidLink (JW Player)',
|
||||
provider: 'vidlink',
|
||||
serverIndex: 2,
|
||||
supportsEvents: true,
|
||||
supportsProgress: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const vidlinkProvider: StreamingProvider = {
|
||||
id: 'vidlink',
|
||||
name: 'VidLink',
|
||||
servers: VIDLINK_SERVERS,
|
||||
|
||||
getStreamUrl(request: StreamRequest, server: StreamingServer): string {
|
||||
const params = new URLSearchParams();
|
||||
params.set('autoplay', 'true');
|
||||
params.set('title', 'false');
|
||||
params.set('poster', 'true');
|
||||
params.set('nextbutton', 'true');
|
||||
|
||||
if (server.serverIndex === 2) {
|
||||
params.set('player', 'jw');
|
||||
}
|
||||
|
||||
if (request.startAt && request.startAt > 0) {
|
||||
params.set('startAt', String(Math.floor(request.startAt)));
|
||||
}
|
||||
|
||||
let basePath: string;
|
||||
if (request.type === 'movie') {
|
||||
basePath = `/movie/${request.tmdbId}`;
|
||||
} else {
|
||||
basePath = `/tv/${request.tmdbId}/${request.season}/${request.episode}`;
|
||||
}
|
||||
|
||||
return `https://vidlink.pro${basePath}?${params.toString()}`;
|
||||
},
|
||||
|
||||
getSandboxPolicy(): string {
|
||||
return 'allow-scripts allow-same-origin allow-forms allow-popups allow-presentation';
|
||||
},
|
||||
|
||||
getAllowedFeatures(): string {
|
||||
return 'autoplay; fullscreen; picture-in-picture; encrypted-media';
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,304 @@
|
||||
import type {
|
||||
StreamingProvider,
|
||||
StreamingServer,
|
||||
StreamRequest,
|
||||
StreamResponse,
|
||||
StreamError,
|
||||
WatchProgressData,
|
||||
AutoMarkWatchedConfig,
|
||||
PlayerEvent,
|
||||
} from './types';
|
||||
import { vidlinkProvider, vidkingProvider, anyembedProvider } from './providers';
|
||||
|
||||
const STORAGE_KEYS = {
|
||||
PREFERRED_SERVER: 'showy_preferred_server',
|
||||
WATCH_PROGRESS: 'showy_watch_progress',
|
||||
AUTO_MARK_WATCHED: 'showy_auto_mark_watched',
|
||||
AUTO_MARK_PROMPT_SHOWN: 'showy_auto_mark_prompt_shown',
|
||||
WATCH_LOGS: 'showy_watch_logs',
|
||||
} as const;
|
||||
|
||||
/** All registered streaming providers */
|
||||
const providers: StreamingProvider[] = [
|
||||
vidlinkProvider,
|
||||
vidkingProvider,
|
||||
anyembedProvider,
|
||||
];
|
||||
|
||||
/** Get all available servers from all providers */
|
||||
export function getAllServers(): StreamingServer[] {
|
||||
return providers.flatMap((p) => p.servers);
|
||||
}
|
||||
|
||||
/** Get a provider by server ID */
|
||||
export function getProviderForServer(serverId: string): StreamingProvider | undefined {
|
||||
return providers.find((p) => p.servers.some((s) => s.id === serverId));
|
||||
}
|
||||
|
||||
/** Get a server by ID */
|
||||
export function getServerById(serverId: string): StreamingServer | undefined {
|
||||
return getAllServers().find((s) => s.id === serverId);
|
||||
}
|
||||
|
||||
/** Build a stream URL for the given request and server */
|
||||
export function getStreamUrl(request: StreamRequest, server: StreamingServer): StreamResponse | StreamError {
|
||||
const provider = getProviderForServer(server.id);
|
||||
if (!provider) {
|
||||
return {
|
||||
server,
|
||||
message: 'Provider not found for this server',
|
||||
code: 'UNAVAILABLE',
|
||||
};
|
||||
}
|
||||
|
||||
// Validate the request
|
||||
if (!request.tmdbId && !request.imdbId) {
|
||||
return {
|
||||
server,
|
||||
message: 'A valid TMDB or IMDB ID is required',
|
||||
code: 'INVALID_ID',
|
||||
};
|
||||
}
|
||||
|
||||
if (request.type === 'tv' && (!request.season || !request.episode)) {
|
||||
return {
|
||||
server,
|
||||
message: 'Season and episode numbers are required for TV shows',
|
||||
code: 'MISSING_EPISODE',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const url = provider.getStreamUrl(request, server);
|
||||
return { url, server, request };
|
||||
} catch {
|
||||
return {
|
||||
server,
|
||||
message: 'Failed to build stream URL',
|
||||
code: 'UNKNOWN',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if a response is an error */
|
||||
export function isStreamError(result: StreamResponse | StreamError): result is StreamError {
|
||||
return 'code' in result;
|
||||
}
|
||||
|
||||
/** Get iframe sandbox policy for a server */
|
||||
export function getServerSandboxPolicy(serverId: string): string {
|
||||
const provider = getProviderForServer(serverId);
|
||||
return provider?.getSandboxPolicy() ?? 'allow-scripts allow-same-origin';
|
||||
}
|
||||
|
||||
/** Get iframe allowed features for a server */
|
||||
export function getServerAllowedFeatures(serverId: string): string {
|
||||
const provider = getProviderForServer(serverId);
|
||||
return provider?.getAllowedFeatures() ?? 'autoplay; fullscreen';
|
||||
}
|
||||
|
||||
// --- Persistence ---
|
||||
|
||||
/** Get the user's preferred server ID */
|
||||
export function getPreferredServerId(): string | null {
|
||||
try {
|
||||
return localStorage.getItem(STORAGE_KEYS.PREFERRED_SERVER);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Save the user's preferred server ID */
|
||||
export function setPreferredServerId(serverId: string): void {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEYS.PREFERRED_SERVER, serverId);
|
||||
} catch {
|
||||
// Storage not available
|
||||
}
|
||||
}
|
||||
|
||||
/** Get the preferred server, falling back to first available */
|
||||
export function getPreferredServer(): StreamingServer {
|
||||
const preferredId = getPreferredServerId();
|
||||
if (preferredId) {
|
||||
const server = getServerById(preferredId);
|
||||
if (server) return server;
|
||||
}
|
||||
return getAllServers()[0];
|
||||
}
|
||||
|
||||
// --- Watch Progress ---
|
||||
|
||||
/** Get all watch progress data */
|
||||
export function getWatchProgress(): Record<string, WatchProgressData> {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.WATCH_PROGRESS);
|
||||
return data ? JSON.parse(data) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** Get watch progress for a specific entry */
|
||||
export function getEntryWatchProgress(tmdbId: number): WatchProgressData | null {
|
||||
const progress = getWatchProgress();
|
||||
return progress[String(tmdbId)] || null;
|
||||
}
|
||||
|
||||
/** Save watch progress for an entry */
|
||||
export function saveWatchProgress(data: WatchProgressData): void {
|
||||
try {
|
||||
const progress = getWatchProgress();
|
||||
progress[String(data.tmdbId)] = { ...data, lastUpdated: Date.now() };
|
||||
localStorage.setItem(STORAGE_KEYS.WATCH_PROGRESS, JSON.stringify(progress));
|
||||
} catch {
|
||||
// Storage not available
|
||||
}
|
||||
}
|
||||
|
||||
/** Get the episode progress key */
|
||||
function getEpisodeKey(season: number, episode: number): string {
|
||||
return `s${season}e${episode}`;
|
||||
}
|
||||
|
||||
/** Update progress from a player event */
|
||||
export function updateProgressFromEvent(
|
||||
event: PlayerEvent,
|
||||
title: string,
|
||||
posterPath?: string
|
||||
): void {
|
||||
const existing = getEntryWatchProgress(event.tmdbId);
|
||||
|
||||
const data: WatchProgressData = {
|
||||
tmdbId: event.tmdbId,
|
||||
type: event.mediaType,
|
||||
title,
|
||||
posterPath,
|
||||
watched: event.currentTime,
|
||||
duration: event.duration,
|
||||
lastUpdated: Date.now(),
|
||||
...(existing?.showProgress ? { showProgress: existing.showProgress } : {}),
|
||||
};
|
||||
|
||||
if (event.mediaType === 'tv' && event.season && event.episode) {
|
||||
data.lastSeasonWatched = event.season;
|
||||
data.lastEpisodeWatched = event.episode;
|
||||
const key = getEpisodeKey(event.season, event.episode);
|
||||
data.showProgress = {
|
||||
...(data.showProgress || {}),
|
||||
[key]: {
|
||||
season: event.season,
|
||||
episode: event.episode,
|
||||
watched: event.currentTime,
|
||||
duration: event.duration,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
saveWatchProgress(data);
|
||||
}
|
||||
|
||||
// --- Auto Mark Watched ---
|
||||
|
||||
/** Get auto-mark-watched config */
|
||||
export function getAutoMarkWatchedConfig(): AutoMarkWatchedConfig {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.AUTO_MARK_WATCHED);
|
||||
return data ? JSON.parse(data) : { enabled: false, threshold: 90 };
|
||||
} catch {
|
||||
return { enabled: false, threshold: 90 };
|
||||
}
|
||||
}
|
||||
|
||||
/** Save auto-mark-watched config */
|
||||
export function setAutoMarkWatchedConfig(config: AutoMarkWatchedConfig): void {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEYS.AUTO_MARK_WATCHED, JSON.stringify(config));
|
||||
} catch {
|
||||
// Storage not available
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if the auto-mark prompt has been shown */
|
||||
export function hasAutoMarkPromptBeenShown(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN) === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Mark that the auto-mark prompt has been shown */
|
||||
export function markAutoMarkPromptShown(): void {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEYS.AUTO_MARK_PROMPT_SHOWN, 'true');
|
||||
} catch {
|
||||
// Storage not available
|
||||
}
|
||||
}
|
||||
|
||||
// --- Watch Logs (for future DB backup) ---
|
||||
|
||||
interface WatchLog {
|
||||
tmdbId: number;
|
||||
type: 'movie' | 'tv';
|
||||
title: string;
|
||||
season?: number;
|
||||
episode?: number;
|
||||
completedAt: number;
|
||||
duration: number;
|
||||
}
|
||||
|
||||
/** Log a completed watch event */
|
||||
export function logWatchCompleted(log: WatchLog): void {
|
||||
try {
|
||||
const logsData = localStorage.getItem(STORAGE_KEYS.WATCH_LOGS);
|
||||
const logs: WatchLog[] = logsData ? JSON.parse(logsData) : [];
|
||||
logs.push(log);
|
||||
// Keep last 500 logs max
|
||||
const trimmed = logs.slice(-500);
|
||||
localStorage.setItem(STORAGE_KEYS.WATCH_LOGS, JSON.stringify(trimmed));
|
||||
} catch {
|
||||
// Storage not available
|
||||
}
|
||||
}
|
||||
|
||||
/** Get all watch logs */
|
||||
export function getWatchLogs(): WatchLog[] {
|
||||
try {
|
||||
const data = localStorage.getItem(STORAGE_KEYS.WATCH_LOGS);
|
||||
return data ? JSON.parse(data) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Check if an episode/movie is considered "watched" based on progress */
|
||||
export function isConsideredWatched(watched: number, duration: number, threshold = 90): boolean {
|
||||
if (duration <= 0) return false;
|
||||
const percent = (watched / duration) * 100;
|
||||
return percent >= threshold;
|
||||
}
|
||||
|
||||
// --- URL Validation ---
|
||||
|
||||
const ALLOWED_ORIGINS = [
|
||||
'https://vidlink.pro',
|
||||
'https://www.vidking.net',
|
||||
'https://anyembed.xyz',
|
||||
];
|
||||
|
||||
/** Validate that an embed URL is from an allowed origin */
|
||||
export function isValidEmbedUrl(url: string): boolean {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return ALLOWED_ORIGINS.some((origin) => parsed.origin === origin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate a message event origin for player events */
|
||||
export function isValidEventOrigin(origin: string): boolean {
|
||||
return ALLOWED_ORIGINS.includes(origin);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Streaming system types
|
||||
|
||||
export type MediaType = 'movie' | 'tv';
|
||||
|
||||
export interface StreamingServer {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Provider group this server belongs to */
|
||||
provider: string;
|
||||
/** Sub-server index (for providers with multiple servers) */
|
||||
serverIndex?: number;
|
||||
/** Whether this server supports player events */
|
||||
supportsEvents: boolean;
|
||||
/** Whether this server supports progress tracking */
|
||||
supportsProgress: boolean;
|
||||
}
|
||||
|
||||
export interface StreamRequest {
|
||||
type: MediaType;
|
||||
tmdbId: number;
|
||||
imdbId?: string;
|
||||
season?: number;
|
||||
episode?: number;
|
||||
/** Resume from this timestamp in seconds */
|
||||
startAt?: number;
|
||||
}
|
||||
|
||||
export interface StreamResponse {
|
||||
url: string;
|
||||
server: StreamingServer;
|
||||
request: StreamRequest;
|
||||
}
|
||||
|
||||
export interface StreamError {
|
||||
server: StreamingServer;
|
||||
message: string;
|
||||
code: 'INVALID_ID' | 'MISSING_EPISODE' | 'TIMEOUT' | 'NETWORK' | 'UNAVAILABLE' | 'UNKNOWN';
|
||||
}
|
||||
|
||||
export interface PlayerEvent {
|
||||
event: 'play' | 'pause' | 'seeked' | 'ended' | 'timeupdate';
|
||||
currentTime: number;
|
||||
duration: number;
|
||||
mediaType: MediaType;
|
||||
tmdbId: number;
|
||||
season?: number;
|
||||
episode?: number;
|
||||
progress?: number;
|
||||
}
|
||||
|
||||
export interface WatchProgressData {
|
||||
tmdbId: number;
|
||||
type: MediaType;
|
||||
title: string;
|
||||
posterPath?: string;
|
||||
/** Current playback position in seconds */
|
||||
watched: number;
|
||||
/** Total duration in seconds */
|
||||
duration: number;
|
||||
/** For TV shows */
|
||||
lastSeasonWatched?: number;
|
||||
lastEpisodeWatched?: number;
|
||||
/** Per-episode progress for TV shows */
|
||||
showProgress?: Record<string, {
|
||||
season: number;
|
||||
episode: number;
|
||||
watched: number;
|
||||
duration: number;
|
||||
}>;
|
||||
lastUpdated: number;
|
||||
}
|
||||
|
||||
export interface StreamingProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
servers: StreamingServer[];
|
||||
/** Build the embed URL for the given request and server */
|
||||
getStreamUrl(request: StreamRequest, server: StreamingServer): string;
|
||||
/** Get iframe sandbox attributes */
|
||||
getSandboxPolicy(): string;
|
||||
/** Get allowed iframe features */
|
||||
getAllowedFeatures(): string;
|
||||
}
|
||||
|
||||
export interface AutoMarkWatchedConfig {
|
||||
enabled: boolean;
|
||||
/** Threshold percentage (0-100) to consider "finished" */
|
||||
threshold: number;
|
||||
}
|
||||
|
||||
export interface StreamingState {
|
||||
/** Currently selected server */
|
||||
activeServer: StreamingServer | null;
|
||||
/** All available servers */
|
||||
servers: StreamingServer[];
|
||||
/** Current stream URL */
|
||||
currentStreamUrl: string | null;
|
||||
/** Current request being played */
|
||||
currentRequest: StreamRequest | null;
|
||||
/** Loading state */
|
||||
isLoading: boolean;
|
||||
/** Error state */
|
||||
error: StreamError | null;
|
||||
/** Whether the player is visible */
|
||||
isPlayerOpen: boolean;
|
||||
/** Auto-mark-watched configuration */
|
||||
autoMarkWatched: AutoMarkWatchedConfig;
|
||||
/** Whether the auto-mark prompt has been shown */
|
||||
autoMarkPromptShown: boolean;
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
} from '@/components/ui/tooltip';
|
||||
import { CastList } from '@/components/entries/CastList';
|
||||
import { SeasonsContainer } from '@/components/entries/SeasonsContainer';
|
||||
import { StreamingSection } from '@/components/streaming/StreamingSection';
|
||||
// EpisodeWatchHistory is available for future use
|
||||
import { EntrySettingsDialog } from '@/components/dialogs/EntrySettingsDialog';
|
||||
import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog';
|
||||
@@ -410,6 +411,9 @@ export function EntryDetailsPage() {
|
||||
|
||||
{/* Sections */}
|
||||
<div className="mt-10 space-y-8">
|
||||
{/* Streaming player */}
|
||||
<StreamingSection entry={e} seasons={seasons} />
|
||||
|
||||
{e.credits && e.credits.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { useRef } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
useTrendingMovies,
|
||||
useTrendingTv,
|
||||
usePopularMovies,
|
||||
usePopularTv,
|
||||
useTopRatedMovies,
|
||||
useTopRatedTv,
|
||||
useUpcomingMovies,
|
||||
} from '@/hooks/useTmdb';
|
||||
import { useLibrary } from '@/hooks/useEntries';
|
||||
import { useCreateEntry } from '@/hooks/useEntries';
|
||||
import { useLibraryStore } from '@/stores/useLibraryStore';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ChevronLeft, ChevronRight, Star, Play, Plus } from 'lucide-react';
|
||||
import type { TmdbEntry } from '@/types';
|
||||
|
||||
/**
|
||||
* HomePage2 — Netflix-style layout
|
||||
* - Full-bleed hero with featured trending item
|
||||
* - Horizontal scroll rows per category (poster cards)
|
||||
* - No tabs: movies first, then TV in separate rows
|
||||
*/
|
||||
export function HomePage2() {
|
||||
useLibrary();
|
||||
|
||||
const trendingMovies = useTrendingMovies();
|
||||
const trendingTv = useTrendingTv();
|
||||
const popularMovies = usePopularMovies();
|
||||
const popularTv = usePopularTv();
|
||||
const topRatedMovies = useTopRatedMovies();
|
||||
const topRatedTv = useTopRatedTv();
|
||||
const upcomingMovies = useUpcomingMovies();
|
||||
|
||||
const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const popularMovieEntries = popularMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const popularTvEntries = popularTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const topRatedMovieEntries = topRatedMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const topRatedTvEntries = topRatedTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const upcomingMovieEntries = upcomingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
|
||||
const heroItem = trendingMovieEntries[0];
|
||||
const isLoading = trendingMovies.isLoading;
|
||||
|
||||
return (
|
||||
<div className="animate-page-enter -mx-6 -mt-6">
|
||||
{/* Hero Section */}
|
||||
<HeroSpotlight item={heroItem} isLoading={isLoading} />
|
||||
|
||||
{/* Scrollable Rows */}
|
||||
<div className="space-y-8 px-6 pt-8 pb-12">
|
||||
<ScrollRow
|
||||
title="Trending Movies"
|
||||
entries={trendingMovieEntries.slice(1, 20)}
|
||||
isLoading={trendingMovies.isLoading}
|
||||
category="trending"
|
||||
/>
|
||||
<ScrollRow
|
||||
title="Trending TV Shows"
|
||||
entries={trendingTvEntries.slice(0, 20)}
|
||||
isLoading={trendingTv.isLoading}
|
||||
category="trending"
|
||||
/>
|
||||
<ScrollRow
|
||||
title="Popular Movies"
|
||||
entries={popularMovieEntries.slice(0, 20)}
|
||||
isLoading={popularMovies.isLoading}
|
||||
category="popular"
|
||||
/>
|
||||
<ScrollRow
|
||||
title="Popular TV Shows"
|
||||
entries={popularTvEntries.slice(0, 20)}
|
||||
isLoading={popularTv.isLoading}
|
||||
category="popular"
|
||||
/>
|
||||
<ScrollRow
|
||||
title="Top Rated Movies"
|
||||
entries={topRatedMovieEntries.slice(0, 20)}
|
||||
isLoading={topRatedMovies.isLoading}
|
||||
category="top-rated"
|
||||
/>
|
||||
<ScrollRow
|
||||
title="Top Rated TV Shows"
|
||||
entries={topRatedTvEntries.slice(0, 20)}
|
||||
isLoading={topRatedTv.isLoading}
|
||||
category="top-rated"
|
||||
/>
|
||||
<ScrollRow
|
||||
title="Upcoming Movies"
|
||||
entries={upcomingMovieEntries.slice(0, 20)}
|
||||
isLoading={upcomingMovies.isLoading}
|
||||
category="upcoming"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Hero Spotlight ──────────────────────────────────────────────── */
|
||||
|
||||
function HeroSpotlight({ item, isLoading }: { item?: TmdbEntry; isLoading: boolean }) {
|
||||
const createEntry = useCreateEntry();
|
||||
const libraryEntries = useLibraryStore((s) => s.entries);
|
||||
|
||||
if (isLoading || !item) {
|
||||
return <div className="h-[70vh] bg-muted animate-pulse" />;
|
||||
}
|
||||
|
||||
const title = item.title || item.name || 'Untitled';
|
||||
const backdrop = item.backdrop_path
|
||||
? `https://image.tmdb.org/t/p/original${item.backdrop_path}`
|
||||
: null;
|
||||
const isTv = item.media_type === 'tv' || !!item.name;
|
||||
const matchedEntry = Array.from(libraryEntries.values()).find(
|
||||
(e) => e.entryIds?.tmdb_id === item.id
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="relative h-[70vh] min-h-125">
|
||||
{backdrop && (
|
||||
<img
|
||||
src={backdrop}
|
||||
alt=""
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
/>
|
||||
)}
|
||||
{/* Gradient overlays */}
|
||||
<div className="absolute inset-0 bg-linear-to-r from-black/80 via-black/40 to-transparent" />
|
||||
<div className="absolute inset-0 bg-linear-to-t from-background via-transparent to-transparent" />
|
||||
|
||||
{/* Content */}
|
||||
<div className="absolute bottom-16 left-8 sm:left-12 z-10 max-w-xl space-y-4">
|
||||
<div className="flex items-center gap-2 text-white/60 text-xs uppercase tracking-widest font-medium">
|
||||
<span>{isTv ? 'TV Series' : 'Movie'}</span>
|
||||
{item.vote_average > 0 && (
|
||||
<span className="flex items-center gap-1 text-yellow-400">
|
||||
<Star className="h-3 w-3 fill-current" />
|
||||
{item.vote_average.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<h1 className="text-4xl sm:text-6xl font-black text-white leading-none tracking-tight">
|
||||
{title}
|
||||
</h1>
|
||||
{item.overview && (
|
||||
<p className="text-sm sm:text-base text-white/70 line-clamp-3 leading-relaxed">
|
||||
{item.overview}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-3 pt-2">
|
||||
{matchedEntry ? (
|
||||
<Link to={`/entry/${matchedEntry.id}`}>
|
||||
<Button size="lg" className="rounded-full gap-2 px-6 font-semibold">
|
||||
<Play className="h-4 w-4 fill-current" />
|
||||
View Details
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
size="lg"
|
||||
className="rounded-full gap-2 px-6 font-semibold"
|
||||
onClick={() => createEntry.mutate({ tmdb_id: item.id, is_tvserie: isTv })}
|
||||
disabled={createEntry.isPending}
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
Add to Library
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Horizontal Scroll Row ───────────────────────────────────────── */
|
||||
|
||||
function ScrollRow({
|
||||
title,
|
||||
entries,
|
||||
isLoading,
|
||||
category,
|
||||
}: {
|
||||
title: string;
|
||||
entries: TmdbEntry[];
|
||||
isLoading: boolean;
|
||||
category: string;
|
||||
}) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const scroll = (direction: 'left' | 'right') => {
|
||||
if (!scrollRef.current) return;
|
||||
const amount = scrollRef.current.clientWidth * 0.75;
|
||||
scrollRef.current.scrollBy({
|
||||
left: direction === 'left' ? -amount : amount,
|
||||
behavior: 'smooth',
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="h-6 w-48 bg-muted rounded animate-pulse" />
|
||||
<div className="flex gap-3 overflow-hidden">
|
||||
{Array.from({ length: 8 }).map((_, i) => (
|
||||
<div key={i} className="w-37.5 h-56.25 shrink-0 bg-muted rounded-lg animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3 group/row">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-lg font-semibold">{title}</h3>
|
||||
<Link
|
||||
to={`/discover/${category}`}
|
||||
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
See All →
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
{/* Scroll buttons */}
|
||||
<button
|
||||
onClick={() => scroll('left')}
|
||||
className="absolute -left-3 top-1/2 -translate-y-1/2 z-10 h-10 w-10 rounded-full bg-background/90 border shadow-lg flex items-center justify-center opacity-0 group-hover/row:opacity-100 transition-opacity hover:bg-accent"
|
||||
>
|
||||
<ChevronLeft className="h-5 w-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => scroll('right')}
|
||||
className="absolute -right-3 top-1/2 -translate-y-1/2 z-10 h-10 w-10 rounded-full bg-background/90 border shadow-lg flex items-center justify-center opacity-0 group-hover/row:opacity-100 transition-opacity hover:bg-accent"
|
||||
>
|
||||
<ChevronRight className="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
{/* Cards */}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="flex gap-3 overflow-x-auto scrollbar-hide scroll-smooth pb-2"
|
||||
>
|
||||
{entries.map((entry) => (
|
||||
<PosterCard key={entry.id} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Poster Card ─────────────────────────────────────────────────── */
|
||||
|
||||
function PosterCard({ entry }: { entry: TmdbEntry }) {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const poster = entry.poster_path
|
||||
? `https://image.tmdb.org/t/p/w342${entry.poster_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={linkTo}
|
||||
className="group/card shrink-0 w-37.5 space-y-2 transition-transform hover:scale-105"
|
||||
>
|
||||
<div className="relative aspect-2/3 rounded-lg overflow-hidden bg-muted">
|
||||
{poster ? (
|
||||
<img src={poster} alt={title} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<div className="h-full w-full flex items-center justify-center text-muted-foreground text-xs">
|
||||
No Image
|
||||
</div>
|
||||
)}
|
||||
{/* Hover overlay */}
|
||||
<div className="absolute inset-0 bg-black/0 group-hover/card:bg-black/40 transition-colors flex items-center justify-center">
|
||||
<Play className="h-8 w-8 text-white opacity-0 group-hover/card:opacity-100 transition-opacity fill-current" />
|
||||
</div>
|
||||
{/* Rating badge */}
|
||||
{entry.vote_average > 0 && (
|
||||
<div className="absolute top-2 right-2 bg-black/70 backdrop-blur-sm rounded-full px-1.5 py-0.5 flex items-center gap-0.5 text-[10px] text-yellow-400 font-medium">
|
||||
<Star className="h-2.5 w-2.5 fill-current" />
|
||||
{entry.vote_average.toFixed(1)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm font-medium truncate">{title}</p>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,661 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
useTrendingMovies,
|
||||
useTrendingTv,
|
||||
usePopularMovies,
|
||||
usePopularTv,
|
||||
useTopRatedMovies,
|
||||
useTopRatedTv,
|
||||
useUpcomingMovies,
|
||||
} from '@/hooks/useTmdb';
|
||||
import { useLibrary, useCreateEntry } from '@/hooks/useEntries';
|
||||
import { useLibraryStore } from '@/stores/useLibraryStore';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Star,
|
||||
Plus,
|
||||
Play,
|
||||
TrendingUp,
|
||||
Award,
|
||||
Calendar,
|
||||
Search,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
} from 'lucide-react';
|
||||
import type { TmdbEntry } from '@/types';
|
||||
|
||||
export function HomePage3() {
|
||||
useLibrary();
|
||||
|
||||
const trendingMovies = useTrendingMovies();
|
||||
const trendingTv = useTrendingTv();
|
||||
const popularMovies = usePopularMovies();
|
||||
const popularTv = usePopularTv();
|
||||
const topRatedMovies = useTopRatedMovies();
|
||||
const topRatedTv = useTopRatedTv();
|
||||
const upcomingMovies = useUpcomingMovies();
|
||||
|
||||
const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const popularMovieEntries = popularMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const popularTvEntries = popularTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const topRatedMovieEntries = topRatedMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const topRatedTvEntries = topRatedTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const upcomingMovieEntries = upcomingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
|
||||
// Trending grid auto-rotation: exit→swap→enter
|
||||
const [trendingIdx, setTrendingIdx] = useState(0);
|
||||
const [trendingPhase, setTrendingPhase] = useState<'idle' | 'exit' | 'enter'>('idle');
|
||||
const trendingPool = trendingMovieEntries.slice(2);
|
||||
const visibleTrending =
|
||||
trendingPool.length >= 4
|
||||
? [0, 1, 2, 3].map((offset) => trendingPool[(trendingIdx + offset) % trendingPool.length])
|
||||
: trendingPool;
|
||||
|
||||
useEffect(() => {
|
||||
if (trendingPool.length <= 4) return;
|
||||
const timer = setInterval(() => {
|
||||
// 1. Slide existing cards out to the left
|
||||
setTrendingPhase('exit');
|
||||
setTimeout(() => {
|
||||
// 2. Swap in next set
|
||||
setTrendingIdx((i) => i + 1);
|
||||
setTrendingPhase('enter');
|
||||
// 3. Return to idle after enter animation finishes
|
||||
setTimeout(() => setTrendingPhase('idle'), 600);
|
||||
}, 380);
|
||||
}, 7000);
|
||||
return () => clearInterval(timer);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [trendingPool.length]);
|
||||
|
||||
const isLoading =
|
||||
trendingMovies.isLoading ||
|
||||
popularMovies.isLoading ||
|
||||
topRatedMovies.isLoading ||
|
||||
upcomingMovies.isLoading;
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSkeleton />;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="animate-page-enter space-y-12 pb-12">
|
||||
{/* ─── Hero Slider — bleeds full width, breaks out of container padding ─── */}
|
||||
<div className="-mx-4 -mt-18 md:-mx-6 md:-mt-6">
|
||||
<HeroSlider entries={trendingMovieEntries} />
|
||||
</div>
|
||||
|
||||
{/* ─── Trending Now ─────────────────────────────────────────────── */}
|
||||
<section className="space-y-5">
|
||||
<SectionHeader
|
||||
icon={<TrendingUp className="h-5 w-5 text-rose-500" />}
|
||||
title="Trending Now"
|
||||
category="trending"
|
||||
/>
|
||||
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
|
||||
{/* 2x2 backdrop grid — slides out left, new set slides in from right */}
|
||||
<div
|
||||
className="xl:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-4 overflow-hidden"
|
||||
style={{
|
||||
opacity: trendingPhase === 'exit' ? 0 : 1,
|
||||
transform: trendingPhase === 'exit' ? 'translateX(-28px)' : 'translateX(0)',
|
||||
transition: trendingPhase === 'exit'
|
||||
? 'opacity 380ms ease, transform 380ms ease'
|
||||
: 'none',
|
||||
}}
|
||||
>
|
||||
{visibleTrending.map((item, i) => (
|
||||
<BackdropCard
|
||||
key={`${item.id}-${trendingIdx}`}
|
||||
entry={item}
|
||||
animClass={trendingPhase === 'enter' ? 'animate-slide-from-right' : undefined}
|
||||
animDelay={trendingPhase === 'enter' ? i * 90 : 0}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{/* Numbered TV list */}
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs uppercase tracking-widest text-muted-foreground font-semibold mb-3">
|
||||
Trending TV
|
||||
</p>
|
||||
{trendingTvEntries.slice(0, 8).map((item, i) => (
|
||||
<NumberedListItem key={item.id} entry={item} rank={i + 1} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ─── Popular Right Now — infinite moving belt ─────────────────── */}
|
||||
<section className="space-y-5">
|
||||
<SectionHeader
|
||||
icon={<Play className="h-5 w-5 text-blue-500" />}
|
||||
title="Popular Right Now"
|
||||
category="popular"
|
||||
/>
|
||||
{/* Overflow clip so the belt bleeds edge-to-edge within the section */}
|
||||
<div className="overflow-hidden">
|
||||
<div
|
||||
className="flex gap-4"
|
||||
style={{
|
||||
animation: 'marquee-left 40s linear infinite',
|
||||
width: 'max-content',
|
||||
}}
|
||||
onMouseEnter={(e) => ((e.currentTarget as HTMLDivElement).style.animationPlayState = 'paused')}
|
||||
onMouseLeave={(e) => ((e.currentTarget as HTMLDivElement).style.animationPlayState = 'running')}
|
||||
>
|
||||
{/* Original + duplicate for seamless loop */}
|
||||
{[...Array(2)].flatMap((_, pass) =>
|
||||
[...popularMovieEntries.slice(0, 8), ...popularTvEntries.slice(0, 6)].map((item) => (
|
||||
<BackdropScrollCard key={`${pass}-${item.id}`} entry={item} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ─── Top Rated ─────────────────────────────────────────────────── */}
|
||||
<section className="space-y-5">
|
||||
<SectionHeader
|
||||
icon={<Award className="h-5 w-5 text-yellow-500" />}
|
||||
title="Top Rated"
|
||||
category="top-rated"
|
||||
/>
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div className="space-y-4">
|
||||
<p className="text-xs uppercase tracking-widest text-muted-foreground font-semibold">
|
||||
Movies
|
||||
</p>
|
||||
{topRatedMovieEntries[0] && (
|
||||
<BackdropCard entry={topRatedMovieEntries[0]} showRating />
|
||||
)}
|
||||
<div className="grid grid-cols-4 gap-3">
|
||||
{topRatedMovieEntries.slice(1, 5).map((item) => (
|
||||
<MiniPosterCard key={item.id} entry={item} hideTitle />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
<p className="text-xs uppercase tracking-widest text-muted-foreground font-semibold">
|
||||
TV Shows
|
||||
</p>
|
||||
<div className="space-y-1">
|
||||
{topRatedTvEntries.slice(0, 10).map((item, i) => (
|
||||
<NumberedListItem key={item.id} entry={item} rank={i + 1} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ─── Coming Soon — horizontal scroll, small cards ─────────────── */}
|
||||
<section className="space-y-5">
|
||||
<SectionHeader
|
||||
icon={<Calendar className="h-5 w-5 text-emerald-500" />}
|
||||
title="Coming Soon"
|
||||
category="upcoming"
|
||||
/>
|
||||
<div
|
||||
className="flex gap-3 overflow-x-auto pb-2"
|
||||
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' } as React.CSSProperties}
|
||||
>
|
||||
{upcomingMovieEntries.slice(0, 14).map((item) => (
|
||||
<UpcomingCard key={item.id} entry={item} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Hero Slider ───────────────────────────────────────────────────── */
|
||||
|
||||
function HeroSlider({ entries }: { entries: TmdbEntry[] }) {
|
||||
const navigate = useNavigate();
|
||||
const [activeIndex, setActiveIndex] = useState(0);
|
||||
const [searchInput, setSearchInput] = useState('');
|
||||
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const createEntry = useCreateEntry();
|
||||
const libraryEntries = useLibraryStore((s) => s.entries);
|
||||
|
||||
const slides = entries.slice(0, 8);
|
||||
|
||||
const go = (idx: number) => {
|
||||
setActiveIndex((idx + slides.length) % slides.length);
|
||||
};
|
||||
|
||||
const startAutoplay = () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
if (slides.length === 0) return;
|
||||
intervalRef.current = setInterval(
|
||||
() => setActiveIndex((i) => (i + 1) % slides.length),
|
||||
6000,
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
startAutoplay();
|
||||
return () => {
|
||||
if (intervalRef.current) clearInterval(intervalRef.current);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [slides.length]);
|
||||
|
||||
const handleSearch = () => {
|
||||
const q = searchInput.trim();
|
||||
if (q) navigate(`/search?q=${encodeURIComponent(q)}`);
|
||||
};
|
||||
|
||||
if (slides.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative w-full overflow-hidden"
|
||||
style={{ aspectRatio: '16/9', maxHeight: '70vh' }}
|
||||
>
|
||||
{/* ── Slide track — full-width flex rail that translates on index change ── */}
|
||||
<div
|
||||
className="flex h-full transition-transform duration-700 ease-in-out will-change-transform"
|
||||
style={{
|
||||
width: `${slides.length * 100}%`,
|
||||
transform: `translateX(calc(-${activeIndex} / ${slides.length} * 100%))`,
|
||||
}}
|
||||
>
|
||||
{slides.map((entry) => {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const backdrop = entry.backdrop_path
|
||||
? `https://image.tmdb.org/t/p/original${entry.backdrop_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const matchedEntry = Array.from(libraryEntries.values()).find(
|
||||
(e) => e.entryIds?.tmdb_id === entry.id,
|
||||
);
|
||||
return (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="relative h-full shrink-0"
|
||||
style={{ width: `${100 / slides.length}%` }}
|
||||
>
|
||||
{backdrop ? (
|
||||
<img
|
||||
src={backdrop}
|
||||
alt=""
|
||||
className="absolute inset-0 h-full w-full object-cover rounded-none"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 bg-linear-to-br from-primary/20 to-muted" />
|
||||
)}
|
||||
<div className="absolute inset-0 bg-linear-to-t from-black/90 via-black/20 to-black/50" />
|
||||
{/* Per-slide info — slides with the track */}
|
||||
<div className="absolute bottom-0 left-0 right-0 z-10 space-y-2 px-4 pb-5 md:px-6 md:pb-8">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded-full bg-white/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-white/60 backdrop-blur-sm">
|
||||
{isTv ? 'Series' : 'Movie'}
|
||||
</span>
|
||||
{entry.vote_average > 0 && (
|
||||
<span className="flex items-center gap-1 text-xs text-yellow-400">
|
||||
<Star className="h-3 w-3 fill-current" />
|
||||
{entry.vote_average.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<h2 className="text-2xl font-black leading-tight text-white drop-shadow-lg md:text-4xl">
|
||||
{title}
|
||||
</h2>
|
||||
{entry.overview && (
|
||||
<p className="line-clamp-2 max-w-lg text-xs text-white/60 md:text-sm">
|
||||
{entry.overview}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2 pt-1">
|
||||
{matchedEntry ? (
|
||||
<Link to={`/entry/${matchedEntry.id}`}>
|
||||
<Button size="sm" variant="secondary" className="rounded-full gap-1.5 text-xs">
|
||||
<Play className="h-3 w-3 fill-current" />
|
||||
Details
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="rounded-full gap-1.5 text-xs"
|
||||
onClick={() => createEntry.mutate({ tmdb_id: entry.id, is_tvserie: isTv })}
|
||||
disabled={createEntry.isPending}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
Add
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* ── Search bar — fixed top-center overlay ── */}
|
||||
<div className="absolute top-5 left-1/2 z-20 w-full max-w-sm -translate-x-1/2 px-4">
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/60" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search movies, TV shows..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
|
||||
className="w-full rounded-full border border-white/20 bg-black/40 py-2.5 pl-9 pr-4 text-sm text-white backdrop-blur-md placeholder-white/50 transition-colors focus:border-white/50 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Left arrow ── */}
|
||||
<button
|
||||
className="absolute left-3 top-1/2 z-20 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/30 text-white backdrop-blur-sm transition-colors hover:bg-black/60"
|
||||
onClick={() => { go(activeIndex - 1); startAutoplay(); }}
|
||||
aria-label="Previous"
|
||||
>
|
||||
<ChevronLeft className="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
{/* ── Right arrow ── */}
|
||||
<button
|
||||
className="absolute right-3 top-1/2 z-20 flex h-9 w-9 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/30 text-white backdrop-blur-sm transition-colors hover:bg-black/60"
|
||||
onClick={() => { go(activeIndex + 1); startAutoplay(); }}
|
||||
aria-label="Next"
|
||||
>
|
||||
<ChevronRight className="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
{/* ── Dot indicators — fixed bottom-right overlay ── */}
|
||||
<div className="absolute bottom-5 right-4 z-20 flex items-center gap-1.5 md:bottom-8 md:right-6">
|
||||
{slides.map((_, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => { go(i); startAutoplay(); }}
|
||||
aria-label={`Go to slide ${i + 1}`}
|
||||
className={`rounded-full transition-all duration-300 ${
|
||||
i === activeIndex
|
||||
? 'h-1.5 w-6 bg-white'
|
||||
: 'h-1.5 w-1.5 bg-white/30 hover:bg-white/60'
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Backdrop Card (16:9, used in grids) ───────────────────────────── */
|
||||
|
||||
function BackdropCard({
|
||||
entry,
|
||||
showRating,
|
||||
animClass,
|
||||
animDelay,
|
||||
}: {
|
||||
entry: TmdbEntry;
|
||||
showRating?: boolean;
|
||||
animClass?: string;
|
||||
animDelay?: number;
|
||||
}) {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const backdrop = entry.backdrop_path
|
||||
? `https://image.tmdb.org/t/p/w780${entry.backdrop_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={linkTo}
|
||||
className={`group relative block overflow-hidden rounded-xl bg-muted ${animClass ?? 'animate-page-enter'}`}
|
||||
style={{ aspectRatio: '16/9', animationDelay: animDelay ? `${animDelay}ms` : undefined }}
|
||||
>
|
||||
{backdrop ? (
|
||||
<img
|
||||
src={backdrop}
|
||||
alt={title}
|
||||
className="absolute inset-0 h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 bg-linear-to-br from-muted-foreground/20 to-muted" />
|
||||
)}
|
||||
<div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/10 to-transparent" />
|
||||
<div className="absolute bottom-0 left-0 right-0 p-3">
|
||||
<p className="truncate text-sm font-semibold text-white">{title}</p>
|
||||
{showRating && entry.vote_average > 0 && (
|
||||
<span className="mt-0.5 flex items-center gap-1 text-xs text-yellow-400">
|
||||
<Star className="h-3 w-3 fill-current" />
|
||||
{entry.vote_average.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Backdrop Scroll Card (fixed width, for horizontal scroll row) ─── */
|
||||
|
||||
function BackdropScrollCard({
|
||||
entry,
|
||||
}: {
|
||||
entry: TmdbEntry;
|
||||
}) {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const backdrop = entry.backdrop_path
|
||||
? `https://image.tmdb.org/t/p/w780${entry.backdrop_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={linkTo}
|
||||
className="group relative block shrink-0 overflow-hidden rounded-xl bg-muted"
|
||||
style={{ width: '260px', aspectRatio: '16/9' }}
|
||||
>
|
||||
{backdrop ? (
|
||||
<img
|
||||
src={backdrop}
|
||||
alt={title}
|
||||
className="absolute inset-0 h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 bg-linear-to-br from-muted-foreground/20 to-muted" />
|
||||
)}
|
||||
<div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/10 to-transparent" />
|
||||
<div className="absolute bottom-0 left-0 right-0 p-3">
|
||||
<p className="truncate text-sm font-semibold text-white">{title}</p>
|
||||
{entry.vote_average > 0 && (
|
||||
<span className="mt-0.5 flex items-center gap-1 text-xs text-yellow-400">
|
||||
<Star className="h-3 w-3 fill-current" />
|
||||
{entry.vote_average.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Numbered List Item ────────────────────────────────────────────── */
|
||||
|
||||
function NumberedListItem({ entry, rank }: { entry: TmdbEntry; rank: number }) {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const poster = entry.poster_path
|
||||
? `https://image.tmdb.org/t/p/w92${entry.poster_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={linkTo}
|
||||
className="group flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-accent/50"
|
||||
>
|
||||
<span className="w-8 text-center text-2xl font-black tabular-nums text-muted-foreground/40 transition-colors group-hover:text-foreground/60">
|
||||
{rank}
|
||||
</span>
|
||||
<div className="h-12 w-8 shrink-0 overflow-hidden rounded bg-muted">
|
||||
{poster && <img src={poster} alt="" className="h-full w-full object-cover" />}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{title}</p>
|
||||
{entry.vote_average > 0 && (
|
||||
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Star className="h-2.5 w-2.5 fill-yellow-400 text-yellow-400" />
|
||||
{entry.vote_average.toFixed(1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Mini Poster Card ──────────────────────────────────────────────── */
|
||||
|
||||
function MiniPosterCard({ entry, hideTitle }: { entry: TmdbEntry; hideTitle?: boolean }) {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const poster = entry.poster_path
|
||||
? `https://image.tmdb.org/t/p/w342${entry.poster_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
|
||||
|
||||
return (
|
||||
<Link to={linkTo} className="group space-y-2">
|
||||
<div className="relative overflow-hidden rounded-lg bg-muted" style={{ aspectRatio: '2/3' }}>
|
||||
{poster ? (
|
||||
<img
|
||||
src={poster}
|
||||
alt={title}
|
||||
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
|
||||
No Image
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!hideTitle && <p className="truncate text-xs font-medium">{title}</p>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Upcoming Card (small, for horizontal scroll) ──────────────────── */
|
||||
|
||||
function formatRelativeTime(dateStr: string): string {
|
||||
const now = new Date();
|
||||
const release = new Date(dateStr);
|
||||
const diffMs = release.getTime() - now.getTime();
|
||||
if (diffMs <= 0) return 'Out now';
|
||||
const totalMinutes = Math.floor(diffMs / 60000);
|
||||
const totalHours = Math.floor(totalMinutes / 60);
|
||||
const totalDays = Math.floor(totalHours / 24);
|
||||
const months = Math.floor(totalDays / 30);
|
||||
const remDays = totalDays % 30;
|
||||
if (months > 0 && remDays > 0) return `in ${months}m ${remDays}d`;
|
||||
if (months > 0) return `in ${months}m`;
|
||||
if (totalDays > 0) return `in ${totalDays} day${totalDays !== 1 ? 's' : ''}`;
|
||||
if (totalHours > 0) return `in ${totalHours} hour${totalHours !== 1 ? 's' : ''}`;
|
||||
if (totalMinutes > 0) return `in ${totalMinutes} min`;
|
||||
return 'Very soon';
|
||||
}
|
||||
|
||||
function UpcomingCard({ entry }: { entry: TmdbEntry }) {
|
||||
const title = entry.title || entry.name || 'Untitled';
|
||||
const poster = entry.poster_path
|
||||
? `https://image.tmdb.org/t/p/w185${entry.poster_path}`
|
||||
: null;
|
||||
const isTv = entry.media_type === 'tv' || !!entry.name;
|
||||
const linkTo = `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${entry.id}`;
|
||||
const releaseDate = entry.release_date || entry.first_air_date;
|
||||
const relativeTime = releaseDate ? formatRelativeTime(releaseDate) : null;
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={linkTo}
|
||||
className="group relative shrink-0 overflow-hidden rounded-xl border border-border/50 bg-card transition-colors hover:border-border"
|
||||
style={{ width: '110px' }}
|
||||
>
|
||||
<div className="relative overflow-hidden" style={{ aspectRatio: '2/3' }}>
|
||||
{poster ? (
|
||||
<img
|
||||
src={poster}
|
||||
alt={title}
|
||||
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center bg-muted text-xs text-muted-foreground">
|
||||
No Image
|
||||
</div>
|
||||
)}
|
||||
{/* Date overlay — always visible at bottom of poster */}
|
||||
{releaseDate && (
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-linear-to-t from-black/80 to-transparent px-2 py-2">
|
||||
<p className="text-[9px] font-semibold leading-tight text-white/90">
|
||||
{new Date(releaseDate).toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric',
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{/* Hover overlay — shows relative countdown */}
|
||||
{relativeTime && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 backdrop-blur-[1px] transition-opacity duration-200 group-hover:opacity-100">
|
||||
<span className="rounded-full bg-white/15 px-2.5 py-1 text-[10px] font-bold text-white backdrop-blur-sm">
|
||||
{relativeTime}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Section Header ────────────────────────────────────────────────── */
|
||||
|
||||
function SectionHeader({
|
||||
icon,
|
||||
title,
|
||||
category,
|
||||
}: {
|
||||
icon: React.ReactNode;
|
||||
title: string;
|
||||
category: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{icon}
|
||||
<h2 className="text-xl font-bold">{title}</h2>
|
||||
</div>
|
||||
<Link
|
||||
to={`/discover/${category}`}
|
||||
className="text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
Explore All →
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ─── Loading Skeleton ──────────────────────────────────────────────── */
|
||||
|
||||
function LoadingSkeleton() {
|
||||
return (
|
||||
<div className="animate-pulse space-y-12 pb-12">
|
||||
<div className="w-full rounded-2xl bg-muted" style={{ aspectRatio: '16/9', maxHeight: '70vh' }} />
|
||||
<div className="space-y-4">
|
||||
<div className="h-6 w-48 rounded bg-muted" />
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="rounded-xl bg-muted" style={{ aspectRatio: '16/9' }} />
|
||||
<div className="rounded-xl bg-muted" style={{ aspectRatio: '16/9' }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -22,6 +22,12 @@ import {
|
||||
const HomePage = lazy(() =>
|
||||
import('@/pages/HomePage').then((m) => ({ default: m.HomePage }))
|
||||
);
|
||||
const HomePage2 = lazy(() =>
|
||||
import('@/pages/HomePage2').then((m) => ({ default: m.HomePage2 }))
|
||||
);
|
||||
const HomePage3 = lazy(() =>
|
||||
import('@/pages/HomePage3').then((m) => ({ default: m.HomePage3 }))
|
||||
);
|
||||
const DashboardPage = lazy(() =>
|
||||
import('@/pages/DashboardPage').then((m) => ({ default: m.DashboardPage }))
|
||||
);
|
||||
@@ -105,6 +111,22 @@ export const router = createRouter([
|
||||
</SuspensePage>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: '/home2',
|
||||
element: (
|
||||
<SuspensePage fallback={<HomeSkeleton />}>
|
||||
<HomePage2 />
|
||||
</SuspensePage>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: '/home3',
|
||||
element: (
|
||||
<SuspensePage fallback={<HomeSkeleton />}>
|
||||
<HomePage3 />
|
||||
</SuspensePage>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: '/search',
|
||||
element: (
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { create } from 'zustand';
|
||||
import type { StreamingServer, StreamRequest, StreamError, AutoMarkWatchedConfig } from '@/lib/streaming/types';
|
||||
import {
|
||||
getAllServers,
|
||||
getPreferredServer,
|
||||
setPreferredServerId,
|
||||
getStreamUrl,
|
||||
isStreamError,
|
||||
getAutoMarkWatchedConfig,
|
||||
setAutoMarkWatchedConfig,
|
||||
hasAutoMarkPromptBeenShown,
|
||||
markAutoMarkPromptShown,
|
||||
} from '@/lib/streaming/streaming-manager';
|
||||
|
||||
interface StreamingStore {
|
||||
// State
|
||||
activeServer: StreamingServer | null;
|
||||
servers: StreamingServer[];
|
||||
currentStreamUrl: string | null;
|
||||
currentRequest: StreamRequest | null;
|
||||
isLoading: boolean;
|
||||
error: StreamError | null;
|
||||
isPlayerOpen: boolean;
|
||||
autoMarkWatched: AutoMarkWatchedConfig;
|
||||
autoMarkPromptShown: boolean;
|
||||
|
||||
// Actions
|
||||
initialize: () => void;
|
||||
setActiveServer: (server: StreamingServer) => void;
|
||||
play: (request: StreamRequest) => void;
|
||||
switchServer: (serverId: string) => void;
|
||||
closePlayer: () => void;
|
||||
setError: (error: StreamError | null) => void;
|
||||
setLoading: (loading: boolean) => void;
|
||||
enableAutoMarkWatched: (threshold?: number) => void;
|
||||
disableAutoMarkWatched: () => void;
|
||||
dismissAutoMarkPrompt: () => void;
|
||||
tryNextServer: () => void;
|
||||
}
|
||||
|
||||
export const useStreamingStore = create<StreamingStore>((set, get) => ({
|
||||
activeServer: null,
|
||||
servers: [],
|
||||
currentStreamUrl: null,
|
||||
currentRequest: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
isPlayerOpen: false,
|
||||
autoMarkWatched: getAutoMarkWatchedConfig(),
|
||||
autoMarkPromptShown: hasAutoMarkPromptBeenShown(),
|
||||
|
||||
initialize: () => {
|
||||
const servers = getAllServers();
|
||||
const preferred = getPreferredServer();
|
||||
set({
|
||||
servers,
|
||||
activeServer: preferred,
|
||||
autoMarkWatched: getAutoMarkWatchedConfig(),
|
||||
autoMarkPromptShown: hasAutoMarkPromptBeenShown(),
|
||||
});
|
||||
},
|
||||
|
||||
setActiveServer: (server: StreamingServer) => {
|
||||
setPreferredServerId(server.id);
|
||||
set({ activeServer: server });
|
||||
|
||||
// If there's an active request, rebuild the URL with the new server
|
||||
const { currentRequest } = get();
|
||||
if (currentRequest) {
|
||||
get().play(currentRequest);
|
||||
}
|
||||
},
|
||||
|
||||
play: (request: StreamRequest) => {
|
||||
const { activeServer } = get();
|
||||
if (!activeServer) {
|
||||
set({
|
||||
error: {
|
||||
server: getAllServers()[0],
|
||||
message: 'No server selected',
|
||||
code: 'UNAVAILABLE',
|
||||
},
|
||||
isLoading: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
set({ isLoading: true, error: null, currentRequest: request, isPlayerOpen: true });
|
||||
|
||||
const result = getStreamUrl(request, activeServer);
|
||||
if (isStreamError(result)) {
|
||||
set({ error: result, isLoading: false, currentStreamUrl: null });
|
||||
} else {
|
||||
set({ currentStreamUrl: result.url, isLoading: false, error: null });
|
||||
}
|
||||
},
|
||||
|
||||
switchServer: (serverId: string) => {
|
||||
const { servers, currentRequest } = get();
|
||||
const server = servers.find((s) => s.id === serverId);
|
||||
if (!server) return;
|
||||
|
||||
setPreferredServerId(server.id);
|
||||
set({ activeServer: server, isLoading: true, error: null });
|
||||
|
||||
if (currentRequest) {
|
||||
const result = getStreamUrl(currentRequest, server);
|
||||
if (isStreamError(result)) {
|
||||
set({ error: result, isLoading: false, currentStreamUrl: null });
|
||||
} else {
|
||||
set({ currentStreamUrl: result.url, isLoading: false, error: null });
|
||||
}
|
||||
} else {
|
||||
set({ isLoading: false });
|
||||
}
|
||||
},
|
||||
|
||||
closePlayer: () => {
|
||||
set({
|
||||
isPlayerOpen: false,
|
||||
currentStreamUrl: null,
|
||||
currentRequest: null,
|
||||
error: null,
|
||||
});
|
||||
},
|
||||
|
||||
setError: (error: StreamError | null) => {
|
||||
set({ error });
|
||||
},
|
||||
|
||||
setLoading: (loading: boolean) => {
|
||||
set({ isLoading: loading });
|
||||
},
|
||||
|
||||
enableAutoMarkWatched: (threshold = 90) => {
|
||||
const config: AutoMarkWatchedConfig = { enabled: true, threshold };
|
||||
setAutoMarkWatchedConfig(config);
|
||||
markAutoMarkPromptShown();
|
||||
set({ autoMarkWatched: config, autoMarkPromptShown: true });
|
||||
},
|
||||
|
||||
disableAutoMarkWatched: () => {
|
||||
const config: AutoMarkWatchedConfig = { enabled: false, threshold: 90 };
|
||||
setAutoMarkWatchedConfig(config);
|
||||
markAutoMarkPromptShown();
|
||||
set({ autoMarkWatched: config, autoMarkPromptShown: true });
|
||||
},
|
||||
|
||||
dismissAutoMarkPrompt: () => {
|
||||
markAutoMarkPromptShown();
|
||||
set({ autoMarkPromptShown: true });
|
||||
},
|
||||
|
||||
tryNextServer: () => {
|
||||
const { activeServer, servers, currentRequest } = get();
|
||||
if (!activeServer || !currentRequest) return;
|
||||
|
||||
const currentIndex = servers.findIndex((s) => s.id === activeServer.id);
|
||||
const nextIndex = (currentIndex + 1) % servers.length;
|
||||
const nextServer = servers[nextIndex];
|
||||
|
||||
if (nextServer.id === activeServer.id) {
|
||||
// We've cycled through all servers
|
||||
set({
|
||||
error: {
|
||||
server: activeServer,
|
||||
message: 'All servers are unavailable. Please try again later.',
|
||||
code: 'UNAVAILABLE',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
get().switchServer(nextServer.id);
|
||||
},
|
||||
}));
|
||||
Reference in new issue
Block a user