Store full TMDB data, add rate limiting and stale-entry refresh

Backend
- Route all TMDB requests through a rate limiter (20 req/s, 8 concurrent)
  with 429/5xx retries; stop logging the API key
- Fetch external ids, certification, keywords, videos, watch providers and
  alternative titles in the entry details request
- Shared entry mapper used by create, refresh, season refresh and importer
- New columns on entries, ids, ratings, seasons, episodes and people, with
  an idempotent startup migration (adds missing columns, widens types)
- Fix TV IMDb ids, network country/logo, episode tmdb_id on refresh, and
  genre/network removal on refresh
- Add stale-entries maintenance job (count, start, cancel) and live
  recommendations endpoint

Frontend
- Entry page: certification, tagline, creators, in-app trailer, vote count,
  TV/movie details, network logos, external links, keywords, where to
  watch, and recommendations
- Episode page: directors, writers and guest stars
- Settings: TMDB refresh card with live progress
This commit is contained in:
X4Lo committed 2026-11-05 11:39:15 +00:00
1 parent cee6f7f961
commit a9ff2d089a
33 files changed
+1722 -483

No files matched your search

+12 -1
View File
@@ -1,6 +1,12 @@
import { api } from "@/lib/api";
import { normalizeEntry, normalizeCredit } from "@/lib/normalizers";
import type { Entry, Credit, TmdbPreview } from "@/types";
import type {
Entry,
Credit,
TmdbPreview,
TmdbEntry,
TmdbPaginatedResponse,
} from "@/types";
export const entriesApi = {
getAll: () =>
@@ -58,6 +64,11 @@ export const entriesApi = {
.get<Credit[]>(`/entries/${id}/credits`)
.then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])),
getRecommendations: (id: number) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>(`/entries/${id}/recommendations`)
.then((r) => r.data),
syncSeries: () => api.get("/entries/sync-series").then((r) => r.data),
previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
+40
View File
@@ -11,7 +11,47 @@ export interface OrphanPeopleResult {
count: number;
}
export interface StaleRefreshJob {
running: boolean;
hours?: number;
total?: number;
done?: number;
succeeded?: number;
failed?: { id: number; title: string; error: string }[];
current?: { id: number; title: string } | null;
cancelRequested?: boolean;
startedAt?: string;
finishedAt?: string | null;
}
export interface StaleEntriesResult {
count: number;
hours: number;
job: StaleRefreshJob;
}
export const maintenanceApi = {
getStaleEntries: (hours = 24) =>
api
.get<StaleEntriesResult>("/maintenance/stale-entries", {
params: { hours },
})
.then((r) => r.data),
// 409 means a job is already running; its status is returned either way
startStaleRefresh: (hours = 24) =>
api
.post<StaleRefreshJob>("/maintenance/stale-entries/refresh", null, {
params: { hours },
validateStatus: (s) => s === 202 || s === 409,
})
.then((r) => r.data),
cancelStaleRefresh: () =>
api
.delete<StaleRefreshJob>("/maintenance/stale-entries/refresh")
.then((r) => r.data),
scanOrphanFiles: () =>
api.get<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
@@ -13,6 +13,8 @@ interface CastListProps {
maxItems?: number;
/** Override link for "All Cast & Crew" — if unset, uses /entry/:entryId/cast */
allCastHref?: string;
/** Section heading (default: "Cast") */
title?: string;
}
export function CastList({
@@ -21,6 +23,7 @@ export function CastList({
isTvSeries,
maxItems,
allCastHref,
title = "Cast",
}: CastListProps) {
let castCredits = credits.filter((c) => c.cast_type === "cast");
const hasMore = maxItems != null && castCredits.length > maxItems;
@@ -36,7 +39,7 @@ export function CastList({
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Cast</h3>
<h3 className="text-lg font-semibold">{title}</h3>
{allCastLink && (
<Link
to={allCastLink}
@@ -0,0 +1,44 @@
import { useEntryRecommendations } from "@/hooks/useEntries";
import { EntryCard } from "@/components/entries/EntryCard";
import { Skeleton } from "@/components/ui/skeleton";
const GRID =
"grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6";
const MAX_ITEMS = 12;
/** "More like this": live TMDB recommendations for a library entry. */
export function RecommendationsSection({
entryId,
isTvSeries,
}: {
entryId: number;
isTvSeries: boolean;
}) {
const { data, isLoading, isError } = useEntryRecommendations(entryId);
if (isError) return null;
const results = (data?.results ?? [])
.filter((r) => r.poster_path)
.slice(0, MAX_ITEMS)
// Recommendations don't always carry media_type; it matches the entry's
.map((r) => ({
...r,
media_type: r.media_type ?? (isTvSeries ? "tv" : "movie"),
}));
if (!isLoading && results.length === 0) return null;
return (
<section className="space-y-3">
<h3 className="text-lg font-semibold">More like this</h3>
<div className={GRID}>
{isLoading
? Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 rounded-lg" />
))
: results.map((r) => <EntryCard key={r.id} tmdbEntry={r} />)}
</div>
</section>
);
}
@@ -0,0 +1,59 @@
import { useState } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import type { TmdbVideo } from "@/types";
/** Plays an entry's stored TMDB YouTube videos; trailers come first. */
export function TrailerDialog({
open,
onOpenChange,
title,
videos,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
videos: TmdbVideo[];
}) {
const [activeKey, setActiveKey] = useState(videos[0]?.key);
const active = videos.find((v) => v.key === activeKey) ?? videos[0];
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-full max-w-4xl! gap-3 p-3">
<DialogTitle className="pr-8 text-sm">
{title} · {active?.name}
</DialogTitle>
{active && (
<div className="aspect-video w-full overflow-hidden rounded-lg bg-black">
<iframe
key={active.key}
src={`https://www.youtube-nocookie.com/embed/${active.key}?autoplay=1&rel=0`}
title={active.name}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
className="h-full w-full"
/>
</div>
)}
{videos.length > 1 && (
<div className="flex gap-2 overflow-x-auto pb-1">
{videos.map((v) => (
<button
key={v.key}
type="button"
onClick={() => setActiveKey(v.key)}
className={`shrink-0 rounded-md border px-2.5 py-1 text-xs transition-colors ${
v.key === active?.key
? "border-foreground/30 bg-accent font-medium"
: "border-border/60 text-muted-foreground hover:text-foreground"
}`}
>
{v.type}: {v.name}
</button>
))}
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,121 @@
import { useState } from "react";
import { ExternalLink } from "lucide-react";
import { getTmdbImageUrl } from "@/lib/api";
import type { WatchProvider, WatchProviderRegion } from "@/types";
const CATEGORIES: { key: keyof WatchProviderRegion; label: string }[] = [
{ key: "flatrate", label: "Stream" },
{ key: "free", label: "Free" },
{ key: "ads", label: "With ads" },
{ key: "rent", label: "Rent" },
{ key: "buy", label: "Buy" },
];
/** Country from the browser locale (en-US → US), falling back to US. */
function defaultRegion(available: string[]): string {
const fromLocale = navigator.language?.split("-")[1]?.toUpperCase();
if (fromLocale && available.includes(fromLocale)) return fromLocale;
if (available.includes("US")) return "US";
return available[0];
}
const regionName = (() => {
try {
const names = new Intl.DisplayNames(["en"], { type: "region" });
return (code: string) => names.of(code) ?? code;
} catch {
return (code: string) => code;
}
})();
export function WatchProvidersCard({
providers,
}: {
providers: Record<string, WatchProviderRegion> | null | undefined;
}) {
const regions = Object.keys(providers ?? {}).sort((a, b) =>
regionName(a).localeCompare(regionName(b)),
);
const [region, setRegion] = useState(() =>
regions.length ? defaultRegion(regions) : "",
);
if (!providers || regions.length === 0) return null;
const info = providers[region] ?? providers[regions[0]];
const groups = CATEGORIES.map((c) => ({
...c,
list: (info[c.key] as WatchProvider[] | null | undefined) ?? [],
})).filter((g) => g.list.length > 0);
return (
<div className="rounded-xl border border-border/60 bg-card/50 p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Where to watch
</h3>
<select
value={region}
onChange={(e) => setRegion(e.target.value)}
className="max-w-36 rounded-md border border-border/60 bg-background px-1.5 py-0.5 text-xs"
aria-label="Country"
>
{regions.map((r) => (
<option key={r} value={r}>
{regionName(r)}
</option>
))}
</select>
</div>
{groups.length === 0 ? (
<p className="text-sm text-muted-foreground">
Not available in {regionName(region)}.
</p>
) : (
<div className="space-y-3">
{groups.map((g) => (
<div key={g.key} className="space-y-1.5">
<p className="text-[11px] font-medium text-muted-foreground">
{g.label}
</p>
<div className="flex flex-wrap gap-1.5">
{g.list
.slice()
.sort(
(a, b) =>
(a.display_priority ?? 99) - (b.display_priority ?? 99),
)
.map((p) => (
<img
key={p.provider_id}
src={
p.logo_path
? getTmdbImageUrl(p.logo_path, "w92")
: undefined
}
alt={p.provider_name}
title={p.provider_name}
className="h-9 w-9 rounded-lg object-cover ring-1 ring-border/60"
/>
))}
</div>
</div>
))}
</div>
)}
{info.link && (
<a
href={info.link}
target="_blank"
rel="noopener noreferrer"
className="mt-3 inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
Data from JustWatch via TMDB
</a>
)}
</div>
);
}
+10
View File
@@ -9,6 +9,7 @@ export const entryKeys = {
detail: (id: number) => ["entries", id] as const,
seasons: (id: number) => ["entries", id, "seasons"] as const,
credits: (id: number) => ["entries", id, "credits"] as const,
recommendations: (id: number) => ["entries", id, "recommendations"] as const,
tmdbPreview: (tmdbId: number, type: string) =>
["entries", "tmdb-preview", type, tmdbId] as const,
};
@@ -43,6 +44,15 @@ export function useEntrySeasons(id: number) {
});
}
export function useEntryRecommendations(id: number) {
return useQuery({
queryKey: entryKeys.recommendations(id),
queryFn: () => entriesApi.getRecommendations(id),
enabled: !!id,
staleTime: 30 * 60 * 1000,
});
}
export function useEntryCredits(id: number) {
return useQuery({
queryKey: entryKeys.credits(id),
+22 -1
View File
@@ -10,7 +10,15 @@
* - Genres come as string arrays from the backend mapper
*/
import type { Entry, Collection, Media, Credit, Genre, DiscoveryVideo } from "@/types";
import type {
Entry,
Collection,
Media,
Credit,
Genre,
Network,
DiscoveryVideo,
} from "@/types";
/* ---------- Media ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -46,6 +54,18 @@ export function normalizeCredit(raw: any): Credit {
};
}
/* ---------- Network ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeNetwork(raw: any): Network {
return {
id: raw.id,
name: raw.name,
origin_country: raw.originCountry ?? raw.origin_country ?? null,
homepage: raw.homepage ?? null,
logo_path: raw.logoPath ?? raw.logo_path ?? null,
};
}
/* ---------- Genre ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeGenres(raw: any[]): Genre[] {
@@ -82,6 +102,7 @@ export function normalizeEntry(raw: any): Entry {
collections: raw.collections
? raw.collections.map(normalizeCollection)
: undefined,
networks: raw.networks ? raw.networks.map(normalizeNetwork) : undefined,
// Mark as in library when loaded from the library endpoint
isInLibrary: raw.isInLibrary ?? true,
};
+226 -12
View File
@@ -38,6 +38,12 @@ import {
Tv,
Clock,
CalendarDays,
Globe,
Languages,
Building2,
DollarSign,
ListVideo,
CircleDot,
} from "lucide-react";
import {
Tooltip,
@@ -47,6 +53,9 @@ import {
import { CastList } from "@/components/entries/CastList";
import { SeasonsContainer } from "@/components/entries/SeasonsContainer";
import { StreamingSection } from "@/components/streaming/StreamingSection";
import { WatchProvidersCard } from "@/components/entries/WatchProvidersCard";
import { TrailerDialog } from "@/components/entries/TrailerDialog";
import { RecommendationsSection } from "@/components/entries/RecommendationsSection";
import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog";
import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog";
import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog";
@@ -61,6 +70,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
import { getTmdbImageUrl } from "@/lib/api";
import {
getPosterUrl,
getFullPosterUrl,
@@ -108,6 +118,26 @@ function getWatchStatusInfo(value: string | null | undefined) {
return WATCH_STATUSES.find((s) => s.value === value);
}
const formatMoney = (value: number) =>
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
notation: "compact",
maximumFractionDigits: 1,
}).format(value);
const formatCount = (value: number) =>
new Intl.NumberFormat("en-US", { notation: "compact" }).format(value);
const languageName = (() => {
try {
const names = new Intl.DisplayNames(["en"], { type: "language" });
return (code: string) => names.of(code) ?? code;
} catch {
return (code: string) => code;
}
})();
export function EntryDetailsPage() {
const { id } = useParams<{ id: string }>();
const entryId = parseInt(id!, 10);
@@ -137,6 +167,7 @@ export function EntryDetailsPage() {
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [showStatusDialog, setShowStatusDialog] = useState(false);
const [showPosterDialog, setShowPosterDialog] = useState(false);
const [showTrailer, setShowTrailer] = useState(false);
const [editSeenRecord, setEditSeenRecord] = useState<EntrySeen | null>(null);
// Track recently viewed for command palette
@@ -171,6 +202,27 @@ export function EntryDetailsPage() {
? getWatchStatusInfo(e.watch_status)
: undefined;
const userRating = e.entryRatings?.user_rating ?? 0;
const videos = e.tmdb_videos ?? [];
const nextEpisode = e.is_tvseries ? e.next_episode_to_air : null;
const socialLinks = [
e.homepage && { label: "Website", href: e.homepage },
e.entryIds?.wikidata_id && {
label: "Wikidata",
href: `https://www.wikidata.org/wiki/${e.entryIds.wikidata_id}`,
},
e.entryIds?.instagram_id && {
label: "Instagram",
href: `https://www.instagram.com/${e.entryIds.instagram_id}`,
},
e.entryIds?.twitter_id && {
label: "X",
href: `https://x.com/${e.entryIds.twitter_id}`,
},
e.entryIds?.facebook_id && {
label: "Facebook",
href: `https://www.facebook.com/${e.entryIds.facebook_id}`,
},
].filter(Boolean) as { label: string; href: string }[];
const lastSeen =
watchHistory
.map((wh) => wh.date_seen)
@@ -227,6 +279,11 @@ export function EntryDetailsPage() {
)}
{e.is_tvseries ? "TV Series" : "Movie"}
</span>
{e.certification && (
<span className="rounded border border-foreground/30 px-1.5 py-px text-xs font-semibold tracking-wide text-foreground/90">
{e.certification}
</span>
)}
{e.is_tvseries && e.status && (
<span className="rounded-full border border-border/60 bg-background/60 px-2.5 py-0.5 text-xs font-medium text-muted-foreground backdrop-blur">
{e.status}
@@ -251,6 +308,11 @@ export function EntryDetailsPage() {
<h1 className="select-text text-4xl font-extrabold leading-[1.05] tracking-tight text-balance sm:text-5xl">
{e.title}
</h1>
{e.tagline && (
<p className="select-text text-base italic text-foreground/70">
{e.tagline}
</p>
)}
{e.original_title && e.original_title !== e.title && (
<p className="select-text text-sm text-muted-foreground italic">
{e.original_title}
@@ -283,6 +345,22 @@ export function EntryDetailsPage() {
{seasons.length === 1 ? "season" : "seasons"}
</MetaItem>
)}
{e.is_tvseries && e.created_by && e.created_by.length > 0 && (
<MetaItem>
Created by{" "}
{e.created_by.map((c, i) => (
<span key={c.id}>
{i > 0 && ", "}
<Link
to={`/people/tmdb/${c.id}`}
className="font-medium text-foreground hover:underline"
>
{c.name}
</Link>
</span>
))}
</MetaItem>
)}
{director?.people?.name && (
<MetaItem>
Directed by{" "}
@@ -314,15 +392,26 @@ export function EntryDetailsPage() {
{/* Actions */}
<div className="flex flex-wrap items-center justify-center gap-2 pt-1 sm:justify-start">
<StreamingSection entry={e} seasons={seasons} />
<a
href={`https://www.youtube.com/results?search_query=${encodeURIComponent(e.title + " official trailer")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-11 items-center gap-2 rounded-md border border-border/60 bg-background/60 px-5 text-sm font-medium backdrop-blur transition-colors hover:bg-accent"
>
<Play className="h-4 w-4" />
Trailer
</a>
{videos.length > 0 ? (
<button
type="button"
onClick={() => setShowTrailer(true)}
className="inline-flex h-11 items-center gap-2 rounded-md border border-border/60 bg-background/60 px-5 text-sm font-medium backdrop-blur transition-colors hover:bg-accent"
>
<Play className="h-4 w-4" />
Trailer
</button>
) : (
<a
href={`https://www.youtube.com/results?search_query=${encodeURIComponent(e.title + " official trailer")}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex h-11 items-center gap-2 rounded-md border border-border/60 bg-background/60 px-5 text-sm font-medium backdrop-blur transition-colors hover:bg-accent"
>
<Play className="h-4 w-4" />
Trailer
</a>
)}
<div className="flex items-center gap-1.5">
<IconAction
@@ -449,6 +538,21 @@ export function EntryDetailsPage() {
</Section>
)}
{e.keywords && e.keywords.length > 0 && (
<Section title="Keywords">
<div className="flex flex-wrap gap-1.5">
{e.keywords.map((k) => (
<span
key={k}
className="rounded-md bg-muted px-2 py-0.5 text-xs text-muted-foreground"
>
{k}
</span>
))}
</div>
</Section>
)}
{credits.length > 0 && (
<CastList
credits={credits}
@@ -463,6 +567,8 @@ export function EntryDetailsPage() {
)}
<EntryCollectionsSection entryId={e.id} />
<RecommendationsSection entryId={e.id} isTvSeries={e.is_tvseries} />
</div>
{/* ── Sidebar ── */}
@@ -485,6 +591,11 @@ export function EntryDetailsPage() {
: null
}
accent="text-sky-500"
sub={
e.entryRatings?.tmdb_vote_count
? `${formatCount(e.entryRatings.tmdb_vote_count)} votes`
: undefined
}
/>
<RatingTile
label="You"
@@ -510,9 +621,80 @@ export function EntryDetailsPage() {
{formatRuntime(e.runtime)}
</DetailRow>
)}
{e.is_tvseries &&
(e.number_of_seasons || e.number_of_episodes) && (
<DetailRow icon={<ListVideo />} label="Episodes">
{[
e.number_of_seasons &&
`${e.number_of_seasons} ${e.number_of_seasons === 1 ? "season" : "seasons"}`,
e.number_of_episodes && `${e.number_of_episodes} eps`,
]
.filter(Boolean)
.join(" · ")}
</DetailRow>
)}
{e.is_tvseries && e.last_air_date && (
<DetailRow icon={<CalendarDays />} label="Last aired">
{formatDate(e.last_air_date)}
</DetailRow>
)}
{nextEpisode && (
<DetailRow icon={<CircleDot />} label="Next episode">
<span className="block">
S{nextEpisode.season_number}E{nextEpisode.episode_number}
{nextEpisode.air_date &&
` · ${formatDate(nextEpisode.air_date)}`}
</span>
<span className="block text-xs font-normal text-muted-foreground">
{nextEpisode.name}
</span>
</DetailRow>
)}
{e.is_tvseries && e.networks && e.networks.length > 0 && (
<DetailRow icon={<Tv />} label="Network">
{e.networks.map((n) => n.name).join(", ")}
<span className="inline-flex flex-wrap justify-end gap-2">
{e.networks.map((n) =>
n.logo_path ? (
<img
key={n.id}
src={getTmdbImageUrl(n.logo_path, "w92")}
alt={n.name}
title={n.name}
className="h-4 max-w-20 object-contain dark:invert dark:brightness-200"
/>
) : (
<span key={n.id}>{n.name}</span>
),
)}
</span>
</DetailRow>
)}
{e.tv_type && (
<DetailRow icon={<Film />} label="Type">
{e.tv_type}
</DetailRow>
)}
{e.original_language && (
<DetailRow icon={<Languages />} label="Language">
{languageName(e.original_language)}
</DetailRow>
)}
{!e.is_tvseries && e.budget ? (
<DetailRow icon={<DollarSign />} label="Budget">
{formatMoney(e.budget)}
</DetailRow>
) : null}
{!e.is_tvseries && e.revenue ? (
<DetailRow icon={<DollarSign />} label="Box office">
{formatMoney(e.revenue)}
</DetailRow>
) : null}
{e.production_companies && e.production_companies.length > 0 && (
<DetailRow icon={<Building2 />} label="Studio">
{e.production_companies
.slice(0, 3)
.map((c) => c.name)
.join(", ")}
</DetailRow>
)}
{e.country && (
@@ -545,8 +727,10 @@ export function EntryDetailsPage() {
)}
</dl>
{(e.entryIds?.tmdb_id || e.entryIds?.imdb_id) && (
<div className="mt-4 flex gap-2 border-t border-border/60 pt-4">
{(e.entryIds?.tmdb_id ||
e.entryIds?.imdb_id ||
socialLinks.length > 0) && (
<div className="mt-4 flex flex-wrap gap-2 border-t border-border/60 pt-4">
{e.entryIds?.tmdb_id && (
<ExternalChip
href={`https://www.themoviedb.org/${e.is_tvseries ? "tv" : "movie"}/${e.entryIds.tmdb_id}`}
@@ -561,9 +745,23 @@ export function EntryDetailsPage() {
IMDb
</ExternalChip>
)}
{socialLinks.map((l) => (
<ExternalChip key={l.label} href={l.href}>
{l.label === "Website" ? (
<span className="inline-flex items-center gap-1">
<Globe className="h-3 w-3" />
Website
</span>
) : (
l.label
)}
</ExternalChip>
))}
</div>
)}
</div>
<WatchProvidersCard providers={e.watch_providers} />
</aside>
</div>
@@ -649,6 +847,15 @@ export function EntryDetailsPage() {
}}
/>
{showTrailer && videos.length > 0 && (
<TrailerDialog
open={showTrailer}
onOpenChange={setShowTrailer}
title={e.title}
videos={videos}
/>
)}
<Dialog open={showPosterDialog} onOpenChange={setShowPosterDialog}>
<DialogContent className="w-auto max-w-[calc(100%-2rem)] sm:max-w-[calc(100%-2rem)] p-0 bg-transparent ring-0 overflow-hidden">
<DialogTitle className="sr-only">{e.title} poster</DialogTitle>
@@ -751,12 +958,14 @@ function RatingTile({
value,
accent,
emptyLabel = "—",
sub,
onClick,
}: {
label: string;
value: string | null;
accent: string;
emptyLabel?: string;
sub?: string;
onClick?: () => void;
}) {
const content = (
@@ -776,6 +985,11 @@ function RatingTile({
{emptyLabel}
</span>
)}
{sub && (
<span className="text-[10px] text-muted-foreground tabular-nums">
{sub}
</span>
)}
</>
);
const className =
+59 -5
View File
@@ -26,7 +26,26 @@ import {
PlayCircle,
} from "lucide-react";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils";
import type { Episode, EpisodeSeen } from "@/types";
import type { Credit, Episode, EpisodePerson, EpisodeSeen } from "@/types";
/** Stored guest star → the Credit shape CastList renders (links via TMDB id). */
function toGuestCredit(guest: EpisodePerson): Credit {
return {
id: guest.id,
entry_id: 0,
people_id: guest.id,
character: guest.character ?? null,
cast_type: "cast",
department: null,
job: null,
order: guest.order ?? null,
people: {
tmdb_id: guest.id,
name: guest.name,
profile_path: guest.profile_path,
} as Credit["people"],
};
}
export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{
@@ -170,13 +189,49 @@ export function EpisodePage() {
{episode.overview}
</p>
)}
{episode.crew && episode.crew.length > 0 && (
<div className="space-y-1 text-sm">
{(["Director", "Writer"] as const).map((job) => {
const people = episode.crew!.filter(
(c, i, all) =>
(job === "Writer"
? c.department === "Writing"
: c.job === "Director") &&
all.findIndex(
(o) => o.id === c.id && o.department === c.department,
) === i,
);
if (people.length === 0) return null;
return (
<p key={job} className="text-muted-foreground">
{job === "Director" ? "Directed by" : "Written by"}{" "}
{people.map((p, i) => (
<span key={p.id}>
{i > 0 && ", "}
<Link
to={`/people/tmdb/${p.id}`}
className="font-medium text-foreground hover:underline"
>
{p.name}
</Link>
</span>
))}
</p>
);
})}
</div>
)}
</div>
{/* Guest Stars */}
{/* Guest Stars (stored from TMDB; link to their TMDB person page) */}
{episode.guest_stars && episode.guest_stars.length > 0 && (
<>
<Separator />
<CastList credits={episode.guest_stars} />
<CastList
title="Guest Stars"
credits={episode.guest_stars.map(toGuestCredit)}
/>
</>
)}
@@ -188,8 +243,7 @@ export function EpisodePage() {
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as
| EpisodeSeen
| undefined;
EpisodeSeen | undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
+133 -1
View File
@@ -17,7 +17,8 @@ import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Save, Search, Trash2, Loader2 } from "lucide-react";
import { Progress } from "@/components/ui/progress";
import { Save, Search, Trash2, Loader2, RefreshCw } from "lucide-react";
import type { Settings } from "@/types";
const settingsSchema = z.object({
@@ -162,6 +163,125 @@ function DuplicateCreditsSection() {
);
}
function StaleRefreshSection() {
const [hours, setHours] = useState(24);
const queryClient = useQueryClient();
const status = useQuery({
queryKey: ["maintenance", "stale-entries", hours],
queryFn: () => maintenanceApi.getStaleEntries(hours),
// Poll while a job is running so progress updates live
refetchInterval: (query) => (query.state.data?.job.running ? 2000 : false),
});
const start = useMutation({
mutationFn: () => maintenanceApi.startStaleRefresh(hours),
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: ["maintenance", "stale-entries"],
}),
});
const cancel = useMutation({
mutationFn: maintenanceApi.cancelStaleRefresh,
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: ["maintenance", "stale-entries"],
}),
});
const job = status.data?.job;
const running = !!job?.running;
const progress = job?.total
? Math.round(((job.done ?? 0) / job.total) * 100)
: 0;
return (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
Re-fetches details, seasons, episodes and credits from TMDB for entries
not refreshed recently. Requests are rate limited, so a large library
takes a while. Entries with auto sync off are skipped.
</p>
<div className="flex flex-wrap items-center gap-2">
<Label htmlFor="stale-hours" className="text-xs">
Older than
</Label>
<Input
id="stale-hours"
type="number"
min={0}
value={hours}
onChange={(e) => setHours(Math.max(0, Number(e.target.value) || 0))}
className="h-8 w-20"
disabled={running}
/>
<span className="text-xs text-muted-foreground">hours</span>
<span className="text-xs text-muted-foreground">
·{" "}
{status.isLoading
? "counting…"
: `${status.data?.count ?? 0} entries due`}
</span>
</div>
<div className="flex items-center gap-2">
{running ? (
<Button
variant="outline"
size="sm"
onClick={() => cancel.mutate()}
disabled={cancel.isPending || job?.cancelRequested}
>
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
{job?.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
<Button
variant="outline"
size="sm"
onClick={() => start.mutate()}
disabled={start.isPending || !status.data?.count}
>
{start.isPending ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="mr-1.5 h-3.5 w-3.5" />
)}
Refresh stale entries
</Button>
)}
</div>
{job && job.total != null && (
<div className="space-y-1.5">
<Progress value={progress} className="h-1.5" />
<p className="text-xs text-muted-foreground">
{running
? "Refreshing"
: job.cancelRequested
? "Cancelled"
: "Finished"}
: {job.done}/{job.total} · {job.succeeded} ok
{job.failed &&
job.failed.length > 0 &&
` · ${job.failed.length} failed`}
{running && job.current && ` · ${job.current.title}`}
</p>
{!running && job.failed && job.failed.length > 0 && (
<ul className="max-h-28 overflow-y-auto text-xs text-destructive">
{job.failed.map((f) => (
<li key={f.id}>
{f.title}: {f.error}
</li>
))}
</ul>
)}
</div>
)}
</div>
);
}
function WatchStatusesSection() {
const [fixResult, setFixResult] = useState<{
completed: number;
@@ -419,6 +539,18 @@ export function SettingsPage() {
<TabsContent value="maintenance" className="mt-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>TMDB Refresh</CardTitle>
<CardDescription>
Keep library data in sync with The Movie Database.
</CardDescription>
</CardHeader>
<CardContent>
<StaleRefreshSection />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Media Cleanup</CardTitle>
+103 -2
View File
@@ -2,17 +2,88 @@
export interface EntryIds {
tmdb_id: number | null;
imdb_id: string | null;
tvdb_id: number | null;
tvdb_id: number | string | null;
wikidata_id?: string | null;
facebook_id?: string | null;
instagram_id?: string | null;
twitter_id?: string | null;
}
export interface EntryRatings {
id?: number;
user_rating: number | null;
tmdb_rating: number | null;
tmdb_vote_count?: number | null;
imdb_rating: number | null;
rotten_tomatoes_rating: number | null;
}
/* ---------- TMDB detail blocks stored on Entry ---------- */
export interface TmdbVideo {
key: string;
name: string;
type: string;
official: boolean;
published_at: string | null;
iso_639_1: string | null;
}
export interface WatchProvider {
provider_id: number;
provider_name: string;
logo_path: string | null;
display_priority: number | null;
}
export interface WatchProviderRegion {
link: string | null;
flatrate?: WatchProvider[] | null;
free?: WatchProvider[] | null;
ads?: WatchProvider[] | null;
rent?: WatchProvider[] | null;
buy?: WatchProvider[] | null;
}
export interface ProductionCompany {
id: number;
name: string;
logo_path: string | null;
origin_country: string | null;
}
export interface SpokenLanguage {
iso_639_1: string;
english_name: string;
name: string;
}
export interface TvCreator {
id: number;
name: string;
profile_path: string | null;
}
export interface EpisodeSummary {
id: number;
name: string;
season_number: number;
episode_number: number;
air_date: string | null;
episode_type: string | null;
runtime: number | null;
still_path: string | null;
}
export interface EpisodePerson {
id: number;
name: string;
profile_path: string | null;
character?: string | null;
order?: number | null;
job?: string | null;
department?: string | null;
}
export interface Media {
id: number;
mediaable: "entry" | "people" | "collection" | "season" | "episode";
@@ -60,6 +131,33 @@ export interface Entry {
entrySeens?: EntrySeen[];
episodeSeens?: EpisodeSeen[];
networks?: Network[];
// TMDB details (detail endpoint only for the JSON blocks)
certification?: string | null;
network_studio?: string | null;
adult?: boolean;
tmdb_popularity?: number | null;
original_language?: string | null;
origin_country?: string[] | null;
spoken_languages?: SpokenLanguage[] | null;
production_countries?: { iso_3166_1: string; name: string }[] | null;
production_companies?: ProductionCompany[] | null;
homepage?: string | null;
budget?: number | null;
revenue?: number | null;
tagline?: string | null;
keywords?: string[] | null;
tmdb_videos?: TmdbVideo[] | null;
watch_providers?: Record<string, WatchProviderRegion> | null;
alternative_titles?: { iso_3166_1: string; title: string; type: string }[] | null;
tv_type?: string | null;
created_by?: TvCreator[] | null;
number_of_seasons?: number | null;
number_of_episodes?: number | null;
last_air_date?: string | null;
in_production?: boolean | null;
next_episode_to_air?: EpisodeSummary | null;
last_episode_to_air?: EpisodeSummary | null;
last_fetch?: string | null;
// Computed for library
isInLibrary?: boolean;
isInWatchlist?: boolean;
@@ -93,6 +191,9 @@ export interface Episode {
air_date: string | null;
user_rating: number | null;
tmdb_rating: number | null;
tmdb_vote_count?: number | null;
production_code?: string | null;
crew?: EpisodePerson[] | null;
still_path: string | null;
overview: string | null;
date_first_seen: string | null;
@@ -100,7 +201,7 @@ export interface Episode {
createdAt: string;
updatedAt: string;
episodeSeens?: EpisodeSeen[];
guest_stars?: Credit[];
guest_stars?: EpisodePerson[] | null;
entry?: Entry;
season?: Season;
}