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();