diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js index fe05fb0..1eb9cda 100644 --- a/backend/controllers/entryController.js +++ b/backend/controllers/entryController.js @@ -3,6 +3,12 @@ const collectionManager = require("../services/collectionManager"); const entryManager = require("../services/entryManager"); const entryService = require("../services/entryService"); const tmdbService = require("../services/tmdbService"); +const artworkService = require("../services/artworkService"); +const { + mapEntryFields, + mapEntryIds, + mapEntryRatings, +} = require("../mappers/entryMapper"); const asyncWrapper = require("../utils/asyncWrapper"); const _collectionManager = collectionManager; @@ -145,6 +151,40 @@ class EntryController { res.status(200).json(data); }); + // * GET - TMDB RECOMMENDATIONS BY TMDB ID (entries not in the library) + getTmdbRecommendations = asyncWrapper(async (req, res) => { + const { type, tmdbId } = req.params; + const data = await tmdbService.fetchEntryRecommendations( + tmdbId, + type === "tv", + req.query.page || 1, + ); + if (!data) + return res + .status(500) + .json({ message: "Failed to fetch recommendations" }); + res.status(200).json(data); + }); + + // * GET - ARTWORK: TMDB images merged with the entry's media table + getEntryArtwork = asyncWrapper(async (req, res) => { + const artwork = await artworkService.getEntryArtwork(req.params.id); + res.status(200).json(artwork); + }); + + // * POST - ARTWORK: download a TMDB image into the entry's media table + addEntryArtwork = asyncWrapper(async (req, res) => { + const media = await artworkService.addEntryArtwork(req.params.id, req.body); + res.status(201).json(media); + }); + + // * GET - ARTWORK BY TMDB ID (entries not in the library) + getTmdbArtwork = asyncWrapper(async (req, res) => { + const { type, tmdbId } = req.params; + const artwork = await artworkService.getTmdbArtwork(type, tmdbId); + res.status(200).json(artwork); + }); + // * PUT - REQUEST COLLECTION REFRECH fetchEntryCollection = asyncWrapper(async (req, res, next) => { const { id } = req.params; @@ -242,6 +282,59 @@ class EntryController { } } + // Directors, so the preview page can show "Directed by" + for (const c of creditsData?.crew ?? []) { + const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job]; + if (!jobs.includes("Director")) continue; + credits.push({ + id: c.credit_id || c.jobs?.[0]?.credit_id || "crew-" + c.id, + cast_type: "crew", + job: "Director", + department: "Directing", + character: null, + people_id: c.id, + people: { + id: c.id, + name: c.name || c.original_name, + profile_path: c.profile_path, + tmdb_id: c.id, + }, + }); + } + + // Same shape as a library entry, so the details page can render either + const entry = { + id: 0, + ...mapEntryFields(data), + is_tvseries: is_tvserie, + isInLibrary: false, + entryIds: { tmdb_id: data.id, ...mapEntryIds(data) }, + entryRatings: { + user_rating: null, + imdb_rating: null, + rotten_tomatoes_rating: null, + ...mapEntryRatings(data), + }, + genres: data.genres || [], + networks: (data.networks || []).map((n) => ({ + id: n.id, + name: n.name, + origin_country: n.origin_country || null, + logo_path: n.logo_path || null, + homepage: null, + })), + }; + const seasons = (data.seasons || []).map((s) => ({ + id: s.id, + name: s.name, + season_number: s.season_number, + episode_count: s.episode_count, + air_date: s.air_date, + poster_path: s.poster_path, + overview: s.overview, + tmdb_rating: s.vote_average, + })); + // Normalize to a shape similar to our Entry model const preview = { tmdb_id: data.id, @@ -267,6 +360,8 @@ class EntryController { homepage: data.homepage || null, imdb_id: data.imdb_id || data.external_ids?.imdb_id || null, credits, + entry, + seasons, }; res.status(200).json(preview); diff --git a/backend/models/Media.js b/backend/models/Media.js index 64cf641..3310548 100644 --- a/backend/models/Media.js +++ b/backend/models/Media.js @@ -9,6 +9,8 @@ const Media = sequelize.define("media", { type: { type: DataTypes.STRING(50) }, path: { type: DataTypes.STRING(200) }, + // TMDB file_path this image was downloaded from (null for custom uploads) + tmdbPath: { type: DataTypes.STRING(200), field: "tmdb_path" }, isLocal: { type: DataTypes.BOOLEAN, field: "is_local" }, isSelected: { diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index f9e6b5e..dd17494 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -18,6 +18,11 @@ entryRouter.get("/tmdb/top-rated/:type", entryController.getTmdbTopRated); entryRouter.get("/tmdb/upcoming/movie", entryController.getTmdbUpcoming); entryRouter.get("/tmdb/search", entryController.getTmdbSearch); entryRouter.get("/tmdb/preview/:type/:tmdbId", entryController.getTmdbPreview); +entryRouter.get( + "/tmdb/recommendations/:type/:tmdbId", + entryController.getTmdbRecommendations, +); +entryRouter.get("/tmdb/artwork/:type/:tmdbId", entryController.getTmdbArtwork); entryRouter.get("/sync-series", entryController.syncSeries); @@ -35,6 +40,8 @@ entryRouter.get( "/:id/recommendations", entryController.getEntryRecommendations, ); +entryRouter.get("/:id/artwork", entryController.getEntryArtwork); +entryRouter.post("/:id/artwork", entryController.addEntryArtwork); entryRouter.put("/:id/refresh", entryController.refrechEntry); entryRouter.put("/:id/fetch-collection", entryController.fetchEntryCollection); diff --git a/backend/services/artworkService.js b/backend/services/artworkService.js new file mode 100644 index 0000000..6a1d1e2 --- /dev/null +++ b/backend/services/artworkService.js @@ -0,0 +1,207 @@ +const path = require("path"); +const { v4: uuidv4 } = require("uuid"); + +const Entry = require("../models/Entry"); +const EntryId = require("../models/EntryId"); +const Media = require("../models/Media"); + +const BadRequestError = require("../errors/BadRequestError"); +const NotFoundError = require("../errors/NotFoundError"); +const InternalServerError = require("../errors/InternalServerError"); + +const configService = require("./configService"); +const tmdbService = require("./tmdbService"); +const mediaDownloaderService = require("./mediaDownloaderService"); +const mediaOptimizerService = require("./mediaOptimizerService"); +const { logToFile } = require("./logService"); + +// TMDB images response key → our Media.type +const ARTWORK_TYPES = { + posters: "poster", + backdrops: "backdrop", + logos: "logo", +}; +const MEDIA_TYPES = Object.values(ARTWORK_TYPES); + +function mapTmdbImage(image) { + return { + file_path: image.file_path, + width: image.width, + height: image.height, + aspect_ratio: image.aspect_ratio, + language: image.iso_639_1 || null, + vote_average: image.vote_average ?? 0, + vote_count: image.vote_count ?? 0, + }; +} + +function sortByVotes(a, b) { + return b.vote_count - a.vote_count || b.vote_average - a.vote_average; +} + +/** TMDB artwork grouped by type, best-voted first. */ +async function fetchTmdbArtwork(tmdbId, isTv) { + const data = await tmdbService.fetchEntryMedia(tmdbId, isTv); + if (!data) { + throw new InternalServerError("Couldn't fetch artwork from TMDB"); + } + + const result = {}; + for (const [tmdbKey, type] of Object.entries(ARTWORK_TYPES)) { + result[`${type}s`] = (data[tmdbKey] ?? []) + .map(mapTmdbImage) + .sort(sortByVotes); + } + return result; +} + +class ArtworkService { + constructor() { + if (!ArtworkService.instance) { + ArtworkService.instance = this; + } + return ArtworkService.instance; + } + + /** Artwork for an entry that is not in the library (TMDB only). */ + async getTmdbArtwork(type, tmdbId) { + const result = await fetchTmdbArtwork(tmdbId, type === "tv"); + for (const key of Object.keys(result)) { + result[key] = result[key].map((img) => ({ ...img, in_library: false })); + } + return result; + } + + /** + * TMDB artwork merged with the entry's media table. TMDB images we already + * have are flagged `in_library` with their media id; local images that + * don't match a TMDB image (custom uploads, older downloads) are appended. + */ + async getEntryArtwork(entryId) { + const entry = await Entry.findByPk(entryId, { + attributes: ["id", "is_tvseries"], + include: [{ model: EntryId, as: "entryId" }], + }); + if (!entry) throw new NotFoundError("Entry not found"); + + const medias = await Media.findAll({ + where: { mediaable: "entry", mediaableId: entryId, type: MEDIA_TYPES }, + order: [["id", "ASC"]], + }); + + const tmdbId = entry.entryId?.tmdb_id; + const tmdb = tmdbId + ? await fetchTmdbArtwork(tmdbId, entry.is_tvseries) + : { posters: [], backdrops: [], logos: [] }; + + const result = {}; + for (const type of MEDIA_TYPES) { + const key = `${type}s`; + const ofType = medias.filter((m) => m.type === type); + const byTmdbPath = new Map( + ofType.filter((m) => m.tmdbPath).map((m) => [m.tmdbPath, m]), + ); + + const merged = tmdb[key].map((img) => { + const media = byTmdbPath.get(img.file_path); + return { + ...img, + in_library: !!media, + media_id: media?.id ?? null, + media_path: media?.path ?? null, + is_selected: !!media?.isSelected, + }; + }); + + const localOnly = ofType + .filter( + (m) => + !m.tmdbPath || !tmdb[key].some((i) => i.file_path === m.tmdbPath), + ) + .map((m) => ({ + file_path: null, + width: null, + height: null, + aspect_ratio: null, + language: null, + vote_average: 0, + vote_count: 0, + in_library: true, + media_id: m.id, + media_path: m.path, + is_selected: !!m.isSelected, + is_custom: !!m.isCustom, + })); + + // Library images first so what you already have is easy to find + result[key] = [ + ...localOnly, + ...merged.filter((i) => i.in_library), + ...merged.filter((i) => !i.in_library), + ]; + } + return result; + } + + /** + * Downloads a TMDB image into the entry's media table. If the entry has no + * selected image of that type yet, the new one becomes selected. + * @param {number} entryId + * @param {{type: "poster"|"backdrop"|"logo", file_path: string}} data + */ + async addEntryArtwork(entryId, { type, file_path }) { + if (!MEDIA_TYPES.includes(type)) { + throw new BadRequestError(`Invalid artwork type: ${type}`); + } + if (!file_path || !/^\/[\w.-]+$/.test(file_path)) { + throw new BadRequestError("Invalid TMDB file path"); + } + + const entry = await Entry.findByPk(entryId, { attributes: ["id"] }); + if (!entry) throw new NotFoundError("Entry not found"); + + const where = { mediaable: "entry", mediaableId: entryId, type }; + const existing = await Media.findOne({ + where: { ...where, tmdbPath: file_path }, + }); + if (existing) return existing; + + configService.createMediaFolders(); + const extension = file_path.split(".").pop(); + const filename = `${uuidv4()}.${extension}`; + const dir = path.join( + configService.getSettings().userDataPath, + "images", + "entries", + `${type}s`, + ); + + await mediaDownloaderService.downloadImage( + `https://image.tmdb.org/t/p/original${file_path}`, + path.join(dir, filename), + ); + + const hasSelected = await Media.count({ + where: { ...where, isSelected: true }, + }); + const media = await Media.create({ + ...where, + path: filename, + tmdbPath: file_path, + isLocal: true, + isSelected: hasSelected === 0, + isCustom: false, + }); + + mediaOptimizerService + .doGeneratePreview("entries", `${type}s`, filename) + .catch((err) => + logToFile(`Artwork | Error generating preview for ${filename}: ${err}`), + ); + + logToFile(`Artwork | Added ${type} ${file_path} to entry ${entryId}`); + return media; + } +} + +module.exports = new ArtworkService(); diff --git a/backend/services/collectionManager.js b/backend/services/collectionManager.js index 84d4d0c..7958f37 100644 --- a/backend/services/collectionManager.js +++ b/backend/services/collectionManager.js @@ -98,6 +98,7 @@ class CollectionManager { mediaableId: collection.id, type: image.type, path: image.path, + tmdbPath: image.tmdb_path || null, isLocal: true, isSelected: true, }); diff --git a/backend/services/entryManager.js b/backend/services/entryManager.js index f2f2ce4..b2d4e17 100644 --- a/backend/services/entryManager.js +++ b/backend/services/entryManager.js @@ -502,6 +502,7 @@ class EntryManager { mediaableId: oldEntry.id, type: image.type, path: image.path, + tmdbPath: image.tmdb_path || null, isLocal: true, isSelected: true, }); diff --git a/backend/services/entryService.js b/backend/services/entryService.js index 37a6c48..138f688 100644 --- a/backend/services/entryService.js +++ b/backend/services/entryService.js @@ -375,6 +375,7 @@ class EntryService { mediaableId: savedEntry.id, type: image.type, path: image.path, + tmdbPath: image.tmdb_path || null, isLocal: true, isSelected: true, }); diff --git a/backend/services/mediaDownloaderService.js b/backend/services/mediaDownloaderService.js index 595bc91..f22bec3 100644 --- a/backend/services/mediaDownloaderService.js +++ b/backend/services/mediaDownloaderService.js @@ -151,7 +151,11 @@ class MediaDownloaderService { logToFile( `Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`, ); - downloadedImages.push({ type: mediaType, path: filename }); + downloadedImages.push({ + type: mediaType, + path: filename, + tmdb_path: media.file_path, + }); }) .catch((err) => { logToFile( diff --git a/backend/services/models-services/entryService.js b/backend/services/models-services/entryService.js index fcd2236..e807129 100644 --- a/backend/services/models-services/entryService.js +++ b/backend/services/models-services/entryService.js @@ -108,6 +108,7 @@ async function saveEntry(data) { mediaableId: savedEntry.id, type: image.type, path: image.path, + tmdbPath: image.tmdb_path || null, isLocal: true, isSelected: true, }); @@ -519,6 +520,7 @@ async function refrechEntry(entryId) { mediaableId: oldEntry.id, type: image.type, path: image.path, + tmdbPath: image.tmdb_path || null, isLocal: true, isSelected: true, }); diff --git a/backend/services/peopleManager.js b/backend/services/peopleManager.js index 6d8faee..4016df3 100644 --- a/backend/services/peopleManager.js +++ b/backend/services/peopleManager.js @@ -72,6 +72,7 @@ class PeopleManager { mediaableId: person.id, type: image.type, path: image.path, + tmdbPath: image.tmdb_path || null, isLocal: true, isSelected: true, }); diff --git a/react_frontend/src/api/entries.ts b/react_frontend/src/api/entries.ts index 5c45da0..4e76617 100644 --- a/react_frontend/src/api/entries.ts +++ b/react_frontend/src/api/entries.ts @@ -6,6 +6,9 @@ import type { TmdbPreview, TmdbEntry, TmdbPaginatedResponse, + ArtworkResponse, + ArtworkType, + Media, } from "@/types"; export const entriesApi = { @@ -69,6 +72,24 @@ export const entriesApi = { .get>(`/entries/${id}/recommendations`) .then((r) => r.data), + getTmdbRecommendations: (type: "movie" | "tv", tmdbId: number) => + api + .get>( + `/entries/tmdb/recommendations/${type}/${tmdbId}`, + ) + .then((r) => r.data), + + getArtwork: (id: number) => + api.get(`/entries/${id}/artwork`).then((r) => r.data), + + getTmdbArtwork: (type: "movie" | "tv", tmdbId: number) => + api + .get(`/entries/tmdb/artwork/${type}/${tmdbId}`) + .then((r) => r.data), + + addArtwork: (id: number, data: { type: ArtworkType; file_path: string }) => + api.post(`/entries/${id}/artwork`, data).then((r) => r.data), + syncSeries: () => api.get("/entries/sync-series").then((r) => r.data), previewTmdb: (tmdbId: number, type: "movie" | "tv") => diff --git a/react_frontend/src/components/entries/ArtworkSection.tsx b/react_frontend/src/components/entries/ArtworkSection.tsx new file mode 100644 index 0000000..55ea6f6 --- /dev/null +++ b/react_frontend/src/components/entries/ArtworkSection.tsx @@ -0,0 +1,445 @@ +import { useEffect, useMemo, useState } from "react"; +import { Check, Download, Loader2, Star } from "lucide-react"; +import { useAddArtwork, useArtwork } from "@/hooks/useEntries"; +import { getMediaUrl, getTmdbImageUrl } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Skeleton } from "@/components/ui/skeleton"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; +import type { ArtworkItem, ArtworkType } from "@/types"; + +// Rows shown at first and added per "Show more" +const ROWS_STEP = 2; +// Checkerboard behind logos so transparent/dark logos stay visible +const CHECKER = + "bg-[repeating-conic-gradient(#8883_0_25%,transparent_0_50%)] bg-size-[16px_16px]"; + +const TYPES: { + type: ArtworkType; + key: "posters" | "backdrops" | "logos"; + label: string; + thumbSize: string; + grid: string; + /** Columns per breakpoint; must match `grid` */ + cols: { base: number; sm?: number; md?: number; xl?: number }; + aspect: string; +}[] = [ + { + type: "poster", + key: "posters", + label: "Posters", + thumbSize: "w342", + grid: "grid-cols-3 sm:grid-cols-4 md:grid-cols-5 xl:grid-cols-6", + cols: { base: 3, sm: 4, md: 5, xl: 6 }, + aspect: "aspect-2/3", + }, + { + type: "backdrop", + key: "backdrops", + label: "Backdrops", + thumbSize: "w780", + grid: "grid-cols-1 sm:grid-cols-2 xl:grid-cols-3", + cols: { base: 1, sm: 2, xl: 3 }, + aspect: "aspect-video", + }, + { + type: "logo", + key: "logos", + label: "Logos", + thumbSize: "w500", + grid: "grid-cols-2 sm:grid-cols-3 xl:grid-cols-4", + cols: { base: 2, sm: 3, xl: 4 }, + aspect: "aspect-[2/1]", + }, +]; + +const languageName = (() => { + try { + const names = new Intl.DisplayNames(["en"], { type: "language" }); + return (code: string) => names.of(code) ?? code; + } catch { + return (code: string) => code; + } +})(); + +function imageUrls(item: ArtworkItem, type: ArtworkType, thumbSize: string) { + if (item.file_path) { + return { + thumb: getTmdbImageUrl(item.file_path, thumbSize), + full: getTmdbImageUrl(item.file_path, "original"), + }; + } + const folder = `${type}s`; + return { + thumb: getMediaUrl("entries", folder, "preview", item.media_path!), + full: getMediaUrl("entries", folder, "full", item.media_path!), + }; +} + +const BREAKPOINTS = [ + ["xl", 1280], + ["md", 768], + ["sm", 640], +] as const; + +/** Current column count for a grid, following the Tailwind breakpoints. */ +function useGridColumns(cols: { + base: number; + sm?: number; + md?: number; + xl?: number; +}) { + const compute = () => { + for (const [bp, minWidth] of BREAKPOINTS) { + const value = cols[bp]; + if (value && window.matchMedia(`(min-width: ${minWidth}px)`).matches) { + return value; + } + } + return cols.base; + }; + const [columns, setColumns] = useState(compute); + + useEffect(() => { + const update = () => setColumns(compute()); + update(); + const queries = BREAKPOINTS.map(([, w]) => + window.matchMedia(`(min-width: ${w}px)`), + ); + queries.forEach((q) => q.addEventListener("change", update)); + return () => + queries.forEach((q) => q.removeEventListener("change", update)); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [cols.base, cols.sm, cols.md, cols.xl]); + + return columns; +} + +const itemKey = (item: ArtworkItem) => + item.file_path ?? `media-${item.media_id}`; + +/** + * Posters, backdrops and logos from TMDB merged with the entry's media table. + * For library entries, TMDB images can be added (downloaded) to the library. + */ +export function ArtworkSection({ + entryId = 0, + tmdbId = 0, + isTvSeries, + originalLanguage, +}: { + entryId?: number; + tmdbId?: number; + isTvSeries: boolean; + originalLanguage?: string | null; +}) { + const isLibrary = !!entryId; + const { data, isLoading, isError } = useArtwork( + isLibrary ? { entryId } : { tmdbId, type: isTvSeries ? "tv" : "movie" }, + ); + const addArtwork = useAddArtwork(entryId); + + const [activeType, setActiveType] = useState("poster"); + const [language, setLanguage] = useState("all"); + const [libraryOnly, setLibraryOnly] = useState(false); + const [rows, setRows] = useState(ROWS_STEP); + const [pendingPath, setPendingPath] = useState(null); + const [viewing, setViewing] = useState(null); + + const config = TYPES.find((t) => t.type === activeType)!; + const columns = useGridColumns(config.cols); + const visible = columns * rows; + const items = useMemo(() => data?.[config.key] ?? [], [data, config.key]); + + // Languages present for this type, most common first ("none" = no text) + const languages = useMemo(() => { + const counts = new Map(); + for (const item of items) { + if (!item.file_path) continue; + const lang = item.language ?? "none"; + counts.set(lang, (counts.get(lang) ?? 0) + 1); + } + const preferred = ["none", "en", originalLanguage].filter(Boolean); + return [...counts.entries()].sort(([a, ca], [b, cb]) => { + const pa = preferred.indexOf(a); + const pb = preferred.indexOf(b); + if (pa !== -1 || pb !== -1) + return (pa === -1 ? 99 : pa) - (pb === -1 ? 99 : pb); + return cb - ca; + }); + }, [items, originalLanguage]); + + const filtered = items.filter((item) => { + if (libraryOnly && !item.in_library) return false; + if (language === "all" || !item.file_path) return true; + return (item.language ?? "none") === language; + }); + + const changeType = (type: ArtworkType) => { + setActiveType(type); + setLanguage("all"); + setRows(ROWS_STEP); + }; + + const add = (item: ArtworkItem) => { + if (!item.file_path) return; + setPendingPath(item.file_path); + addArtwork.mutate( + { type: activeType, file_path: item.file_path }, + { + onSuccess: () => + setViewing((v) => + v?.file_path === item.file_path ? { ...v, in_library: true } : v, + ), + onSettled: () => setPendingPath(null), + }, + ); + }; + + if (isError) return null; + + const total = data + ? data.posters.length + data.backdrops.length + data.logos.length + : 0; + if (!isLoading && total === 0) return null; + + return ( +
+
+

Artwork

+
+ + {isLibrary && ( + + )} +
+
+ + changeType(v as ArtworkType)} + > + + {TYPES.map((t) => ( + + {t.label} + {data && ( + + {data[t.key].length} + + )} + + ))} + + + + {isLoading ? ( +
+ {Array.from({ length: columns * ROWS_STEP }).map((_, i) => ( + + ))} +
+ ) : filtered.length === 0 ? ( +

+ No {config.label.toLowerCase()} match these filters. +

+ ) : ( + <> +
+ {filtered.slice(0, visible).map((item) => ( + add(item)} + onOpen={() => setViewing(item)} + /> + ))} +
+ {filtered.length > visible && ( +
+ +
+ )} + + )} + + !open && setViewing(null)} + > + + {config.label} preview + {viewing && ( + <> + +
+ + {viewing.width && viewing.height + ? `${viewing.width}×${viewing.height}` + : "Local file"} + {viewing.file_path && + ` · ${viewing.language ? languageName(viewing.language) : "No text"}`} + + {viewing.in_library ? ( + + ) : ( + isLibrary && + viewing.file_path && ( + + ) + )} +
+ + )} +
+
+
+ ); +} + +function LibraryBadge({ selected }: { selected?: boolean }) { + return ( + + + {selected ? "Selected" : "In library"} + + ); +} + +function ArtworkTile({ + item, + type, + thumbSize, + aspect, + canAdd, + adding, + onAdd, + onOpen, +}: { + item: ArtworkItem; + type: ArtworkType; + thumbSize: string; + aspect: string; + canAdd: boolean; + adding: boolean; + onAdd: () => void; + onOpen: () => void; +}) { + const { thumb } = imageUrls(item, type, thumbSize); + + return ( +
+ + + {/* Top: library badge / language */} +
+ {item.in_library ? ( + + ) : ( + + )} + {item.file_path && item.language && ( + + {item.language} + + )} +
+ + {/* Bottom: votes + add */} +
+ {item.vote_count > 0 ? ( + + + {item.vote_average.toFixed(1)} + + ) : ( + + )} + {canAdd && !item.in_library && item.file_path && ( + + )} +
+
+ ); +} diff --git a/react_frontend/src/components/entries/RecommendationsSection.tsx b/react_frontend/src/components/entries/RecommendationsSection.tsx index 483570e..6a51f00 100644 --- a/react_frontend/src/components/entries/RecommendationsSection.tsx +++ b/react_frontend/src/components/entries/RecommendationsSection.tsx @@ -1,4 +1,7 @@ -import { useEntryRecommendations } from "@/hooks/useEntries"; +import { + useEntryRecommendations, + useTmdbRecommendations, +} from "@/hooks/useEntries"; import { EntryCard } from "@/components/entries/EntryCard"; import { Skeleton } from "@/components/ui/skeleton"; @@ -6,15 +9,23 @@ 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. */ +/** + * "More like this": live TMDB recommendations. Pass `entryId` for a library + * entry, or `tmdbId` for one that is not in the library. + */ export function RecommendationsSection({ - entryId, + entryId = 0, + tmdbId = 0, isTvSeries, }: { - entryId: number; + entryId?: number; + tmdbId?: number; isTvSeries: boolean; }) { - const { data, isLoading, isError } = useEntryRecommendations(entryId); + const type = isTvSeries ? "tv" : "movie"; + const library = useEntryRecommendations(entryId); + const tmdb = useTmdbRecommendations(entryId ? 0 : tmdbId, type); + const { data, isLoading, isError } = entryId ? library : tmdb; if (isError) return null; diff --git a/react_frontend/src/hooks/useEntries.ts b/react_frontend/src/hooks/useEntries.ts index 39e03be..a8c87e4 100644 --- a/react_frontend/src/hooks/useEntries.ts +++ b/react_frontend/src/hooks/useEntries.ts @@ -2,7 +2,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { toast } from "sonner"; import { entriesApi } from "@/api/entries"; import { useLibraryStore } from "@/stores/useLibraryStore"; -import type { Entry } from "@/types"; +import type { ArtworkType, Entry } from "@/types"; export const entryKeys = { all: ["entries"] as const, @@ -10,6 +10,11 @@ export const entryKeys = { seasons: (id: number) => ["entries", id, "seasons"] as const, credits: (id: number) => ["entries", id, "credits"] as const, recommendations: (id: number) => ["entries", id, "recommendations"] as const, + artwork: (id: number) => ["entries", id, "artwork"] as const, + tmdbArtwork: (tmdbId: number, type: string) => + ["entries", "tmdb-artwork", type, tmdbId] as const, + tmdbRecommendations: (tmdbId: number, type: string) => + ["entries", "tmdb-recommendations", type, tmdbId] as const, tmdbPreview: (tmdbId: number, type: string) => ["entries", "tmdb-preview", type, tmdbId] as const, }; @@ -53,6 +58,52 @@ export function useEntryRecommendations(id: number) { }); } +export function useTmdbRecommendations( + tmdbId: number, + type: "movie" | "tv", +) { + return useQuery({ + queryKey: entryKeys.tmdbRecommendations(tmdbId, type), + queryFn: () => entriesApi.getTmdbRecommendations(type, tmdbId), + enabled: !!tmdbId, + staleTime: 30 * 60 * 1000, + }); +} + +/** Artwork for a library entry (TMDB + media table), or by TMDB id otherwise. */ +export function useArtwork( + source: { entryId: number } | { tmdbId: number; type: "movie" | "tv" }, +) { + const isLibrary = "entryId" in source; + return useQuery({ + queryKey: isLibrary + ? entryKeys.artwork(source.entryId) + : entryKeys.tmdbArtwork(source.tmdbId, source.type), + queryFn: () => + isLibrary + ? entriesApi.getArtwork(source.entryId) + : entriesApi.getTmdbArtwork(source.type, source.tmdbId), + enabled: isLibrary ? !!source.entryId : !!source.tmdbId, + staleTime: 10 * 60 * 1000, + }); +} + +export function useAddArtwork(entryId: number) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (data: { type: ArtworkType; file_path: string }) => + entriesApi.addArtwork(entryId, data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: entryKeys.artwork(entryId) }); + queryClient.invalidateQueries({ queryKey: entryKeys.detail(entryId) }); + queryClient.invalidateQueries({ queryKey: entryKeys.all, exact: true }); + }, + onError: () => { + toast.error("Failed to add artwork"); + }, + }); +} + export function useEntryCredits(id: number) { return useQuery({ queryKey: entryKeys.credits(id), diff --git a/react_frontend/src/hooks/useTmdbEntryLink.ts b/react_frontend/src/hooks/useTmdbEntryLink.ts index fe497dd..0ae511f 100644 --- a/react_frontend/src/hooks/useTmdbEntryLink.ts +++ b/react_frontend/src/hooks/useTmdbEntryLink.ts @@ -14,7 +14,7 @@ interface TmdbEntryLink { /** * Resolves the correct navigation link for a TmdbEntry. * If the entry is already in the library, links directly to EntryDetailsPage. - * Otherwise, links to the TmdbPreviewPage. + * Otherwise, links to the TMDB preview of the entry details page. */ export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink { const libraryEntries = useLibraryStore((s) => s.entries); diff --git a/react_frontend/src/pages/EntryDetailsPage.tsx b/react_frontend/src/pages/EntryDetailsPage.tsx index fd80afd..6ac1954 100644 --- a/react_frontend/src/pages/EntryDetailsPage.tsx +++ b/react_frontend/src/pages/EntryDetailsPage.tsx @@ -5,6 +5,8 @@ import { useEntrySeasons, useRefreshEntry, useEntryCredits, + useTmdbPreview, + useCreateEntry, } from "@/hooks/useEntries"; import { useEntrySeenByEntry, useDeleteEntrySeen } from "@/hooks/useEntrySeen"; import { useCollections } from "@/hooks/useCollections"; @@ -44,6 +46,8 @@ import { DollarSign, ListVideo, CircleDot, + Plus, + Loader2, } from "lucide-react"; import { Tooltip, @@ -56,6 +60,7 @@ 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 { ArtworkSection } from "@/components/entries/ArtworkSection"; import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog"; import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog"; import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog"; @@ -81,7 +86,13 @@ import { formatDate, } from "@/lib/media-utils"; import { useUpdateEntry, useDeleteEntry } from "@/hooks/useEntries"; -import type { Collection, Entry, EntrySeen } from "@/types"; +import type { + Collection, + Credit, + Entry, + EntrySeen, + TmdbPreviewSeason, +} from "@/types"; const WATCH_STATUSES = [ { @@ -138,25 +149,60 @@ const languageName = (() => { } })(); +/** + * Entry details for both sources: + * - `/entry/:id`: a library entry, loaded from the local DB. + * - `/entry/tmdb/:type/:tmdbId`: not in the library; everything comes from + * the TMDB preview (same shape), and library-only actions are hidden. If + * the title is already in the library, redirect to its page. + */ export function EntryDetailsPage() { - const { id } = useParams<{ id: string }>(); - const entryId = parseInt(id!, 10); + const { id, type, tmdbId } = useParams<{ + id?: string; + type?: string; + tmdbId?: string; + }>(); + const entryId = id ? parseInt(id, 10) : 0; + const isLibrary = !!entryId; + const previewTmdbId = !isLibrary && tmdbId ? parseInt(tmdbId, 10) : 0; + const previewType = type === "tv" ? "tv" : "movie"; const navigate = useNavigate(); + + // Library queries are disabled when entryId is 0, the preview when tmdbId is 0 const { data: entry, isLoading } = useEntry(entryId); const { data: seasons } = useEntrySeasons(entryId); const { data: allCredits = [] } = useEntryCredits(entryId); const { data: watchHistory = [] } = useEntrySeenByEntry(entryId); + const { + data: preview, + isLoading: previewLoading, + isError: previewError, + } = useTmdbPreview(previewTmdbId, previewType); const updateEntry = useUpdateEntry(); const refreshEntry = useRefreshEntry(); const deleteEntrySeen = useDeleteEntrySeen(); const deleteEntry = useDeleteEntry(); + const createEntry = useCreateEntry(); // Merge library entry with detail entry so we get both library flags AND full details (credits, etc.) const libraryEntry = useLibraryStore((s) => s.entries.get(entryId)); - const displayEntry = - libraryEntry && entry + const libraryMatch = useLibraryStore((s) => { + if (!previewTmdbId) return null; + for (const le of s.entries.values()) { + if (le.entryIds?.tmdb_id === previewTmdbId) return le; + } + return null; + }); + const displayEntry: Entry | undefined = isLibrary + ? libraryEntry && entry ? { ...libraryEntry, ...entry, isInLibrary: true } - : entry || libraryEntry; + : entry || libraryEntry + : preview?.entry; + + // Already in the library: show the library page instead of the preview + useEffect(() => { + if (libraryMatch) navigate(`/entry/${libraryMatch.id}`, { replace: true }); + }, [libraryMatch, navigate]); const [showSettings, setShowSettings] = useState(false); const [showSeenDialog, setShowSeenDialog] = useState(false); @@ -175,24 +221,59 @@ export function EntryDetailsPage() { useEffect(() => { if (displayEntry) { addRecentlyViewed({ - id: `lib-${entryId}`, + id: isLibrary ? `lib-${entryId}` : `tmdb-${previewTmdbId}`, title: displayEntry.title, type: displayEntry.is_tvseries ? "tv" : "movie", poster_path: displayEntry.poster_path, - libraryId: entryId, + libraryId: isLibrary ? entryId : undefined, tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined, }); } - }, [entryId, displayEntry?.title]); + }, [entryId, previewTmdbId, displayEntry?.title]); - if (isLoading || !displayEntry) { + if (!isLibrary && previewError) { + return ( +
+

Could not load entry from TMDB.

+ +
+ ); + } + + if ( + (isLibrary ? isLoading : previewLoading) || + !displayEntry || + libraryMatch + ) { return ; } const e = displayEntry; - // Use useEntryCredits (allCredits) which includes both cast AND crew (director). + // Library: useEntryCredits (allCredits) includes both cast AND crew (director); // e.credits from useEntry is a limited preview (10 items). - const credits = allCredits.length > 0 ? allCredits : e.credits || []; + // Preview: the TMDB preview's cast + directors, linked by TMDB id. + const credits: Credit[] = isLibrary + ? allCredits.length > 0 + ? allCredits + : e.credits || [] + : ((preview?.credits ?? []) as unknown as Credit[]); + const previewSeasons = isLibrary ? [] : (preview?.seasons ?? []); + const seasonCount = isLibrary + ? (seasons?.length ?? 0) + : previewSeasons.length; + const tmdbType = e.is_tvseries ? "tv" : "movie"; + + const addToLibrary = () => { + createEntry.mutate( + { tmdb_id: previewTmdbId, is_tvserie: e.is_tvseries }, + { + onSuccess: (newEntry) => + navigate(`/entry/${newEntry.id}`, { replace: true }), + }, + ); + }; const backdrop = getBackdropUrl(e); const poster = getPosterUrl(e); const director = credits.find( @@ -289,7 +370,7 @@ export function EntryDetailsPage() { {e.status} )} - {e.is_tvseries && ( + {e.is_tvseries && isLibrary && ( + )} {videos.length > 0 ? ( - - ); - } - - const backdrop = preview.backdrop_path - ? `${TMDB_IMG}/w1280${preview.backdrop_path}` - : null; - const poster = preview.poster_path - ? `${TMDB_IMG}/w500${preview.poster_path}` - : "/images/default-poster.png"; - - const handleAddToLibrary = () => { - createEntry.mutate( - { tmdb_id: preview.tmdb_id, is_tvserie: preview.is_tvseries }, - { - onSuccess: (newEntry) => - navigate(`/entry/${newEntry.id}`, { replace: true }), - }, - ); - }; - - return ( -
- {/* Backdrop banner */} -
- {backdrop ? ( - - ) : ( -
- )} -
-
- - {/* Main content */} -
- {/* Add to Library button — top right */} -
- {libraryEntry ? ( - - ) : ( - - )} -
- - {/* Two-column header: poster | info */} -
- {/* LEFT: Poster */} -
- {preview.title} - {/* External links */} -
- {preview.tmdb_id && ( - - - TMDB - - )} - {preview.imdb_id && ( - - - IMDb - - )} -
-
- - {/* RIGHT: Info */} -
- {/* Title */} -
-

- {preview.title} -

-
- - {/* Meta */} -
- {preview.release_date && ( - {getYear(preview.release_date)} - )} - {preview.is_tvseries && preview.status && ( - <> - • - {preview.status} - - )} - {preview.runtime && !preview.is_tvseries && ( - <> - {preview.release_date && •} - {formatRuntime(preview.runtime)} - - )} -
- - {/* TV series season count */} - {preview.is_tvseries && preview.number_of_seasons != null && ( -
- - {preview.number_of_seasons}{" "} - {preview.number_of_seasons === 1 ? "Season" : "Seasons"} - - {preview.number_of_episodes != null && ( - - ({preview.number_of_episodes} episodes) - - )} -
- )} - - {/* Genres */} - {preview.genres.length > 0 && ( -
- {preview.genres.map((g) => ( - - {g.name} - - ))} -
- )} - - {/* Rating */} - {preview.vote_average != null && preview.vote_average > 0 && ( -
- - TMDB: - {preview.vote_average.toFixed(1)}/10 - -
- )} - - {/* Storyline */} - {preview.storyline && ( - <> -

- {preview.storyline} -

- - )} -
-
- - {/* Sections */} -
- {preview.credits && preview.credits.length > 0 && ( - <> - - - - )} -
-
-
- ); -} diff --git a/react_frontend/src/router.tsx b/react_frontend/src/router.tsx index 6db16d2..51a8234 100644 --- a/react_frontend/src/router.tsx +++ b/react_frontend/src/router.tsx @@ -53,11 +53,6 @@ const EntryDetailsPage = lazy(() => default: m.EntryDetailsPage, })), ); -const TmdbPreviewPage = lazy(() => - import("@/pages/TmdbPreviewPage").then((m) => ({ - default: m.TmdbPreviewPage, - })), -); const TmdbCastsPage = lazy(() => import("@/pages/TmdbCastsPage").then((m) => ({ default: m.TmdbCastsPage, @@ -226,7 +221,7 @@ export const router = createRouter([ path: "/entry/tmdb/:type/:tmdbId", element: ( }> - + ), }, diff --git a/react_frontend/src/types/index.ts b/react_frontend/src/types/index.ts index b127f2c..76d871f 100644 --- a/react_frontend/src/types/index.ts +++ b/react_frontend/src/types/index.ts @@ -426,4 +426,43 @@ export interface TmdbPreview { homepage: string | null; imdb_id: string | null; credits: TmdbPreviewCredit[]; + /** Same shape as a library Entry, built from the TMDB data */ + entry?: Entry; + seasons?: TmdbPreviewSeason[]; +} + +export interface TmdbPreviewSeason { + id: number; + name: string; + season_number: number; + episode_count: number; + air_date: string | null; + poster_path: string | null; + overview: string | null; + tmdb_rating: number | null; +} + +/* ---------- Artwork (TMDB images merged with the media table) ---------- */ +export type ArtworkType = "poster" | "backdrop" | "logo"; + +export interface ArtworkItem { + /** TMDB file path; null for local-only media (custom uploads, old downloads) */ + file_path: string | null; + width: number | null; + height: number | null; + aspect_ratio: number | null; + language: string | null; + vote_average: number; + vote_count: number; + in_library: boolean; + media_id?: number | null; + media_path?: string | null; + is_selected?: boolean; + is_custom?: boolean; +} + +export interface ArtworkResponse { + posters: ArtworkItem[]; + backdrops: ArtworkItem[]; + logos: ArtworkItem[]; }