Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28eee34548 | ||
|
|
a9ff2d089a | ||
|
|
cee6f7f961 |
No files matched your search
@@ -0,0 +1,74 @@
|
||||
const sequelize = require("./database");
|
||||
|
||||
/**
|
||||
* Lightweight, idempotent schema migrations.
|
||||
*
|
||||
* `sequelize.sync()` runs without `alter`, so new model attributes never reach
|
||||
* existing tables. This adds any column a model defines but the table lacks
|
||||
* (additive only — nothing is dropped) and widens the few columns whose type
|
||||
* changed. Safe to run on every start.
|
||||
*/
|
||||
|
||||
// [model name, attribute name, expected DB type prefix (from describeTable)]
|
||||
const TYPE_CHANGES = [
|
||||
["entry", "certification", "VARCHAR(20)"],
|
||||
["entry", "last_fetch", "DATETIME"],
|
||||
["entry", "network_studio", "VARCHAR(100)"],
|
||||
["network", "name", "VARCHAR(100)"],
|
||||
];
|
||||
|
||||
async function addMissingColumns(queryInterface) {
|
||||
for (const model of Object.values(sequelize.models)) {
|
||||
const table = model.getTableName();
|
||||
let columns;
|
||||
try {
|
||||
columns = await queryInterface.describeTable(table);
|
||||
} catch {
|
||||
continue; // table not created yet; sync handles it
|
||||
}
|
||||
|
||||
for (const [name, attribute] of Object.entries(model.rawAttributes)) {
|
||||
const column = attribute.field || name;
|
||||
if (columns[column] || attribute.type?.key === "VIRTUAL") continue;
|
||||
|
||||
console.log(`[MIGRATION] Adding column ${table}.${column}`);
|
||||
await queryInterface.addColumn(table, column, {
|
||||
type: attribute.type,
|
||||
allowNull: attribute.allowNull !== false,
|
||||
defaultValue: attribute.defaultValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function applyTypeChanges(queryInterface) {
|
||||
for (const [modelName, attributeName, expectedType] of TYPE_CHANGES) {
|
||||
const model = sequelize.models[modelName];
|
||||
if (!model) continue;
|
||||
|
||||
const attribute = model.rawAttributes[attributeName];
|
||||
const column = attribute.field || attributeName;
|
||||
const table = model.getTableName();
|
||||
const columns = await queryInterface.describeTable(table);
|
||||
const current = columns[column]?.type?.toUpperCase();
|
||||
|
||||
if (!current || current.startsWith(expectedType)) continue;
|
||||
|
||||
console.log(
|
||||
`[MIGRATION] Changing ${table}.${column} from ${current} to ${expectedType}`,
|
||||
);
|
||||
await queryInterface.changeColumn(table, column, {
|
||||
type: attribute.type,
|
||||
allowNull: attribute.allowNull !== false,
|
||||
defaultValue: attribute.defaultValue,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function runMigrations() {
|
||||
const queryInterface = sequelize.getQueryInterface();
|
||||
await addMissingColumns(queryInterface);
|
||||
await applyTypeChanges(queryInterface);
|
||||
}
|
||||
|
||||
module.exports = { runMigrations };
|
||||
@@ -1,9 +1,15 @@
|
||||
const EntryRating = require('../models/EntryRating');
|
||||
const collectionManager = require('../services/collectionManager');
|
||||
const entryManager = require('../services/entryManager');
|
||||
const entryService = require('../services/entryService');
|
||||
const tmdbService = require('../services/tmdbService');
|
||||
const asyncWrapper = require('../utils/asyncWrapper');
|
||||
const EntryRating = require("../models/EntryRating");
|
||||
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;
|
||||
const _entryManager = entryManager;
|
||||
@@ -105,7 +111,7 @@ class EntryController {
|
||||
const seasons = await _entryService.getEntrySeasons(id);
|
||||
|
||||
if (seasons.length == 0) {
|
||||
return res.status(204).json({ message: 'Provided entry has no seasons' });
|
||||
return res.status(204).json({ message: "Provided entry has no seasons" });
|
||||
}
|
||||
|
||||
res.status(200).json(seasons);
|
||||
@@ -126,6 +132,59 @@ class EntryController {
|
||||
res.status(201).json(entry);
|
||||
});
|
||||
|
||||
// * GET - TMDB RECOMMENDATIONS FOR A LIBRARY ENTRY (live, not stored)
|
||||
getEntryRecommendations = asyncWrapper(async (req, res) => {
|
||||
const entry = await _entryService.getEntryById(req.params.id, false);
|
||||
const tmdbId = entry.entryId?.tmdb_id;
|
||||
if (!tmdbId)
|
||||
return res.status(400).json({ message: "Entry has no TMDB id" });
|
||||
|
||||
const data = await tmdbService.fetchEntryRecommendations(
|
||||
tmdbId,
|
||||
entry.is_tvseries,
|
||||
req.query.page || 1,
|
||||
);
|
||||
if (!data)
|
||||
return res
|
||||
.status(500)
|
||||
.json({ message: "Failed to fetch recommendations" });
|
||||
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;
|
||||
@@ -145,7 +204,7 @@ class EntryController {
|
||||
const { page } = req.query;
|
||||
const data = await tmdbService.fetchTrending(type, page || 1);
|
||||
if (!data)
|
||||
return res.status(500).json({ message: 'Failed to fetch trending data' });
|
||||
return res.status(500).json({ message: "Failed to fetch trending data" });
|
||||
res.status(200).json(data);
|
||||
});
|
||||
|
||||
@@ -155,7 +214,7 @@ class EntryController {
|
||||
const { page } = req.query;
|
||||
const data = await tmdbService.fetchPopular(type, page || 1);
|
||||
if (!data)
|
||||
return res.status(500).json({ message: 'Failed to fetch popular data' });
|
||||
return res.status(500).json({ message: "Failed to fetch popular data" });
|
||||
res.status(200).json(data);
|
||||
});
|
||||
|
||||
@@ -163,10 +222,10 @@ class EntryController {
|
||||
getTmdbSearch = asyncWrapper(async (req, res) => {
|
||||
const { query, page } = req.query;
|
||||
if (!query)
|
||||
return res.status(400).json({ message: 'Query parameter is required' });
|
||||
return res.status(400).json({ message: "Query parameter is required" });
|
||||
const data = await tmdbService.searchMulti(query, page || 1);
|
||||
if (!data)
|
||||
return res.status(500).json({ message: 'Failed to search TMDB' });
|
||||
return res.status(500).json({ message: "Failed to search TMDB" });
|
||||
res.status(200).json(data);
|
||||
});
|
||||
|
||||
@@ -178,7 +237,7 @@ class EntryController {
|
||||
if (!data)
|
||||
return res
|
||||
.status(500)
|
||||
.json({ message: 'Failed to fetch top rated data' });
|
||||
.json({ message: "Failed to fetch top rated data" });
|
||||
res.status(200).json(data);
|
||||
});
|
||||
|
||||
@@ -187,17 +246,17 @@ class EntryController {
|
||||
const { page } = req.query;
|
||||
const data = await tmdbService.fetchUpcoming(page || 1);
|
||||
if (!data)
|
||||
return res.status(500).json({ message: 'Failed to fetch upcoming data' });
|
||||
return res.status(500).json({ message: "Failed to fetch upcoming data" });
|
||||
res.status(200).json(data);
|
||||
});
|
||||
|
||||
// * GET - TMDB PREVIEW (fetch details without saving to library)
|
||||
getTmdbPreview = asyncWrapper(async (req, res) => {
|
||||
const { type, tmdbId } = req.params;
|
||||
const is_tvserie = type === 'tv';
|
||||
const is_tvserie = type === "tv";
|
||||
const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie);
|
||||
if (!data)
|
||||
return res.status(404).json({ message: 'Entry not found on TMDB' });
|
||||
return res.status(404).json({ message: "Entry not found on TMDB" });
|
||||
|
||||
// Fetch credits in parallel
|
||||
const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie);
|
||||
@@ -208,7 +267,7 @@ class EntryController {
|
||||
for (const c of creditsData.cast) {
|
||||
credits.push({
|
||||
id: c.credit_id || c.id,
|
||||
cast_type: 'cast',
|
||||
cast_type: "cast",
|
||||
character: is_tvserie
|
||||
? c.roles?.[0]?.character || c.character || null
|
||||
: c.character || null,
|
||||
@@ -223,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,
|
||||
@@ -248,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);
|
||||
|
||||
@@ -78,6 +78,33 @@ class MaintenanceController {
|
||||
const result = await _maintenanceService.fixImpossibleSeenDates();
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
parseHours(value) {
|
||||
const hours = Number(value ?? 24);
|
||||
return Number.isFinite(hours) && hours >= 0 ? hours : 24;
|
||||
}
|
||||
|
||||
async getStaleEntries(req, res) {
|
||||
const hours = maintenanceController.parseHours(req.query.hours);
|
||||
const entries = await _maintenanceService.getStaleEntries(hours);
|
||||
return res.status(200).json({
|
||||
count: entries.length,
|
||||
hours,
|
||||
job: _maintenanceService.getStaleRefreshStatus(),
|
||||
});
|
||||
}
|
||||
|
||||
async startStaleRefresh(req, res) {
|
||||
const hours = maintenanceController.parseHours(req.query.hours);
|
||||
const result = await _maintenanceService.startStaleRefresh(hours);
|
||||
return res.status(result.alreadyRunning ? 409 : 202).json(result);
|
||||
}
|
||||
|
||||
async cancelStaleRefresh(req, res) {
|
||||
return res.status(200).json(_maintenanceService.cancelStaleRefresh());
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MaintenanceController();
|
||||
const maintenanceController = new MaintenanceController();
|
||||
|
||||
module.exports = maintenanceController;
|
||||
@@ -4,6 +4,10 @@ const Season = require("../models/Season");
|
||||
const Entry = require("../models/Entry");
|
||||
const EntryId = require("../models/EntryId");
|
||||
const { fetchSeasonData } = require("../services/tmdbService");
|
||||
const {
|
||||
mapSeasonFields,
|
||||
mapEpisodeFields,
|
||||
} = require("../mappers/entryMapper.js");
|
||||
|
||||
class SeasonController {
|
||||
constructor() {
|
||||
@@ -117,14 +121,22 @@ class SeasonController {
|
||||
return res.status(500).send("Couldn't fetch data from TMDB");
|
||||
}
|
||||
|
||||
await season.update({
|
||||
name: seasonData.name,
|
||||
overview: seasonData.overview,
|
||||
episode_count: seasonData.episodes?.length ?? season.episode_count,
|
||||
air_date: seasonData.air_date,
|
||||
tmdb_rating: seasonData.vote_average,
|
||||
poster_path: seasonData.poster_path,
|
||||
});
|
||||
await season.update(mapSeasonFields(seasonData));
|
||||
|
||||
// Keep the season's episodes in sync too (guest stars, crew, votes…)
|
||||
for (const episode of seasonData.episodes ?? []) {
|
||||
const existingEpisode = await Episode.findOne({
|
||||
where: { tmdb_id: episode.id },
|
||||
});
|
||||
if (existingEpisode) {
|
||||
await existingEpisode.update(mapEpisodeFields(episode));
|
||||
} else {
|
||||
await Episode.create({
|
||||
...mapEpisodeFields(episode),
|
||||
season_id: season.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const refreshedSeason = await Season.findByPk(req.params.id);
|
||||
res.send(refreshedSeason);
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Maps TMDB responses (from tmdbService.fetchEntryData / fetchSeasonData) to
|
||||
* the column values we store. Used by entry creation, the entry refresh and
|
||||
* the legacy importer so every path saves the same fields.
|
||||
*/
|
||||
|
||||
const CERTIFICATION_REGIONS = ["US", "GB"];
|
||||
const MAX_VIDEOS = 12;
|
||||
const MAX_KEYWORDS = 30;
|
||||
const MAX_EPISODE_CREW = 15;
|
||||
const MAX_GUEST_STARS = 25;
|
||||
|
||||
const pick = (obj, keys) =>
|
||||
obj ? Object.fromEntries(keys.map((k) => [k, obj[k] ?? null])) : null;
|
||||
|
||||
function isTv(data) {
|
||||
return data.first_air_date !== undefined || data.name !== undefined;
|
||||
}
|
||||
|
||||
/** First non-empty certification, preferring US, then the origin country. */
|
||||
function mapCertification(data) {
|
||||
const regions = [...CERTIFICATION_REGIONS, ...(data.origin_country ?? [])];
|
||||
|
||||
if (data.content_ratings) {
|
||||
const results = data.content_ratings.results ?? [];
|
||||
for (const region of regions) {
|
||||
const rating = results.find((r) => r.iso_3166_1 === region)?.rating;
|
||||
if (rating) return rating;
|
||||
}
|
||||
return results.find((r) => r.rating)?.rating ?? null;
|
||||
}
|
||||
|
||||
if (data.release_dates) {
|
||||
const results = data.release_dates.results ?? [];
|
||||
const certFor = (r) => {
|
||||
const dates = (r?.release_dates ?? []).filter((d) => d.certification);
|
||||
// Prefer theatrical (3), then limited (2), then anything
|
||||
const byType =
|
||||
dates.find((d) => d.type === 3) ??
|
||||
dates.find((d) => d.type === 2) ??
|
||||
dates[0];
|
||||
return byType?.certification || null;
|
||||
};
|
||||
for (const region of regions) {
|
||||
const cert = certFor(results.find((r) => r.iso_3166_1 === region));
|
||||
if (cert) return cert;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function mapVideos(videos) {
|
||||
const results = (videos?.results ?? []).filter(
|
||||
(v) => v.site === "YouTube" && v.key,
|
||||
);
|
||||
const rank = (v) =>
|
||||
(v.type === "Trailer" ? 0 : v.type === "Teaser" ? 1 : 2) +
|
||||
(v.official ? 0 : 3);
|
||||
return results
|
||||
.sort(
|
||||
(a, b) =>
|
||||
rank(a) - rank(b) ||
|
||||
new Date(b.published_at) - new Date(a.published_at),
|
||||
)
|
||||
.slice(0, MAX_VIDEOS)
|
||||
.map((v) =>
|
||||
pick(v, ["key", "name", "type", "official", "published_at", "iso_639_1"]),
|
||||
);
|
||||
}
|
||||
|
||||
/** Keeps per-country provider lists, trimmed to what the UI needs. */
|
||||
function mapWatchProviders(providers) {
|
||||
const results = providers?.results;
|
||||
if (!results) return null;
|
||||
|
||||
const trimList = (list) =>
|
||||
list?.map((p) =>
|
||||
pick(p, [
|
||||
"provider_id",
|
||||
"provider_name",
|
||||
"logo_path",
|
||||
"display_priority",
|
||||
]),
|
||||
);
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(results).map(([country, info]) => [
|
||||
country,
|
||||
{
|
||||
link: info.link ?? null,
|
||||
flatrate: trimList(info.flatrate),
|
||||
free: trimList(info.free),
|
||||
ads: trimList(info.ads),
|
||||
rent: trimList(info.rent),
|
||||
buy: trimList(info.buy),
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function mapEpisodeSummary(episode) {
|
||||
return pick(episode, [
|
||||
"id",
|
||||
"name",
|
||||
"season_number",
|
||||
"episode_number",
|
||||
"air_date",
|
||||
"episode_type",
|
||||
"runtime",
|
||||
"still_path",
|
||||
]);
|
||||
}
|
||||
|
||||
/** Entry table columns. */
|
||||
function mapEntryFields(data) {
|
||||
const tv = isTv(data);
|
||||
const keywords = (data.keywords?.keywords ?? data.keywords?.results ?? [])
|
||||
.slice(0, MAX_KEYWORDS)
|
||||
.map((k) => k.name);
|
||||
const alternativeTitles = (
|
||||
data.alternative_titles?.titles ??
|
||||
data.alternative_titles?.results ??
|
||||
[]
|
||||
).map((t) => pick(t, ["iso_3166_1", "title", "type"]));
|
||||
|
||||
return {
|
||||
title: data.title || data.name,
|
||||
original_title: data.original_title || data.original_name,
|
||||
release_date: data.release_date || data.first_air_date || null,
|
||||
release_status: data.status,
|
||||
runtime:
|
||||
data.runtime ||
|
||||
data.episode_run_time?.[0] ||
|
||||
data.last_episode_to_air?.runtime ||
|
||||
null,
|
||||
|
||||
tagline: data.tagline || null,
|
||||
storyline: data.overview,
|
||||
country: data.production_countries?.[0]?.name ?? null,
|
||||
|
||||
status: data.status,
|
||||
certification: mapCertification(data),
|
||||
network_studio:
|
||||
data.networks?.[0]?.name ?? data.production_companies?.[0]?.name ?? null,
|
||||
|
||||
adult: !!data.adult,
|
||||
tmdb_popularity: data.popularity ?? null,
|
||||
original_language: data.original_language ?? null,
|
||||
origin_country: data.origin_country ?? null,
|
||||
spoken_languages:
|
||||
data.spoken_languages?.map((l) =>
|
||||
pick(l, ["iso_639_1", "english_name", "name"]),
|
||||
) ?? null,
|
||||
production_countries: data.production_countries ?? null,
|
||||
production_companies:
|
||||
data.production_companies?.map((c) =>
|
||||
pick(c, ["id", "name", "logo_path", "origin_country"]),
|
||||
) ?? null,
|
||||
homepage: data.homepage || null,
|
||||
budget: tv ? null : data.budget || null,
|
||||
revenue: tv ? null : data.revenue || null,
|
||||
keywords,
|
||||
tmdb_videos: mapVideos(data.videos),
|
||||
watch_providers: mapWatchProviders(data["watch/providers"]),
|
||||
alternative_titles: alternativeTitles,
|
||||
|
||||
tv_type: tv ? (data.type ?? null) : null,
|
||||
created_by: tv
|
||||
? (data.created_by ?? []).map((p) =>
|
||||
pick(p, ["id", "name", "profile_path"]),
|
||||
)
|
||||
: null,
|
||||
number_of_seasons: tv ? (data.number_of_seasons ?? null) : null,
|
||||
number_of_episodes: tv ? (data.number_of_episodes ?? null) : null,
|
||||
last_air_date: tv ? (data.last_air_date ?? null) : null,
|
||||
in_production: tv ? (data.in_production ?? null) : null,
|
||||
next_episode_to_air: tv
|
||||
? mapEpisodeSummary(data.next_episode_to_air)
|
||||
: null,
|
||||
last_episode_to_air: tv
|
||||
? mapEpisodeSummary(data.last_episode_to_air)
|
||||
: null,
|
||||
|
||||
poster_path: data.poster_path,
|
||||
banner_path: data.backdrop_path,
|
||||
|
||||
last_fetch: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
/** EntryId table columns. TV details have no imdb_id; it's in external_ids. */
|
||||
function mapEntryIds(data) {
|
||||
const ext = data.external_ids ?? {};
|
||||
return {
|
||||
imdb_id: data.imdb_id || ext.imdb_id || null,
|
||||
tvdb_id: ext.tvdb_id != null ? String(ext.tvdb_id) : null,
|
||||
wikidata_id: ext.wikidata_id || null,
|
||||
facebook_id: ext.facebook_id || null,
|
||||
instagram_id: ext.instagram_id || null,
|
||||
twitter_id: ext.twitter_id || null,
|
||||
};
|
||||
}
|
||||
|
||||
/** EntryRating TMDB columns (user/imdb/rt ratings are left untouched). */
|
||||
function mapEntryRatings(data) {
|
||||
return {
|
||||
tmdb_rating: data.vote_average ?? null,
|
||||
tmdb_vote_count: data.vote_count ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Season table columns from a season details response. */
|
||||
function mapSeasonFields(seasonData) {
|
||||
return {
|
||||
tmdb_id: seasonData.id,
|
||||
tvdb_id:
|
||||
seasonData.external_ids?.tvdb_id != null
|
||||
? String(seasonData.external_ids.tvdb_id)
|
||||
: null,
|
||||
name: seasonData.name,
|
||||
overview: seasonData.overview,
|
||||
season_number: seasonData.season_number,
|
||||
episode_count: seasonData.episodes?.length ?? 0,
|
||||
air_date: seasonData.air_date,
|
||||
tmdb_rating: seasonData.vote_average,
|
||||
poster_path: seasonData.poster_path,
|
||||
};
|
||||
}
|
||||
|
||||
/** Episode table columns from an entry of seasonData.episodes. */
|
||||
function mapEpisodeFields(episode) {
|
||||
return {
|
||||
tmdb_id: episode.id,
|
||||
name: episode.name,
|
||||
overview: episode.overview,
|
||||
episode_number: episode.episode_number,
|
||||
episode_type: episode.episode_type,
|
||||
runtime: episode.runtime,
|
||||
air_date: episode.air_date,
|
||||
tmdb_rating: episode.vote_average,
|
||||
tmdb_vote_count: episode.vote_count ?? null,
|
||||
production_code: episode.production_code || null,
|
||||
crew: (episode.crew ?? [])
|
||||
.filter((c) => ["Directing", "Writing"].includes(c.department))
|
||||
.slice(0, MAX_EPISODE_CREW)
|
||||
.map((c) => pick(c, ["id", "name", "job", "department", "profile_path"])),
|
||||
guest_stars: (episode.guest_stars ?? [])
|
||||
.slice(0, MAX_GUEST_STARS)
|
||||
.map((g) =>
|
||||
pick(g, ["id", "name", "character", "profile_path", "order"]),
|
||||
),
|
||||
still_path: episode.still_path,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
mapEntryFields,
|
||||
mapEntryIds,
|
||||
mapEntryRatings,
|
||||
mapSeasonFields,
|
||||
mapEpisodeFields,
|
||||
};
|
||||
+62
-21
@@ -1,27 +1,54 @@
|
||||
const { DataTypes } = require('sequelize');
|
||||
const sequelize = require('../config/database');
|
||||
const { DataTypes } = require("sequelize");
|
||||
const sequelize = require("../config/database");
|
||||
|
||||
const Entry = sequelize.define('entry', {
|
||||
const Entry = sequelize.define("entry", {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||
|
||||
title: { type: DataTypes.STRING(500) },
|
||||
original_title: { type: DataTypes.STRING(100), field: 'original_title' },
|
||||
release_date: { type: DataTypes.DATE, field: 'release_date' },
|
||||
release_status: { type: DataTypes.STRING(50), field: 'release_status' },
|
||||
original_title: { type: DataTypes.STRING(100), field: "original_title" },
|
||||
release_date: { type: DataTypes.DATE, field: "release_date" },
|
||||
release_status: { type: DataTypes.STRING(50), field: "release_status" },
|
||||
runtime: { type: DataTypes.INTEGER },
|
||||
|
||||
tagline: { type: DataTypes.STRING(200) },
|
||||
storyline: { type: DataTypes.STRING(3000) },
|
||||
country: { type: DataTypes.STRING(30) },
|
||||
|
||||
certification: { type: DataTypes.INTEGER },
|
||||
network_studio: { type: DataTypes.STRING(40), field: 'network_studio' },
|
||||
collection_id: { type: DataTypes.INTEGER, field: 'collection_id' },
|
||||
max_cast: { type: DataTypes.INTEGER, field: 'max_cast', defaultValue: 10 },
|
||||
certification: { type: DataTypes.STRING(20) },
|
||||
network_studio: { type: DataTypes.STRING(100), field: "network_studio" },
|
||||
|
||||
// ? TMDB details
|
||||
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||
tmdb_popularity: { type: DataTypes.FLOAT, field: "tmdb_popularity" },
|
||||
original_language: { type: DataTypes.STRING(10), field: "original_language" },
|
||||
origin_country: { type: DataTypes.JSON, field: "origin_country" },
|
||||
spoken_languages: { type: DataTypes.JSON, field: "spoken_languages" },
|
||||
production_countries: { type: DataTypes.JSON, field: "production_countries" },
|
||||
production_companies: { type: DataTypes.JSON, field: "production_companies" },
|
||||
homepage: { type: DataTypes.STRING(500) },
|
||||
budget: { type: DataTypes.BIGINT },
|
||||
revenue: { type: DataTypes.BIGINT },
|
||||
keywords: { type: DataTypes.JSON },
|
||||
tmdb_videos: { type: DataTypes.JSON, field: "tmdb_videos" },
|
||||
watch_providers: { type: DataTypes.JSON, field: "watch_providers" },
|
||||
alternative_titles: { type: DataTypes.JSON, field: "alternative_titles" },
|
||||
|
||||
// ? TV-only TMDB details
|
||||
tv_type: { type: DataTypes.STRING(30), field: "tv_type" },
|
||||
created_by: { type: DataTypes.JSON, field: "created_by" },
|
||||
number_of_seasons: { type: DataTypes.INTEGER, field: "number_of_seasons" },
|
||||
number_of_episodes: { type: DataTypes.INTEGER, field: "number_of_episodes" },
|
||||
last_air_date: { type: DataTypes.DATEONLY, field: "last_air_date" },
|
||||
in_production: { type: DataTypes.BOOLEAN, field: "in_production" },
|
||||
next_episode_to_air: { type: DataTypes.JSON, field: "next_episode_to_air" },
|
||||
last_episode_to_air: { type: DataTypes.JSON, field: "last_episode_to_air" },
|
||||
|
||||
collection_id: { type: DataTypes.INTEGER, field: "collection_id" },
|
||||
max_cast: { type: DataTypes.INTEGER, field: "max_cast", defaultValue: 10 },
|
||||
credit_fetched: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: false,
|
||||
field: 'credit_fetched',
|
||||
field: "credit_fetched",
|
||||
},
|
||||
|
||||
watchlist: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||
@@ -30,35 +57,49 @@ const Entry = sequelize.define('entry', {
|
||||
showInCalendar: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
defaultValue: true,
|
||||
field: 'show_in_calendar',
|
||||
field: "show_in_calendar",
|
||||
},
|
||||
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: 'auto_sync' },
|
||||
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: "auto_sync" },
|
||||
|
||||
note: { type: DataTypes.STRING(2000) },
|
||||
|
||||
is_tvseries: { type: DataTypes.BOOLEAN, field: 'is_tvseries' },
|
||||
is_tvseries: { type: DataTypes.BOOLEAN, field: "is_tvseries" },
|
||||
status: { type: DataTypes.STRING(20) },
|
||||
|
||||
poster_path: { type: DataTypes.STRING(200), field: 'poster_path' },
|
||||
banner_path: { type: DataTypes.STRING(200), field: 'banner_path' },
|
||||
poster_path: { type: DataTypes.STRING(200), field: "poster_path" },
|
||||
banner_path: { type: DataTypes.STRING(200), field: "banner_path" },
|
||||
|
||||
date_first_seen: { type: DataTypes.DATEONLY, field: 'date_first_seen' },
|
||||
date_last_seen: { type: DataTypes.DATEONLY, field: 'date_last_seen' },
|
||||
date_first_seen: { type: DataTypes.DATEONLY, field: "date_first_seen" },
|
||||
date_last_seen: { type: DataTypes.DATEONLY, field: "date_last_seen" },
|
||||
|
||||
last_fetch: { type: DataTypes.DATEONLY },
|
||||
last_fetch: { type: DataTypes.DATE },
|
||||
|
||||
entry_sync_status: {
|
||||
type: DataTypes.STRING(50),
|
||||
field: 'entry_sync_status',
|
||||
field: "entry_sync_status",
|
||||
allowNull: true,
|
||||
},
|
||||
director: { type: DataTypes.STRING(200), allowNull: true },
|
||||
watch_status: {
|
||||
type: DataTypes.STRING(20),
|
||||
field: 'watch_status',
|
||||
field: "watch_status",
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
},
|
||||
});
|
||||
|
||||
// Large JSON columns only needed on the details page; left out of list queries.
|
||||
Entry.DETAIL_ONLY_ATTRIBUTES = [
|
||||
"keywords",
|
||||
"tmdb_videos",
|
||||
"watch_providers",
|
||||
"alternative_titles",
|
||||
"production_companies",
|
||||
"spoken_languages",
|
||||
"production_countries",
|
||||
"created_by",
|
||||
"next_episode_to_air",
|
||||
"last_episode_to_air",
|
||||
];
|
||||
|
||||
module.exports = Entry;
|
||||
@@ -15,6 +15,10 @@ const EntryId = sequelize.define(
|
||||
tmdb_id: { type: DataTypes.STRING(30) },
|
||||
imdb_id: { type: DataTypes.STRING(30) },
|
||||
tvdb_id: { type: DataTypes.STRING(30) },
|
||||
wikidata_id: { type: DataTypes.STRING(30) },
|
||||
facebook_id: { type: DataTypes.STRING(100) },
|
||||
instagram_id: { type: DataTypes.STRING(100) },
|
||||
twitter_id: { type: DataTypes.STRING(100) },
|
||||
},
|
||||
{
|
||||
timestamps: false,
|
||||
|
||||
@@ -14,6 +14,7 @@ const EntryRating = sequelize.define(
|
||||
},
|
||||
user_rating: { type: DataTypes.FLOAT },
|
||||
tmdb_rating: { type: DataTypes.FLOAT },
|
||||
tmdb_vote_count: { type: DataTypes.INTEGER },
|
||||
imdb_rating: { type: DataTypes.FLOAT },
|
||||
rotten_tomatoes_rating: { type: DataTypes.FLOAT },
|
||||
},
|
||||
|
||||
@@ -25,6 +25,11 @@ const Episode = sequelize.define("episode", {
|
||||
|
||||
user_rating: { type: DataTypes.FLOAT },
|
||||
tmdb_rating: { type: DataTypes.FLOAT },
|
||||
tmdb_vote_count: { type: DataTypes.INTEGER },
|
||||
|
||||
production_code: { type: DataTypes.STRING(50) },
|
||||
crew: { type: DataTypes.JSON },
|
||||
guest_stars: { type: DataTypes.JSON },
|
||||
|
||||
still_path: { type: DataTypes.STRING(200) },
|
||||
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -4,7 +4,7 @@ const sequelize = require("../config/database");
|
||||
const Network = sequelize.define("network", {
|
||||
id: { type: DataTypes.INTEGER, primaryKey: true },
|
||||
|
||||
name: { type: DataTypes.STRING(30) },
|
||||
name: { type: DataTypes.STRING(100) },
|
||||
originCountry: { type: DataTypes.STRING(100), field: "origin_country" },
|
||||
homepage: { type: DataTypes.STRING(100), field: "homepage" },
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ const People = sequelize.define("peoples", {
|
||||
tmdb_id: { type: DataTypes.STRING(100) },
|
||||
|
||||
name: { type: DataTypes.STRING(100) },
|
||||
original_name: { type: DataTypes.STRING(200) },
|
||||
birthday: { type: DataTypes.DATEONLY },
|
||||
deathday: { type: DataTypes.DATEONLY, allowNull: true },
|
||||
gender: { type: DataTypes.INTEGER },
|
||||
|
||||
@@ -6,6 +6,7 @@ const Season = sequelize.define("season", {
|
||||
|
||||
tmdb_id: { type: DataTypes.STRING(30) },
|
||||
imdb_id: { type: DataTypes.STRING(30) },
|
||||
tvdb_id: { type: DataTypes.STRING(30) },
|
||||
|
||||
entry_id: {
|
||||
type: DataTypes.INTEGER,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -31,6 +36,12 @@ entryRouter.delete("/:id", entryController.deleteEntry);
|
||||
|
||||
entryRouter.get("/:id/seasons", entryController.getEntrySeasons);
|
||||
entryRouter.get("/:id/credits", entryController.getEntryCredits);
|
||||
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);
|
||||
|
||||
|
||||
@@ -76,4 +76,19 @@ maintenanceRouter.post(
|
||||
maintenanceController.fixImpossibleSeenDates,
|
||||
);
|
||||
|
||||
// * GET - Count of entries not refreshed in the last ?hours=24 + job status
|
||||
maintenanceRouter.get("/stale-entries", maintenanceController.getStaleEntries);
|
||||
|
||||
// * POST - Start refreshing stale entries in the background (?hours=24)
|
||||
maintenanceRouter.post(
|
||||
"/stale-entries/refresh",
|
||||
maintenanceController.startStaleRefresh,
|
||||
);
|
||||
|
||||
// * DELETE - Cancel the running stale refresh
|
||||
maintenanceRouter.delete(
|
||||
"/stale-entries/refresh",
|
||||
maintenanceController.cancelStaleRefresh,
|
||||
);
|
||||
|
||||
module.exports = maintenanceRouter;
|
||||
+3
-1
@@ -21,6 +21,7 @@ process.on("uncaughtException", (error) => {
|
||||
const relations = require("./config/relations.js");
|
||||
const sequelizeHooks = require("./config/sequelizeHooks.js");
|
||||
const { initializeData } = require("./config/dataInitializer.js");
|
||||
const { runMigrations } = require("./config/migrations.js");
|
||||
const killerRouter = require("./routes/killer.routes.js");
|
||||
const errorHandler = require("./middleware/errorHandler");
|
||||
const authMiddleware = require("./middleware/authMiddleware");
|
||||
@@ -68,8 +69,9 @@ console.log(`Syncing database schema...`);
|
||||
sequelize
|
||||
// .sync({force: true}) // will drop all tables and recreate them.
|
||||
.sync({ alter: doUpdate }) // will attempt to automatically alter tables to fit the model definitions.
|
||||
.then((result) => {
|
||||
.then(async (result) => {
|
||||
console.log(`Database schema synced.`);
|
||||
await runMigrations();
|
||||
initializeData();
|
||||
|
||||
app.listen(PORT, () => {
|
||||
|
||||
@@ -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();
|
||||
@@ -98,6 +98,7 @@ class CollectionManager {
|
||||
mediaableId: collection.id,
|
||||
type: image.type,
|
||||
path: image.path,
|
||||
tmdbPath: image.tmdb_path || null,
|
||||
isLocal: true,
|
||||
isSelected: true,
|
||||
});
|
||||
|
||||
@@ -28,6 +28,13 @@ const entryService = require("./entryService");
|
||||
const mediaManager = require("./mediaManager.js");
|
||||
const networkService = require("./networkService.js");
|
||||
const InternalServerError = require("../errors/InternalServerError.js");
|
||||
const {
|
||||
mapEntryFields,
|
||||
mapEntryIds,
|
||||
mapEntryRatings,
|
||||
mapSeasonFields,
|
||||
mapEpisodeFields,
|
||||
} = require("../mappers/entryMapper.js");
|
||||
|
||||
const _collectionManager = collectionManager;
|
||||
const _entryService = entryService;
|
||||
@@ -107,79 +114,50 @@ class EntryManager {
|
||||
}
|
||||
|
||||
// ! the refrech logic
|
||||
let newData = {
|
||||
title: entryData.title || entryData.name,
|
||||
original_title: entryData.original_title || entryData.original_name,
|
||||
release_date: entryData.release_date || entryData.first_air_date,
|
||||
release_status: entryData.status,
|
||||
runtime: entryData.runtime || null,
|
||||
|
||||
tagline: entryData.tagline || null,
|
||||
storyline: entryData.overview,
|
||||
country:
|
||||
entryData.production_countries.length > 0
|
||||
? entryData.production_countries[0].name
|
||||
: null,
|
||||
|
||||
status: entryData.status,
|
||||
|
||||
poster_path: entryData.poster_path,
|
||||
banner_path: entryData.backdrop_path,
|
||||
|
||||
last_fetch: new Date(),
|
||||
};
|
||||
|
||||
const savedEntry = await _entryService.updateEntryById(id, newData, false);
|
||||
const savedEntry = await _entryService.updateEntryById(
|
||||
id,
|
||||
mapEntryFields(entryData),
|
||||
false,
|
||||
);
|
||||
|
||||
// * updating ids
|
||||
// TODO: get more ids
|
||||
await oldEntry.entryId.update({
|
||||
imdb_id: entryData.imdb_id,
|
||||
});
|
||||
await oldEntry.entryId.update(mapEntryIds(entryData));
|
||||
|
||||
// * updating ratings
|
||||
await oldEntry.entryRating.update({
|
||||
tmdb_rating: entryData.vote_average,
|
||||
});
|
||||
await oldEntry.entryRating.update(mapEntryRatings(entryData));
|
||||
|
||||
// * updating genres
|
||||
// * syncing genres (add new ones, drop ones TMDB no longer lists)
|
||||
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
|
||||
entryData.genres.forEach(async (genre) => {
|
||||
// if the entry already has this genre then skip
|
||||
if (currentGenresIds.includes(genre.id)) return;
|
||||
|
||||
// otherwise assign the genre to the entry
|
||||
await EntryGenre.create({
|
||||
genre_id: genre.id,
|
||||
entry_id: savedEntry.id,
|
||||
const newGenresIds = entryData.genres.map((genre) => genre.id);
|
||||
for (const genreId of newGenresIds) {
|
||||
if (currentGenresIds.includes(genreId)) continue;
|
||||
await EntryGenre.create({ genre_id: genreId, entry_id: savedEntry.id });
|
||||
}
|
||||
const removedGenresIds = currentGenresIds.filter(
|
||||
(genreId) => !newGenresIds.includes(genreId),
|
||||
);
|
||||
if (removedGenresIds.length) {
|
||||
await EntryGenre.destroy({
|
||||
where: { entry_id: savedEntry.id, genre_id: removedGenresIds },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// * networks
|
||||
// * syncing networks (also refreshes each network's name/logo/country)
|
||||
if (entryData.networks) {
|
||||
const oldNetworksIds = oldEntry.networks.map((network) => network.id);
|
||||
const networks = [];
|
||||
for (const networkData of entryData.networks) {
|
||||
// If the entry already has this network, skip it
|
||||
if (oldNetworksIds.includes(networkData.id)) continue;
|
||||
|
||||
// Create or update the network
|
||||
const [oldNetwork, newNetwork] =
|
||||
const [network] =
|
||||
await _networkService.createOrUpdateNetwork(networkData);
|
||||
let network = oldNetwork || newNetwork;
|
||||
if (!network) {
|
||||
throw new NotFoundError("Network not found");
|
||||
}
|
||||
|
||||
// Associate the new network with the entry
|
||||
await oldEntry.addNetwork(network);
|
||||
networks.push(network);
|
||||
}
|
||||
await oldEntry.setNetworks(networks);
|
||||
}
|
||||
|
||||
// * For TV-Series (Seasons & Episodes)
|
||||
if (oldEntry.is_tvseries) {
|
||||
// ? Only refrech if the series's status is not 'Ended'
|
||||
// ? and atleast 48 hours has passed
|
||||
|
||||
// * Update or insert seasons for the entry
|
||||
for (const season of entryData.seasons) {
|
||||
// fetch new season data from tmdb
|
||||
@@ -187,6 +165,7 @@ class EntryManager {
|
||||
entryData.id,
|
||||
season.season_number,
|
||||
);
|
||||
if (!seasonData) continue;
|
||||
|
||||
// Fetch existing season if it exists (using tmdb_id)
|
||||
let existingSeason = await Season.findOne({
|
||||
@@ -198,31 +177,12 @@ class EntryManager {
|
||||
|
||||
// If the season exists, update it; otherwise, create a new season
|
||||
if (existingSeason) {
|
||||
// Update existing season data
|
||||
existingSeason.tmdb_id = seasonData.id;
|
||||
existingSeason.name = seasonData.name;
|
||||
existingSeason.overview = seasonData.overview;
|
||||
existingSeason.episode_count = seasonData.episodes.length;
|
||||
existingSeason.air_date = seasonData.air_date;
|
||||
existingSeason.tmdb_rating = seasonData.vote_average;
|
||||
existingSeason.poster_path = seasonData.poster_path;
|
||||
existingSeason.banner_path = null;
|
||||
|
||||
// Save the updated season
|
||||
await existingSeason.save();
|
||||
await existingSeason.update(mapSeasonFields(seasonData));
|
||||
} else {
|
||||
// Create a new season
|
||||
existingSeason = await Season.create({
|
||||
tmdb_id: seasonData.id,
|
||||
...mapSeasonFields(seasonData),
|
||||
entry_id: oldEntry.id,
|
||||
name: seasonData.name,
|
||||
overview: seasonData.overview,
|
||||
season_number: seasonData.season_number,
|
||||
episode_count: seasonData.episodes.length,
|
||||
air_date: seasonData.air_date,
|
||||
user_rating: 0,
|
||||
tmdb_rating: seasonData.vote_average,
|
||||
poster_path: seasonData.poster_path,
|
||||
banner_path: null,
|
||||
});
|
||||
}
|
||||
@@ -242,31 +202,11 @@ class EntryManager {
|
||||
|
||||
// If the episode exists, update it; otherwise, create a new episode
|
||||
if (existingEpisode) {
|
||||
// Update existing episode data
|
||||
existingEpisode.tmdb_id = episode.tmdb_id;
|
||||
existingEpisode.name = episode.name;
|
||||
existingEpisode.overview = episode.overview;
|
||||
existingEpisode.episode_type = episode.episode_type;
|
||||
existingEpisode.runtime = episode.runtime;
|
||||
existingEpisode.air_date = episode.air_date;
|
||||
existingEpisode.tmdb_rating = episode.vote_average;
|
||||
existingEpisode.still_path = episode.still_path;
|
||||
|
||||
// Updated episode
|
||||
await existingEpisode.save();
|
||||
await existingEpisode.update(mapEpisodeFields(episode));
|
||||
} else {
|
||||
// Create a new episode
|
||||
existingEpisode = await Episode.create({
|
||||
tmdb_id: episode.id,
|
||||
...mapEpisodeFields(episode),
|
||||
season_id: existingSeason.id,
|
||||
name: episode.name,
|
||||
overview: episode.overview,
|
||||
episode_number: episode.episode_number,
|
||||
episode_type: episode.episode_type,
|
||||
runtime: episode.runtime,
|
||||
air_date: episode.air_date,
|
||||
tmdb_rating: episode.vote_average,
|
||||
still_path: episode.still_path,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -315,6 +255,7 @@ class EntryManager {
|
||||
return {
|
||||
tmdb_id: credit.id,
|
||||
name: credit.name,
|
||||
original_name: credit.original_name || null,
|
||||
gender: credit.gender || null,
|
||||
popularity: credit.popularity,
|
||||
known_for_department: credit.known_for_department || null,
|
||||
@@ -561,6 +502,7 @@ class EntryManager {
|
||||
mediaableId: oldEntry.id,
|
||||
type: image.type,
|
||||
path: image.path,
|
||||
tmdbPath: image.tmdb_path || null,
|
||||
isLocal: true,
|
||||
isSelected: true,
|
||||
});
|
||||
|
||||
@@ -20,6 +20,13 @@ const networkService = require("./networkService.js");
|
||||
const Cast = require("../models/Credit.js");
|
||||
const People = require("../models/People.js");
|
||||
const Credit = require("../models/Credit.js");
|
||||
const {
|
||||
mapEntryFields,
|
||||
mapEntryIds,
|
||||
mapEntryRatings,
|
||||
mapSeasonFields,
|
||||
mapEpisodeFields,
|
||||
} = require("../mappers/entryMapper.js");
|
||||
|
||||
const _mediaManager = mediaManager;
|
||||
const _mediaOptimizerService = mediaOptimizerService;
|
||||
@@ -35,6 +42,7 @@ class EntryService {
|
||||
|
||||
async getAllEntries() {
|
||||
const entries = await Entry.findAll({
|
||||
attributes: { exclude: Entry.DETAIL_ONLY_ATTRIBUTES },
|
||||
include: [
|
||||
{ model: EntryId, as: "entryId" },
|
||||
{ model: EntryRating, as: "entryRating" },
|
||||
@@ -154,40 +162,20 @@ class EntryService {
|
||||
console.log("entryService > createEntry > is_tvseries: ", is_tvseries);
|
||||
|
||||
let movie = Entry.build({
|
||||
title: data.title || data.name,
|
||||
original_title: data.original_title || data.original_name,
|
||||
release_date: data.release_date || data.first_air_date,
|
||||
release_status: data.status,
|
||||
runtime: data.runtime || null,
|
||||
|
||||
tagline: data.tagline || null,
|
||||
storyline: data.overview,
|
||||
country:
|
||||
data.production_countries.length > 0
|
||||
? data.production_countries[0].name
|
||||
: null,
|
||||
|
||||
...mapEntryFields(data),
|
||||
is_tvseries: is_tvseries,
|
||||
watchlist: true,
|
||||
status: data.status,
|
||||
|
||||
genres: data.genre_ids,
|
||||
|
||||
poster_path: data.poster_path,
|
||||
banner_path: data.backdrop_path,
|
||||
|
||||
last_fetch: new Date(),
|
||||
});
|
||||
|
||||
let savedEntry = await movie.save();
|
||||
|
||||
console.log("entryService > createEntry > savedEntry: ", savedEntry);
|
||||
console.log("entryService > createEntry > savedEntry: ", savedEntry.id);
|
||||
|
||||
// ? ids
|
||||
await EntryId.create({
|
||||
entry_id: savedEntry.id,
|
||||
tmdb_id: data.id,
|
||||
imdb_id: data.imdb_id,
|
||||
...mapEntryIds(data),
|
||||
});
|
||||
|
||||
// ? genres
|
||||
@@ -218,7 +206,7 @@ class EntryService {
|
||||
await EntryRating.create({
|
||||
entry_id: savedEntry.id,
|
||||
user_rating: 0,
|
||||
tmdb_rating: data.vote_average,
|
||||
...mapEntryRatings(data),
|
||||
});
|
||||
|
||||
// ! seasons & episodes for tv series
|
||||
@@ -227,21 +215,12 @@ class EntryService {
|
||||
let seasons = [];
|
||||
for (const season of data.seasons) {
|
||||
let seasonData = await fetchSeasonData(data.id, season.season_number);
|
||||
if (!seasonData) continue;
|
||||
|
||||
const savedSeason = await Season.create({
|
||||
tmdb_id: seasonData.id,
|
||||
|
||||
...mapSeasonFields(seasonData),
|
||||
entry_id: savedEntry.id,
|
||||
|
||||
name: seasonData.name,
|
||||
overview: seasonData.overview,
|
||||
season_number: seasonData.season_number,
|
||||
episode_count: seasonData.episodes.length,
|
||||
air_date: seasonData.air_date,
|
||||
|
||||
user_rating: 0,
|
||||
tmdb_rating: seasonData.vote_average,
|
||||
|
||||
poster_path: seasonData.poster_path,
|
||||
banner_path: null,
|
||||
});
|
||||
|
||||
@@ -251,20 +230,8 @@ class EntryService {
|
||||
let episodes = [];
|
||||
for (const episode of seasonData.episodes) {
|
||||
const savedEpisode = await Episode.create({
|
||||
tmdb_id: episode.id,
|
||||
|
||||
...mapEpisodeFields(episode),
|
||||
season_id: savedSeason.id,
|
||||
|
||||
name: episode.name,
|
||||
overview: episode.overview,
|
||||
episode_number: episode.episode_number,
|
||||
episode_type: episode.episode_type,
|
||||
runtime: episode.runtime,
|
||||
air_date: episode.air_date,
|
||||
|
||||
tmdb_rating: episode.vote_average,
|
||||
|
||||
still_path: episode.still_path,
|
||||
});
|
||||
|
||||
episodes.push(savedEpisode);
|
||||
@@ -309,6 +276,7 @@ class EntryService {
|
||||
return {
|
||||
tmdb_id: credit.id,
|
||||
name: credit.name,
|
||||
original_name: credit.original_name || null,
|
||||
gender: credit.gender || null,
|
||||
popularity: credit.popularity,
|
||||
known_for_department: credit.known_for_department || null,
|
||||
@@ -407,6 +375,7 @@ class EntryService {
|
||||
mediaableId: savedEntry.id,
|
||||
type: image.type,
|
||||
path: image.path,
|
||||
tmdbPath: image.tmdb_path || null,
|
||||
isLocal: true,
|
||||
isSelected: true,
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ const Media = require("../models/Media");
|
||||
const People = require("../models/People");
|
||||
const Credit = require("../models/Credit");
|
||||
const Entry = require("../models/Entry");
|
||||
const { Op } = require("sequelize");
|
||||
|
||||
const { logToFile } = require("./logService");
|
||||
const configService = require("./configService");
|
||||
@@ -569,6 +570,99 @@ class MaintenanceService {
|
||||
);
|
||||
return { count: impossibleEntries.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* Entries due for a TMDB refresh: never fetched, or last fetched more than
|
||||
* `hours` ago. Entries with auto sync turned off are skipped.
|
||||
* @param {number} [hours=24]
|
||||
*/
|
||||
async getStaleEntries(hours = 24) {
|
||||
const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000);
|
||||
return Entry.findAll({
|
||||
attributes: ["id", "title", "last_fetch"],
|
||||
where: {
|
||||
autoSync: { [Op.not]: false },
|
||||
[Op.or]: [{ last_fetch: null }, { last_fetch: { [Op.lt]: cutoff } }],
|
||||
},
|
||||
order: [["last_fetch", "ASC"]],
|
||||
});
|
||||
}
|
||||
|
||||
/** Current/last stale refresh job, for the status endpoint. */
|
||||
getStaleRefreshStatus() {
|
||||
const job = this.staleRefreshJob;
|
||||
if (!job) return { running: false };
|
||||
return { ...job, failed: job.failed.slice(-50) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts refreshing every stale entry in the background, one at a time.
|
||||
* TMDB requests go through tmdbService's rate limiter, so a large library
|
||||
* is spread out instead of hammering the API.
|
||||
* @param {number} [hours=24]
|
||||
* @returns {Object} the job status, or `{ alreadyRunning: true, ... }`
|
||||
*/
|
||||
async startStaleRefresh(hours = 24) {
|
||||
if (this.staleRefreshJob?.running) {
|
||||
return { alreadyRunning: true, ...this.getStaleRefreshStatus() };
|
||||
}
|
||||
|
||||
const entries = await this.getStaleEntries(hours);
|
||||
const job = {
|
||||
running: true,
|
||||
cancelRequested: false,
|
||||
hours,
|
||||
total: entries.length,
|
||||
done: 0,
|
||||
succeeded: 0,
|
||||
failed: [],
|
||||
current: null,
|
||||
startedAt: new Date(),
|
||||
finishedAt: null,
|
||||
};
|
||||
this.staleRefreshJob = job;
|
||||
logToFile(`Stale refresh started: ${entries.length} entries (> ${hours}h)`);
|
||||
|
||||
// Required lazily: entryManager pulls in most of the services layer.
|
||||
const entryManager = require("./entryManager");
|
||||
|
||||
(async () => {
|
||||
for (const entry of entries) {
|
||||
if (job.cancelRequested) break;
|
||||
job.current = { id: entry.id, title: entry.title };
|
||||
try {
|
||||
await entryManager.refrechEntryById(entry.id, false);
|
||||
job.succeeded++;
|
||||
} catch (error) {
|
||||
job.failed.push({
|
||||
id: entry.id,
|
||||
title: entry.title,
|
||||
error: error.message,
|
||||
});
|
||||
logToFile(
|
||||
`Stale refresh failed for entry ${entry.id} (${entry.title}): ${error.message}`,
|
||||
);
|
||||
}
|
||||
job.done++;
|
||||
}
|
||||
|
||||
job.running = false;
|
||||
job.current = null;
|
||||
job.finishedAt = new Date();
|
||||
logToFile(
|
||||
`Stale refresh ${job.cancelRequested ? "cancelled" : "finished"}: ${job.succeeded} ok, ${job.failed.length} failed of ${job.total}`,
|
||||
);
|
||||
})();
|
||||
|
||||
return this.getStaleRefreshStatus();
|
||||
}
|
||||
|
||||
cancelStaleRefresh() {
|
||||
if (this.staleRefreshJob?.running) {
|
||||
this.staleRefreshJob.cancelRequested = true;
|
||||
}
|
||||
return this.getStaleRefreshStatus();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new MaintenanceService();
|
||||
@@ -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(
|
||||
|
||||
@@ -18,6 +18,13 @@ const EntrySeen = require("../../models/EntrySeen.js");
|
||||
const Episode = require("../../models/Episode.js");
|
||||
const Media = require("../../models/Media.js");
|
||||
const Genre = require("../../models/Genre.js");
|
||||
const {
|
||||
mapEntryFields,
|
||||
mapEntryIds,
|
||||
mapEntryRatings,
|
||||
mapSeasonFields,
|
||||
mapEpisodeFields,
|
||||
} = require("../../mappers/entryMapper.js");
|
||||
|
||||
async function saveEntry(data) {
|
||||
try {
|
||||
@@ -27,29 +34,9 @@ async function saveEntry(data) {
|
||||
var is_tvseries = data.release_date == null ? true : false;
|
||||
|
||||
let movie = Entry.build({
|
||||
title: data.title || data.name,
|
||||
original_title: data.original_title || data.original_name,
|
||||
release_date: data.release_date || data.first_air_date,
|
||||
release_status: data.status,
|
||||
runtime: data.runtime || null,
|
||||
|
||||
tagline: data.tagline || null,
|
||||
storyline: data.overview,
|
||||
country:
|
||||
data.production_countries.length > 0
|
||||
? data.production_countries[0].name
|
||||
: null,
|
||||
|
||||
...mapEntryFields(data),
|
||||
is_tvseries: is_tvseries,
|
||||
watchlist: true,
|
||||
status: data.status,
|
||||
|
||||
genres: data.genre_ids,
|
||||
|
||||
poster_path: data.poster_path,
|
||||
banner_path: data.backdrop_path,
|
||||
|
||||
last_fetch: new Date(),
|
||||
});
|
||||
|
||||
const savedEntry = await movie.save();
|
||||
@@ -58,7 +45,7 @@ async function saveEntry(data) {
|
||||
const ids = await EntryId.create({
|
||||
entry_id: savedEntry.id,
|
||||
tmdb_id: data.id,
|
||||
imdb_id: data.imdb_id,
|
||||
...mapEntryIds(data),
|
||||
});
|
||||
|
||||
// ? genres
|
||||
@@ -73,7 +60,7 @@ async function saveEntry(data) {
|
||||
const ratings = await EntryRating.create({
|
||||
entry_id: savedEntry.id,
|
||||
user_rating: 0,
|
||||
tmdb_rating: data.vote_average,
|
||||
...mapEntryRatings(data),
|
||||
});
|
||||
|
||||
// ! seasons & episodes for tv series
|
||||
@@ -82,21 +69,11 @@ async function saveEntry(data) {
|
||||
let seasons = [];
|
||||
for (const season of data.seasons) {
|
||||
let seasonData = await fetchSeasonData(data.id, season.season_number);
|
||||
if (!seasonData) continue;
|
||||
const savedSeason = await Season.create({
|
||||
tmdb_id: seasonData.id,
|
||||
|
||||
...mapSeasonFields(seasonData),
|
||||
entry_id: savedEntry.id,
|
||||
|
||||
name: seasonData.name,
|
||||
overview: seasonData.overview,
|
||||
season_number: seasonData.season_number,
|
||||
episode_count: seasonData.episodes.length,
|
||||
air_date: seasonData.air_date,
|
||||
|
||||
user_rating: 0,
|
||||
tmdb_rating: seasonData.vote_average,
|
||||
|
||||
poster_path: seasonData.poster_path,
|
||||
banner_path: null,
|
||||
});
|
||||
|
||||
@@ -104,20 +81,8 @@ async function saveEntry(data) {
|
||||
let episodes = [];
|
||||
for (const episode of seasonData.episodes) {
|
||||
const savedEpisode = await Episode.create({
|
||||
tmdb_id: episode.id,
|
||||
|
||||
...mapEpisodeFields(episode),
|
||||
season_id: savedSeason.id,
|
||||
|
||||
name: episode.name,
|
||||
overview: episode.overview,
|
||||
episode_number: episode.episode_number,
|
||||
episode_type: episode.episode_type,
|
||||
runtime: episode.runtime,
|
||||
air_date: episode.air_date,
|
||||
|
||||
tmdb_rating: episode.vote_average,
|
||||
|
||||
still_path: episode.still_path,
|
||||
});
|
||||
|
||||
episodes.push(savedEpisode);
|
||||
@@ -143,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,
|
||||
});
|
||||
@@ -554,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,
|
||||
});
|
||||
|
||||
@@ -50,21 +50,33 @@ class NetworkService {
|
||||
return network;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the network or refreshes its TMDB fields. TMDB sends snake_case
|
||||
* (`origin_country`, `logo_path`); the model attributes are camelCase.
|
||||
* @returns {Promise<[Network, boolean]>} same shape as findOrCreate
|
||||
*/
|
||||
async createOrUpdateNetwork(networkData) {
|
||||
return await Network.findOrCreate({
|
||||
const fields = {
|
||||
name: networkData.name,
|
||||
originCountry: networkData.origin_country || null,
|
||||
logoPath: networkData.logo_path || null,
|
||||
};
|
||||
|
||||
const [network, created] = await Network.findOrCreate({
|
||||
where: { id: networkData.id },
|
||||
defaults: {
|
||||
id: networkData.id,
|
||||
name: networkData.name,
|
||||
|
||||
originCountry: networkData.originCountry,
|
||||
homepage: networkData.homepage,
|
||||
|
||||
logoPath: networkData.logoPath,
|
||||
posterPath: networkData.posterPath,
|
||||
backdropPath: networkData.backdropPath,
|
||||
},
|
||||
defaults: { id: networkData.id, ...fields },
|
||||
});
|
||||
|
||||
if (
|
||||
!created &&
|
||||
(network.name !== fields.name ||
|
||||
network.originCountry !== fields.originCountry ||
|
||||
network.logoPath !== fields.logoPath)
|
||||
) {
|
||||
await network.update(fields);
|
||||
}
|
||||
|
||||
return [network, created];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ class PeopleManager {
|
||||
mediaableId: person.id,
|
||||
type: image.type,
|
||||
path: image.path,
|
||||
tmdbPath: image.tmdb_path || null,
|
||||
isLocal: true,
|
||||
isSelected: true,
|
||||
});
|
||||
|
||||
+186
-206
@@ -5,91 +5,161 @@ const configService = require("./configService");
|
||||
const TMDB_APIURL = configService.getTmdbApiUrl();
|
||||
const TMDB_APIKEY = configService.getTmdbApiKey();
|
||||
|
||||
async function fetchEntryData(tmdb_id, is_tvserie) {
|
||||
try {
|
||||
let type = is_tvserie ? "tv" : "movie";
|
||||
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||
logToFile(`Fetching Entry Data From: ${url}`);
|
||||
let data;
|
||||
await axios.get(url).then((response) => {
|
||||
if (response.status != 200) {
|
||||
logToFile(`Error Fetching Data From: ${url}`);
|
||||
return console.log("Error fetching the data.");
|
||||
}
|
||||
data = response.data;
|
||||
});
|
||||
// ─── Rate limiting ───────────────────────────────────────────────────────────
|
||||
// TMDB allows roughly 50 requests/second per IP. We stay well below that so
|
||||
// bulk jobs (e.g. the stale-entries refresh) never get the IP blocked.
|
||||
const MAX_REQUESTS_PER_WINDOW = 20;
|
||||
const WINDOW_MS = 1000;
|
||||
const MAX_CONCURRENT = 8;
|
||||
const MAX_RETRIES = 4;
|
||||
|
||||
return data;
|
||||
const queue = [];
|
||||
const recentStarts = [];
|
||||
let activeRequests = 0;
|
||||
let wakeTimer = null;
|
||||
|
||||
function scheduleNext() {
|
||||
while (queue.length > 0 && activeRequests < MAX_CONCURRENT) {
|
||||
const now = Date.now();
|
||||
while (recentStarts.length && now - recentStarts[0] >= WINDOW_MS) {
|
||||
recentStarts.shift();
|
||||
}
|
||||
|
||||
if (recentStarts.length >= MAX_REQUESTS_PER_WINDOW) {
|
||||
if (!wakeTimer) {
|
||||
const waitMs = WINDOW_MS - (now - recentStarts[0]) + 5;
|
||||
wakeTimer = setTimeout(() => {
|
||||
wakeTimer = null;
|
||||
scheduleNext();
|
||||
}, waitMs);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
recentStarts.push(now);
|
||||
activeRequests++;
|
||||
const job = queue.shift();
|
||||
job().finally(() => {
|
||||
activeRequests--;
|
||||
scheduleNext();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function enqueue(fn) {
|
||||
return new Promise((resolve, reject) => {
|
||||
queue.push(() => fn().then(resolve, reject));
|
||||
scheduleNext();
|
||||
});
|
||||
}
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function isRetryable(error) {
|
||||
const status = error.response?.status;
|
||||
if (status === 429) return true;
|
||||
if (status >= 500) return true;
|
||||
return !error.response; // network error / timeout
|
||||
}
|
||||
|
||||
/**
|
||||
* Rate-limited GET against the TMDB API. Retries 429s (honouring Retry-After)
|
||||
* and transient failures with backoff. The API key is never logged.
|
||||
* @param {string} path - e.g. "movie/550"
|
||||
* @param {Object} [params] - extra query params
|
||||
* @returns {Promise<Object>} response data
|
||||
*/
|
||||
async function tmdbGet(path, params = {}) {
|
||||
const query = { language: "en-US", ...params };
|
||||
const logQuery = new URLSearchParams(
|
||||
Object.entries(query).filter(([, v]) => v !== undefined),
|
||||
).toString();
|
||||
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try {
|
||||
logToFile(`TMDB GET ${path}?${logQuery}`);
|
||||
const response = await enqueue(() =>
|
||||
axios.get(`${TMDB_APIURL}${path}`, {
|
||||
params: { api_key: TMDB_APIKEY, ...query },
|
||||
timeout: 20000,
|
||||
}),
|
||||
);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
if (attempt >= MAX_RETRIES || !isRetryable(error)) throw error;
|
||||
|
||||
const retryAfter = Number(error.response?.headers?.["retry-after"]);
|
||||
const waitMs =
|
||||
Number.isFinite(retryAfter) && retryAfter > 0
|
||||
? retryAfter * 1000
|
||||
: 1000 * 2 ** (attempt - 1);
|
||||
logToFile(
|
||||
`TMDB GET ${path} failed (${error.response?.status ?? error.code}), retry ${attempt}/${MAX_RETRIES - 1} in ${waitMs}ms`,
|
||||
);
|
||||
await sleep(waitMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs a TMDB request, logging and returning null on failure. */
|
||||
async function safeGet(label, path, params) {
|
||||
try {
|
||||
return await tmdbGet(path, params);
|
||||
} catch (error) {
|
||||
console.log("Error fetching the entry data.", error);
|
||||
logToFile(
|
||||
`Error fetching ${label} (${path}): ${error.response?.status ?? ""} ${error.message}`,
|
||||
);
|
||||
console.log(`Error fetching ${label}.`, error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Entries ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Fetches movie/TV details plus everything we store from the same request:
|
||||
* external ids, certification, keywords, videos, watch providers and
|
||||
* alternative titles.
|
||||
*/
|
||||
async function fetchEntryData(tmdb_id, is_tvserie) {
|
||||
const type = is_tvserie ? "tv" : "movie";
|
||||
const appends = [
|
||||
"external_ids",
|
||||
is_tvserie ? "content_ratings" : "release_dates",
|
||||
"keywords",
|
||||
"videos",
|
||||
"watch/providers",
|
||||
"alternative_titles",
|
||||
];
|
||||
return safeGet("entry data", `${type}/${tmdb_id}`, {
|
||||
append_to_response: appends.join(","),
|
||||
include_video_language: "en,null",
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchSeasonData(tmdbTvId, seasonNumber) {
|
||||
// fetching the informations
|
||||
try {
|
||||
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||
logToFile(`Fetching Season Data From: ${url}`);
|
||||
let data;
|
||||
await axios.get(url).then((response) => {
|
||||
if (response.status != 200) {
|
||||
logToFile(`Error Fetching Data From: ${url}`);
|
||||
return console.log("Error fetching the data.");
|
||||
}
|
||||
data = response.data;
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching the data.");
|
||||
return null;
|
||||
}
|
||||
return safeGet("season data", `tv/${tmdbTvId}/season/${seasonNumber}`, {
|
||||
append_to_response: "external_ids",
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchEntryMedia(tmdb_id, is_tvserie) {
|
||||
try {
|
||||
let type = is_tvserie ? "tv" : "movie";
|
||||
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`;
|
||||
logToFile(`Fetching Entry Media Data From: ${url}`);
|
||||
let data;
|
||||
await axios.get(url).then((response) => {
|
||||
if (response.status != 200) {
|
||||
logToFile(`Error Fetching Data From: ${url}`);
|
||||
return console.log("Error fetching the data.");
|
||||
}
|
||||
data = response.data;
|
||||
});
|
||||
const type = is_tvserie ? "tv" : "movie";
|
||||
// Images are language-agnostic, so don't send language=en-US
|
||||
return safeGet("entry media", `${type}/${tmdb_id}/images`, {
|
||||
language: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching the entry media.", error);
|
||||
return null;
|
||||
}
|
||||
async function fetchEntryRecommendations(tmdb_id, is_tvserie, page = 1) {
|
||||
const type = is_tvserie ? "tv" : "movie";
|
||||
return safeGet("recommendations", `${type}/${tmdb_id}/recommendations`, {
|
||||
page,
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchCollectionData(collectionId) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||
logToFile(`Fetching Collection Data From: ${url}`);
|
||||
let data;
|
||||
await axios.get(url).then((response) => {
|
||||
if (response.status != 200)
|
||||
return console.log(
|
||||
"Error fetching collection data from tmdb:",
|
||||
response,
|
||||
);
|
||||
data = response.data;
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
if (response.status != 200) {
|
||||
logToFile(`Error Fetching Data From: ${url}`);
|
||||
return console.log("Error fetching the data.");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return safeGet("collection data", `collection/${collectionId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -99,158 +169,68 @@ async function fetchCollectionData(collectionId) {
|
||||
* @returns {Promise<Object|null>} - The credits data or null if there's an error
|
||||
*/
|
||||
async function fetchEntryCredits(tmdb_id, is_tvserie) {
|
||||
try {
|
||||
let type = is_tvserie ? "tv" : "movie";
|
||||
let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||
|
||||
if (is_tvserie) {
|
||||
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||
}
|
||||
|
||||
logToFile(`Fetching Entry Credits From: ${url}`);
|
||||
|
||||
let data;
|
||||
await axios.get(url).then((response) => {
|
||||
if (response.status != 200) {
|
||||
logToFile(`Error Fetching Credits From: ${url}`);
|
||||
return console.log("Error fetching the credits data.");
|
||||
}
|
||||
data = response.data;
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching the entry credits.", error);
|
||||
return null;
|
||||
}
|
||||
const path = is_tvserie
|
||||
? `tv/${tmdb_id}/aggregate_credits`
|
||||
: `movie/${tmdb_id}/credits`;
|
||||
return safeGet("entry credits", path);
|
||||
}
|
||||
|
||||
// ─── People ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Fetches detailed information about a person
|
||||
* @param {number} tmdb_id - The TMDB ID of the person
|
||||
* @returns {Promise<Object|null>} - The person data or null if there's an error
|
||||
*/
|
||||
async function fetchPersonDetails(tmdb_id) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}person/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US&append_to_response=external_ids`;
|
||||
logToFile(`Fetching Person Details From: ${url}`);
|
||||
|
||||
let data;
|
||||
await axios.get(url).then((response) => {
|
||||
if (response.status != 200) {
|
||||
logToFile(`Error Fetching Person Details From: ${url}`);
|
||||
return console.log("Error fetching the person data.");
|
||||
}
|
||||
data = response.data;
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching the person details.", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchTrending(type, page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}trending/${type}/week?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
|
||||
logToFile(`Fetching Trending ${type} From: ${url}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log(`Error fetching trending ${type}.`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPopular(type, page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}${type}/popular?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
|
||||
logToFile(`Fetching Popular ${type} From: ${url}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log(`Error fetching popular ${type}.`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchTopRated(type, page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}${type}/top_rated?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
|
||||
logToFile(`Fetching Top Rated ${type} From: ${url}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log(`Error fetching top rated ${type}.`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchUpcoming(page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}movie/upcoming?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
|
||||
logToFile(`Fetching Upcoming Movies From: ${url}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching upcoming movies.", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function searchMulti(query, page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}search/multi?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`;
|
||||
logToFile(`Searching TMDB for: ${query}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log("Error searching TMDB.", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function searchPeople(query, page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}search/person?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`;
|
||||
logToFile(`Searching TMDB People for: ${query}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log("Error searching TMDB people.", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchPopularPeople(page = 1) {
|
||||
try {
|
||||
let url = `${TMDB_APIURL}person/popular?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
|
||||
logToFile(`Fetching Popular People From: ${url}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching popular people.", error);
|
||||
return null;
|
||||
}
|
||||
return safeGet("person details", `person/${tmdb_id}`, {
|
||||
append_to_response: "external_ids",
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchPersonCombinedCredits(tmdb_id) {
|
||||
try {
|
||||
const url = `${TMDB_APIURL}person/${tmdb_id}/combined_credits?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||
logToFile(`Fetching Person Combined Credits From: ${url}`);
|
||||
const response = await axios.get(url);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.log("Error fetching person combined credits.", error);
|
||||
return null;
|
||||
}
|
||||
return safeGet(
|
||||
"person combined credits",
|
||||
`person/${tmdb_id}/combined_credits`,
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Lists & search ──────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchTrending(type, page = 1) {
|
||||
return safeGet(`trending ${type}`, `trending/${type}/week`, { page });
|
||||
}
|
||||
|
||||
async function fetchPopular(type, page = 1) {
|
||||
return safeGet(`popular ${type}`, `${type}/popular`, { page });
|
||||
}
|
||||
|
||||
async function fetchTopRated(type, page = 1) {
|
||||
return safeGet(`top rated ${type}`, `${type}/top_rated`, { page });
|
||||
}
|
||||
|
||||
async function fetchUpcoming(page = 1) {
|
||||
return safeGet("upcoming movies", "movie/upcoming", { page });
|
||||
}
|
||||
|
||||
async function searchMulti(query, page = 1) {
|
||||
return safeGet("search", "search/multi", { query, page });
|
||||
}
|
||||
|
||||
async function searchPeople(query, page = 1) {
|
||||
return safeGet("people search", "search/person", { query, page });
|
||||
}
|
||||
|
||||
async function fetchPopularPeople(page = 1) {
|
||||
return safeGet("popular people", "person/popular", { page });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
tmdbGet,
|
||||
fetchEntryData,
|
||||
fetchSeasonData,
|
||||
fetchEntryMedia,
|
||||
fetchEntryRecommendations,
|
||||
fetchCollectionData,
|
||||
fetchEntryCredits,
|
||||
fetchPersonDetails,
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
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,
|
||||
ArtworkResponse,
|
||||
ArtworkType,
|
||||
Media,
|
||||
} from "@/types";
|
||||
|
||||
export const entriesApi = {
|
||||
getAll: () =>
|
||||
@@ -58,6 +67,29 @@ 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),
|
||||
|
||||
getTmdbRecommendations: (type: "movie" | "tv", tmdbId: number) =>
|
||||
api
|
||||
.get<TmdbPaginatedResponse<TmdbEntry>>(
|
||||
`/entries/tmdb/recommendations/${type}/${tmdbId}`,
|
||||
)
|
||||
.then((r) => r.data),
|
||||
|
||||
getArtwork: (id: number) =>
|
||||
api.get<ArtworkResponse>(`/entries/${id}/artwork`).then((r) => r.data),
|
||||
|
||||
getTmdbArtwork: (type: "movie" | "tv", tmdbId: number) =>
|
||||
api
|
||||
.get<ArtworkResponse>(`/entries/tmdb/artwork/${type}/${tmdbId}`)
|
||||
.then((r) => r.data),
|
||||
|
||||
addArtwork: (id: number, data: { type: ArtworkType; file_path: string }) =>
|
||||
api.post<Media>(`/entries/${id}/artwork`, data).then((r) => r.data),
|
||||
|
||||
syncSeries: () => api.get("/entries/sync-series").then((r) => r.data),
|
||||
|
||||
previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
|
||||
|
||||
@@ -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),
|
||||
|
||||
|
||||
@@ -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<ArtworkType>("poster");
|
||||
const [language, setLanguage] = useState("all");
|
||||
const [libraryOnly, setLibraryOnly] = useState(false);
|
||||
const [rows, setRows] = useState(ROWS_STEP);
|
||||
const [pendingPath, setPendingPath] = useState<string | null>(null);
|
||||
const [viewing, setViewing] = useState<ArtworkItem | null>(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<string, number>();
|
||||
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 (
|
||||
<section className="space-y-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 className="text-lg font-semibold">Artwork</h3>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<select
|
||||
value={language}
|
||||
onChange={(e) => {
|
||||
setLanguage(e.target.value);
|
||||
setRows(ROWS_STEP);
|
||||
}}
|
||||
className="h-8 rounded-md border border-border/60 bg-background px-2 text-xs"
|
||||
aria-label="Language"
|
||||
>
|
||||
<option value="all">All languages</option>
|
||||
{languages.map(([lang, count]) => (
|
||||
<option key={lang} value={lang}>
|
||||
{lang === "none" ? "No text" : languageName(lang)} ({count})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{isLibrary && (
|
||||
<Button
|
||||
variant={libraryOnly ? "default" : "outline"}
|
||||
size="sm"
|
||||
aria-pressed={libraryOnly}
|
||||
onClick={() => {
|
||||
setLibraryOnly((v) => !v);
|
||||
setRows(ROWS_STEP);
|
||||
}}
|
||||
>
|
||||
<Check />
|
||||
In library
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs
|
||||
value={activeType}
|
||||
onValueChange={(v) => changeType(v as ArtworkType)}
|
||||
>
|
||||
<TabsList>
|
||||
{TYPES.map((t) => (
|
||||
<TabsTrigger key={t.type} value={t.type}>
|
||||
{t.label}
|
||||
{data && (
|
||||
<span className="ml-1 text-muted-foreground tabular-nums">
|
||||
{data[t.key].length}
|
||||
</span>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
{isLoading ? (
|
||||
<div className={`grid gap-3 ${config.grid}`}>
|
||||
{Array.from({ length: columns * ROWS_STEP }).map((_, i) => (
|
||||
<Skeleton key={i} className={`${config.aspect} rounded-lg`} />
|
||||
))}
|
||||
</div>
|
||||
) : filtered.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No {config.label.toLowerCase()} match these filters.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<div className={`grid gap-3 ${config.grid}`}>
|
||||
{filtered.slice(0, visible).map((item) => (
|
||||
<ArtworkTile
|
||||
key={itemKey(item)}
|
||||
item={item}
|
||||
type={activeType}
|
||||
thumbSize={config.thumbSize}
|
||||
aspect={config.aspect}
|
||||
canAdd={isLibrary}
|
||||
adding={pendingPath === item.file_path}
|
||||
onAdd={() => add(item)}
|
||||
onOpen={() => setViewing(item)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{filtered.length > visible && (
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setRows((r) => r + ROWS_STEP)}
|
||||
>
|
||||
Show more ({filtered.length - visible} left)
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={!!viewing}
|
||||
onOpenChange={(open) => !open && setViewing(null)}
|
||||
>
|
||||
<DialogContent className="w-auto max-w-[calc(100%-2rem)] sm:max-w-[calc(100%-2rem)] gap-3 p-3">
|
||||
<DialogTitle className="sr-only">{config.label} preview</DialogTitle>
|
||||
{viewing && (
|
||||
<>
|
||||
<img
|
||||
src={imageUrls(viewing, activeType, config.thumbSize).full}
|
||||
alt=""
|
||||
className={`max-h-[80vh] max-w-full rounded-lg object-contain ${
|
||||
activeType === "logo" ? `${CHECKER} p-4` : ""
|
||||
}`}
|
||||
/>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{viewing.width && viewing.height
|
||||
? `${viewing.width}×${viewing.height}`
|
||||
: "Local file"}
|
||||
{viewing.file_path &&
|
||||
` · ${viewing.language ? languageName(viewing.language) : "No text"}`}
|
||||
</span>
|
||||
{viewing.in_library ? (
|
||||
<LibraryBadge selected={viewing.is_selected} />
|
||||
) : (
|
||||
isLibrary &&
|
||||
viewing.file_path && (
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => add(viewing)}
|
||||
disabled={pendingPath === viewing.file_path}
|
||||
>
|
||||
{pendingPath === viewing.file_path ? (
|
||||
<Loader2 className="animate-spin" />
|
||||
) : (
|
||||
<Download />
|
||||
)}
|
||||
Add to library
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function LibraryBadge({ selected }: { selected?: boolean }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow">
|
||||
<Check className="h-3 w-3" />
|
||||
{selected ? "Selected" : "In library"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div
|
||||
className={`group relative overflow-hidden rounded-lg bg-muted ring-1 ${
|
||||
item.in_library ? "ring-emerald-500/60" : "ring-border/60"
|
||||
} ${aspect}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="block h-full w-full cursor-zoom-in"
|
||||
aria-label="View full size"
|
||||
>
|
||||
<img
|
||||
src={thumb}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
className={`h-full w-full transition-transform duration-300 group-hover:scale-[1.03] ${
|
||||
type === "logo" ? `${CHECKER} object-contain p-3` : "object-cover"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Top: library badge / language */}
|
||||
<div className="pointer-events-none absolute inset-x-1.5 top-1.5 flex items-start justify-between gap-1">
|
||||
{item.in_library ? (
|
||||
<LibraryBadge selected={item.is_selected} />
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
{item.file_path && item.language && (
|
||||
<span className="rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase text-white">
|
||||
{item.language}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bottom: votes + add */}
|
||||
<div className="absolute inset-x-1.5 bottom-1.5 flex items-end justify-between gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
|
||||
{item.vote_count > 0 ? (
|
||||
<span className="inline-flex items-center gap-0.5 rounded bg-black/60 px-1.5 py-0.5 text-[10px] text-white tabular-nums">
|
||||
<Star className="h-2.5 w-2.5 fill-yellow-400 text-yellow-400" />
|
||||
{item.vote_average.toFixed(1)}
|
||||
</span>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
{canAdd && !item.in_library && item.file_path && (
|
||||
<Button
|
||||
size="xs"
|
||||
onClick={onAdd}
|
||||
disabled={adding}
|
||||
className="shadow"
|
||||
aria-label="Add to library"
|
||||
>
|
||||
{adding ? <Loader2 className="animate-spin" /> : <Download />}
|
||||
Add
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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,55 @@
|
||||
import {
|
||||
useEntryRecommendations,
|
||||
useTmdbRecommendations,
|
||||
} 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. Pass `entryId` for a library
|
||||
* entry, or `tmdbId` for one that is not in the library.
|
||||
*/
|
||||
export function RecommendationsSection({
|
||||
entryId = 0,
|
||||
tmdbId = 0,
|
||||
isTvSeries,
|
||||
}: {
|
||||
entryId?: number;
|
||||
tmdbId?: number;
|
||||
isTvSeries: boolean;
|
||||
}) {
|
||||
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;
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,19 @@ 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,
|
||||
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,
|
||||
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,
|
||||
};
|
||||
@@ -43,6 +49,61 @@ 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 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),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
useEntrySeasons,
|
||||
useRefreshEntry,
|
||||
useEntryCredits,
|
||||
useTmdbPreview,
|
||||
useCreateEntry,
|
||||
} from "@/hooks/useEntries";
|
||||
import { useEntrySeenByEntry, useDeleteEntrySeen } from "@/hooks/useEntrySeen";
|
||||
import { useCollections } from "@/hooks/useCollections";
|
||||
@@ -38,6 +40,14 @@ import {
|
||||
Tv,
|
||||
Clock,
|
||||
CalendarDays,
|
||||
Globe,
|
||||
Languages,
|
||||
Building2,
|
||||
DollarSign,
|
||||
ListVideo,
|
||||
CircleDot,
|
||||
Plus,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -47,6 +57,10 @@ 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 { ArtworkSection } from "@/components/entries/ArtworkSection";
|
||||
import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog";
|
||||
import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog";
|
||||
import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog";
|
||||
@@ -61,6 +75,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
|
||||
import { getTmdbImageUrl } from "@/lib/api";
|
||||
import {
|
||||
getPosterUrl,
|
||||
getFullPosterUrl,
|
||||
@@ -71,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 = [
|
||||
{
|
||||
@@ -108,25 +129,80 @@ 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;
|
||||
}
|
||||
})();
|
||||
|
||||
/**
|
||||
* 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);
|
||||
@@ -137,6 +213,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
|
||||
@@ -144,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 (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-20">
|
||||
<p className="text-muted-foreground">Could not load entry from TMDB.</p>
|
||||
<Button variant="outline" onClick={() => navigate(-1)}>
|
||||
Go back
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
(isLibrary ? isLoading : previewLoading) ||
|
||||
!displayEntry ||
|
||||
libraryMatch
|
||||
) {
|
||||
return <EntryDetailsSkeleton />;
|
||||
}
|
||||
|
||||
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(
|
||||
@@ -171,6 +283,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,12 +360,17 @@ 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}
|
||||
</span>
|
||||
)}
|
||||
{e.is_tvseries && (
|
||||
{e.is_tvseries && isLibrary && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowStatusDialog(true)}
|
||||
@@ -251,6 +389,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}
|
||||
@@ -277,17 +420,36 @@ export function EntryDetailsPage() {
|
||||
{e.runtime && !e.is_tvseries && (
|
||||
<MetaItem>{formatRuntime(e.runtime)}</MetaItem>
|
||||
)}
|
||||
{e.is_tvseries && seasons && seasons.length > 0 && (
|
||||
{e.is_tvseries && seasonCount > 0 && (
|
||||
<MetaItem>
|
||||
{seasons.length}{" "}
|
||||
{seasons.length === 1 ? "season" : "seasons"}
|
||||
{seasonCount} {seasonCount === 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{" "}
|
||||
<Link
|
||||
to={`/people/${director.people_id}`}
|
||||
to={
|
||||
isLibrary
|
||||
? `/people/${director.people_id}`
|
||||
: `/people/tmdb/${director.people_id}`
|
||||
}
|
||||
className="font-medium text-foreground hover:underline"
|
||||
>
|
||||
{director.people.name}
|
||||
@@ -313,125 +475,154 @@ 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>
|
||||
{isLibrary ? (
|
||||
<StreamingSection entry={e} seasons={seasons} />
|
||||
) : (
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={addToLibrary}
|
||||
disabled={createEntry.isPending}
|
||||
className="h-11 gap-2 px-6 text-sm font-medium"
|
||||
>
|
||||
{createEntry.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="h-4 w-4" />
|
||||
)}
|
||||
{createEntry.isPending ? "Adding..." : "Add to Library"}
|
||||
</Button>
|
||||
)}
|
||||
{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
|
||||
label="Mark as watched"
|
||||
onClick={() => setShowSeenDialog(true)}
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</IconAction>
|
||||
<IconAction
|
||||
label={userRating > 0 ? "Change rating" : "Rate this"}
|
||||
onClick={() => setShowRatingDialog(true)}
|
||||
active={userRating > 0}
|
||||
>
|
||||
<Star
|
||||
className={`h-4 w-4 ${userRating > 0 ? "fill-yellow-400 text-yellow-400" : ""}`}
|
||||
/>
|
||||
</IconAction>
|
||||
<IconAction
|
||||
label={
|
||||
e.favorit ? "Remove from favorites" : "Add to favorites"
|
||||
}
|
||||
onClick={toggleFavorite}
|
||||
disabled={updateEntry.isPending}
|
||||
active={e.favorit}
|
||||
>
|
||||
<Heart
|
||||
className={`h-4 w-4 ${e.favorit ? "fill-red-500 text-red-500" : ""}`}
|
||||
/>
|
||||
</IconAction>
|
||||
<IconAction
|
||||
label="Add to collection"
|
||||
onClick={() => setShowCollectionDialog(true)}
|
||||
>
|
||||
<FolderPlus className="h-4 w-4" />
|
||||
</IconAction>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
className="h-11 w-11 rounded-full border-border/60 bg-background/60 backdrop-blur"
|
||||
aria-label="More actions"
|
||||
/>
|
||||
}
|
||||
{isLibrary && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<IconAction
|
||||
label="Mark as watched"
|
||||
onClick={() => setShowSeenDialog(true)}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{e.is_tvseries ? (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowStatusDialog(true)}
|
||||
>
|
||||
<BookmarkCheck className="mr-2 h-4 w-4" />
|
||||
Set status
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowWatchHistoryDialog(true)}
|
||||
>
|
||||
<History className="mr-2 h-4 w-4" />
|
||||
Watch history
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateEntry.mutate({
|
||||
id: e.id,
|
||||
data: { hidden: !e.hidden },
|
||||
})
|
||||
<Eye className="h-4 w-4" />
|
||||
</IconAction>
|
||||
<IconAction
|
||||
label={userRating > 0 ? "Change rating" : "Rate this"}
|
||||
onClick={() => setShowRatingDialog(true)}
|
||||
active={userRating > 0}
|
||||
>
|
||||
<Star
|
||||
className={`h-4 w-4 ${userRating > 0 ? "fill-yellow-400 text-yellow-400" : ""}`}
|
||||
/>
|
||||
</IconAction>
|
||||
<IconAction
|
||||
label={
|
||||
e.favorit ? "Remove from favorites" : "Add to favorites"
|
||||
}
|
||||
onClick={toggleFavorite}
|
||||
disabled={updateEntry.isPending}
|
||||
active={e.favorit}
|
||||
>
|
||||
<Heart
|
||||
className={`h-4 w-4 ${e.favorit ? "fill-red-500 text-red-500" : ""}`}
|
||||
/>
|
||||
</IconAction>
|
||||
<IconAction
|
||||
label="Add to collection"
|
||||
onClick={() => setShowCollectionDialog(true)}
|
||||
>
|
||||
<FolderPlus className="h-4 w-4" />
|
||||
</IconAction>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
className="h-11 w-11 rounded-full border-border/60 bg-background/60 backdrop-blur"
|
||||
aria-label="More actions"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<EyeOff className="mr-2 h-4 w-4" />
|
||||
{e.hidden ? "Unhide" : "Hide"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => refreshEntry.mutate(e.id)}
|
||||
disabled={refreshEntry.isPending}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{refreshEntry.isPending
|
||||
? "Refreshing..."
|
||||
: "Refresh details"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowMediaDialog(true)}
|
||||
>
|
||||
<ImageIcon className="mr-2 h-4 w-4" />
|
||||
Manage media
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShowSettings(true)}>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setShowDeleteConfirm(true)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete entry
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
{e.is_tvseries ? (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowStatusDialog(true)}
|
||||
>
|
||||
<BookmarkCheck className="mr-2 h-4 w-4" />
|
||||
Set status
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowWatchHistoryDialog(true)}
|
||||
>
|
||||
<History className="mr-2 h-4 w-4" />
|
||||
Watch history
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateEntry.mutate({
|
||||
id: e.id,
|
||||
data: { hidden: !e.hidden },
|
||||
})
|
||||
}
|
||||
>
|
||||
<EyeOff className="mr-2 h-4 w-4" />
|
||||
{e.hidden ? "Unhide" : "Hide"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => refreshEntry.mutate(e.id)}
|
||||
disabled={refreshEntry.isPending}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? "animate-spin" : ""}`}
|
||||
/>
|
||||
{refreshEntry.isPending
|
||||
? "Refreshing..."
|
||||
: "Refresh details"}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setShowMediaDialog(true)}
|
||||
>
|
||||
<ImageIcon className="mr-2 h-4 w-4" />
|
||||
Manage media
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShowSettings(true)}>
|
||||
<Settings className="mr-2 h-4 w-4" />
|
||||
Settings
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => setShowDeleteConfirm(true)}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete entry
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -449,25 +640,63 @@ 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}
|
||||
entryId={e.id}
|
||||
entryId={isLibrary ? e.id : undefined}
|
||||
isTvSeries={e.is_tvseries}
|
||||
maxItems={12}
|
||||
allCastHref={
|
||||
isLibrary
|
||||
? undefined
|
||||
: `/entry/tmdb/${tmdbType}/${previewTmdbId}/cast`
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{e.is_tvseries && seasons && seasons.length > 0 && (
|
||||
{isLibrary && e.is_tvseries && seasons && seasons.length > 0 && (
|
||||
<SeasonsContainer seasons={seasons} entryId={e.id} />
|
||||
)}
|
||||
{!isLibrary && e.is_tvseries && previewSeasons.length > 0 && (
|
||||
<TmdbSeasonsStrip seasons={previewSeasons} />
|
||||
)}
|
||||
|
||||
<EntryCollectionsSection entryId={e.id} />
|
||||
{isLibrary && <EntryCollectionsSection entryId={e.id} />}
|
||||
|
||||
<RecommendationsSection
|
||||
entryId={isLibrary ? e.id : 0}
|
||||
tmdbId={isLibrary ? 0 : previewTmdbId}
|
||||
isTvSeries={e.is_tvseries}
|
||||
/>
|
||||
|
||||
<ArtworkSection
|
||||
entryId={isLibrary ? e.id : 0}
|
||||
tmdbId={isLibrary ? 0 : previewTmdbId}
|
||||
isTvSeries={e.is_tvseries}
|
||||
originalLanguage={e.original_language}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Sidebar ── */}
|
||||
<aside className="space-y-4 lg:sticky lg:top-6 lg:self-start">
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div
|
||||
className={`grid gap-2 ${isLibrary ? "grid-cols-3" : "grid-cols-2"}`}
|
||||
>
|
||||
<RatingTile
|
||||
label="IMDb"
|
||||
value={
|
||||
@@ -485,14 +714,21 @@ 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"
|
||||
value={userRating > 0 ? String(userRating) : null}
|
||||
accent="text-primary"
|
||||
emptyLabel="Rate"
|
||||
onClick={() => setShowRatingDialog(true)}
|
||||
/>
|
||||
{isLibrary && (
|
||||
<RatingTile
|
||||
label="You"
|
||||
value={userRating > 0 ? String(userRating) : null}
|
||||
accent="text-primary"
|
||||
emptyLabel="Rate"
|
||||
onClick={() => setShowRatingDialog(true)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border border-border/60 bg-card/50 p-4">
|
||||
@@ -510,9 +746,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 && (
|
||||
@@ -520,7 +827,7 @@ export function EntryDetailsPage() {
|
||||
{e.country}
|
||||
</DetailRow>
|
||||
)}
|
||||
{!e.is_tvseries && (
|
||||
{isLibrary && !e.is_tvseries && (
|
||||
<DetailRow icon={<Eye />} label="Watched">
|
||||
{watchHistory.length > 0 ? (
|
||||
<button
|
||||
@@ -545,8 +852,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 +870,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 +972,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 +1083,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 +1110,11 @@ function RatingTile({
|
||||
{emptyLabel}
|
||||
</span>
|
||||
)}
|
||||
{sub && (
|
||||
<span className="text-[10px] text-muted-foreground tabular-nums">
|
||||
{sub}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
const className =
|
||||
@@ -834,6 +1173,38 @@ function ExternalChip({
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- TMDB seasons (entries not in the library) ---------- */
|
||||
function TmdbSeasonsStrip({ seasons }: { seasons: TmdbPreviewSeason[] }) {
|
||||
return (
|
||||
<Section title="Seasons">
|
||||
<ScrollArea className="w-full">
|
||||
<div className="flex gap-3 pb-4">
|
||||
{seasons.map((s) => (
|
||||
<div key={s.id} className="w-32 shrink-0 space-y-1.5">
|
||||
<div className="aspect-2/3 overflow-hidden rounded-lg bg-muted ring-1 ring-border/60">
|
||||
{s.poster_path && (
|
||||
<img
|
||||
src={getTmdbImageUrl(s.poster_path, "w342")}
|
||||
alt={s.name}
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className="line-clamp-1 text-sm font-medium">{s.name}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{s.episode_count} eps
|
||||
{s.air_date && ` · ${getYear(s.air_date)}`}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
</ScrollArea>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Collections section ---------- */
|
||||
function EntryCollectionsSection({ entryId }: { entryId: number }) {
|
||||
const { data: allCollections = [], isLoading } = useCollections();
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useEffect } from "react";
|
||||
import { useTmdbPreview, useCreateEntry } from "@/hooks/useEntries";
|
||||
import { useLibraryStore } from "@/stores/useLibraryStore";
|
||||
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Plus, Loader2, ExternalLink } from "lucide-react";
|
||||
import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
|
||||
import { CastList } from "@/components/entries/CastList";
|
||||
import { getYear, formatRuntime } from "@/lib/media-utils";
|
||||
import type { Credit } from "@/types";
|
||||
|
||||
const TMDB_IMG = "https://image.tmdb.org/t/p";
|
||||
|
||||
export function TmdbPreviewPage() {
|
||||
const { type, tmdbId } = useParams<{ type: string; tmdbId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const tmdbIdNum = parseInt(tmdbId!, 10);
|
||||
const mediaType = type as "movie" | "tv";
|
||||
|
||||
const {
|
||||
data: preview,
|
||||
isLoading,
|
||||
isError,
|
||||
} = useTmdbPreview(tmdbIdNum, mediaType);
|
||||
const createEntry = useCreateEntry();
|
||||
|
||||
// Check if already in library
|
||||
const libraryEntry = useLibraryStore((s) => {
|
||||
for (const e of s.entries.values()) {
|
||||
if (e.entryIds?.tmdb_id === tmdbIdNum) return e;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
// Redirect immediately if entry is already in library — skip the preview step
|
||||
useEffect(() => {
|
||||
if (libraryEntry) {
|
||||
navigate(`/entry/${libraryEntry.id}`, { replace: true });
|
||||
}
|
||||
}, [libraryEntry, navigate]);
|
||||
|
||||
// Track recently viewed for command palette
|
||||
const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed);
|
||||
useEffect(() => {
|
||||
if (preview) {
|
||||
addRecentlyViewed({
|
||||
id: `tmdb-${tmdbIdNum}`,
|
||||
title: preview.title,
|
||||
type: mediaType,
|
||||
poster_path: preview.poster_path,
|
||||
libraryId: libraryEntry?.id,
|
||||
tmdbId: tmdbIdNum,
|
||||
});
|
||||
}
|
||||
}, [tmdbIdNum, preview?.title]);
|
||||
|
||||
if (isLoading || !preview) {
|
||||
return <EntryDetailsSkeleton />;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-4 py-20">
|
||||
<p className="text-muted-foreground">Could not load entry from TMDB.</p>
|
||||
<Button variant="outline" onClick={() => navigate(-1)}>
|
||||
Go back
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div>
|
||||
{/* Backdrop banner */}
|
||||
<div className="relative -mx-6 -mt-6 h-52 overflow-hidden">
|
||||
{backdrop ? (
|
||||
<img
|
||||
src={backdrop}
|
||||
alt=""
|
||||
className="h-full w-full object-cover opacity-25 blur-sm scale-105"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full w-full bg-linear-to-br from-primary/15 to-primary/5" />
|
||||
)}
|
||||
<div className="absolute inset-0 bg-linear-to-t from-background via-background/60 to-transparent" />
|
||||
</div>
|
||||
|
||||
{/* Main content */}
|
||||
<div className="mx-auto max-w-4xl">
|
||||
{/* Add to Library button — top right */}
|
||||
<div className="flex justify-end gap-2 -mt-10 relative z-10 mb-2">
|
||||
{libraryEntry ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate(`/entry/${libraryEntry.id}`)}
|
||||
>
|
||||
Already in Library — View
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleAddToLibrary}
|
||||
disabled={createEntry.isPending}
|
||||
>
|
||||
{createEntry.isPending ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{createEntry.isPending ? "Adding..." : "Add to Library"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Two-column header: poster | info */}
|
||||
<div className="flex flex-col gap-6 relative items-start sm:flex-row sm:gap-8 sm:-mt-8">
|
||||
{/* LEFT: Poster */}
|
||||
<div className="w-32 sm:w-44 shrink-0 self-start mx-auto sm:mx-0">
|
||||
<img
|
||||
src={poster}
|
||||
alt={preview.title}
|
||||
className="w-full aspect-2/3 rounded-xl object-cover shadow-2xl ring-1 ring-border/50"
|
||||
/>
|
||||
{/* External links */}
|
||||
<div className="flex items-center justify-center gap-3 mt-3">
|
||||
{preview.tmdb_id && (
|
||||
<a
|
||||
href={`https://www.themoviedb.org/${preview.is_tvseries ? "tv" : "movie"}/${preview.tmdb_id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
TMDB
|
||||
</a>
|
||||
)}
|
||||
{preview.imdb_id && (
|
||||
<a
|
||||
href={`https://www.imdb.com/title/${preview.imdb_id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
IMDb
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* RIGHT: Info */}
|
||||
<div className="flex-1 min-w-0 space-y-4">
|
||||
{/* Title */}
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold leading-tight">
|
||||
{preview.title}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
{/* Meta */}
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
|
||||
{preview.release_date && (
|
||||
<span>{getYear(preview.release_date)}</span>
|
||||
)}
|
||||
{preview.is_tvseries && preview.status && (
|
||||
<>
|
||||
<span>•</span>
|
||||
<span>{preview.status}</span>
|
||||
</>
|
||||
)}
|
||||
{preview.runtime && !preview.is_tvseries && (
|
||||
<>
|
||||
{preview.release_date && <span>•</span>}
|
||||
<span>{formatRuntime(preview.runtime)}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* TV series season count */}
|
||||
{preview.is_tvseries && preview.number_of_seasons != null && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">
|
||||
{preview.number_of_seasons}{" "}
|
||||
{preview.number_of_seasons === 1 ? "Season" : "Seasons"}
|
||||
</Badge>
|
||||
{preview.number_of_episodes != null && (
|
||||
<span className="text-muted-foreground">
|
||||
({preview.number_of_episodes} episodes)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Genres */}
|
||||
{preview.genres.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{preview.genres.map((g) => (
|
||||
<Badge key={g.id} variant="outline" className="text-xs">
|
||||
{g.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rating */}
|
||||
{preview.vote_average != null && preview.vote_average > 0 && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-blue-500/10 border border-blue-500/20 px-3 py-1 text-sm text-blue-600 dark:text-blue-400 font-medium">
|
||||
<span className="font-bold">TMDB:</span>
|
||||
{preview.vote_average.toFixed(1)}/10
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Storyline */}
|
||||
{preview.storyline && (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed max-w-prose">
|
||||
{preview.storyline}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sections */}
|
||||
<div className="mt-10 space-y-8">
|
||||
{preview.credits && preview.credits.length > 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<CastList
|
||||
credits={preview.credits as unknown as Credit[]}
|
||||
maxItems={12}
|
||||
allCastHref={`/entry/tmdb/${mediaType}/${tmdbIdNum}/cast`}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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: (
|
||||
<SuspensePage fallback={<EntryDetailsSkeleton />}>
|
||||
<TmdbPreviewPage />
|
||||
<EntryDetailsPage />
|
||||
</SuspensePage>
|
||||
),
|
||||
},
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -325,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[];
|
||||
}
|
||||
Reference in new issue
Block a user