const Collection = require("../models/Collection"); const Entry = require("../models/Entry"); const EntryId = require("../models/EntryId"); const EntryRating = require("../models/EntryRating"); const EntrySeen = require("../models/EntrySeen"); const EntryGenre = require("../models/EntryGenre.js"); const Genre = require("../models/Genre"); const Media = require("../models/Media"); const Season = require("../models/Season"); const Episode = require("../models/Episode"); const BadRequestError = require("../errors/BadRequestError"); const NotFoundError = require("../errors/NotFoundError"); const mediaOptimizerService = require("./mediaOptimizerService.js"); const mediaManager = require("./mediaManager.js"); const { fetchSeasonData, fetchEntryCredits } = require("./tmdbService.js"); const Network = require("../models/Network.js"); const networkService = require("./networkService.js"); const Cast = require("../models/Credit.js"); const People = require("../models/People.js"); const Credit = require("../models/Credit.js"); const _mediaManager = mediaManager; const _mediaOptimizerService = mediaOptimizerService; const _networkService = networkService; class EntryService { constructor() { if (!EntryService.instance) { EntryService.instance = this; } return EntryService.instance; } async getAllEntries() { const entries = await Entry.findAll({ include: [ { model: EntryId, as: "entryId" }, { model: EntryRating, as: "entryRating" }, { model: Media, as: "medias" }, { model: Season, as: "seasons" }, { model: Network, as: "networks" }, { model: Genre, as: "genres", attributes: ["name"], through: { attributes: [] }, }, ], }); const entriesWithGenreNames = entries.map((entry) => ({ ...entry.get({ plain: true }), genres: entry.genres.map((genre) => genre.name), })); return entriesWithGenreNames; } /** * Retrieves an entry by its ID, optionally as a plain object. * * @param {number} id - The entry ID to retrieve. * @param {boolean} [plain=true] - Whether to return a plain object or a Sequelize instance. * @returns {Promise} The entry data. * @throws {BadRequestError} If no ID is provided. * @throws {NotFoundError} If no entry is found with the given ID. */ async getEntryById(id, plain = true) { if (!id) { throw new BadRequestError("Entry id not provided"); } let entry = await Entry.findByPk(id, { include: [ { model: EntryId, as: "entryId" }, { model: EntryRating, as: "entryRating" }, { model: EntrySeen, as: "entrySeen" }, { model: Season, as: "seasons" }, { model: Media, as: "medias" }, { model: Network, as: "networks" }, { model: Cast, as: "credits", order: [ ["cast_type", "ASC"], ["order", "ASC"], ], limit: 10, include: [{ model: People, as: "person" }], }, { model: Collection, as: "collections", include: [{ model: Media, as: "medias" }], }, { model: Genre, as: "genres", attributes: ["name", "id"], through: { attributes: [] }, }, ], order: [[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"]], }); if (!entry) { throw new NotFoundError("Entry with the provided id was not found"); } if (plain) { const plainEntry = entry.get({ plain: true }); plainEntry.genres = plainEntry.genres.map((g) => g.name); return plainEntry; } return entry; } /** * Retrieves ALL credits (cast + crew) for an entry with associated people. * Used by the Cast & Crew page to lazy-render large credit lists. * * @param {number} id - The entry ID. * @returns {Promise} Array of plain credit objects with `people` populated. */ async getEntryCredits(id) { if (!id) { throw new BadRequestError("Entry id not provided"); } const entry = await Entry.findByPk(id, { attributes: ["id"] }); if (!entry) { throw new NotFoundError("Entry with the provided id was not found"); } const credits = await Credit.findAll({ where: { entry_id: id }, include: [{ model: People, as: "person" }], order: [ ["cast_type", "ASC"], ["order", "ASC"], ["episode_count", "DESC"], ], }); return credits.map((c) => c.get({ plain: true })); } async createEntry(data, plain = true) { // creating the object var is_tvseries = data.release_date == null ? true : false; 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, 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); // ? ids await EntryId.create({ entry_id: savedEntry.id, tmdb_id: data.id, imdb_id: data.imdb_id, }); // ? genres data.genres.forEach(async (genre) => { await EntryGenre.create({ genre_id: genre.id, entry_id: savedEntry.id, }); }); // ? networks if (data.networks) { for (const networkData of data.networks) { // Create or update the network const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData); let network = oldNetwork || newNetwork; if (!network) { throw new NotFoundError("Network not found"); } // Associate the new network with the entry await savedEntry.addNetwork(network); } } // ? ratings await EntryRating.create({ entry_id: savedEntry.id, user_rating: 0, tmdb_rating: data.vote_average, }); // ! seasons & episodes for tv series if (is_tvseries) { // * seasons let seasons = []; for (const season of data.seasons) { let seasonData = await fetchSeasonData(data.id, season.season_number); const savedSeason = await Season.create({ tmdb_id: seasonData.id, 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, }); _mediaManager.getSeasonMedia(savedSeason); // * episodes let episodes = []; for (const episode of seasonData.episodes) { const savedEpisode = await Episode.create({ tmdb_id: episode.id, 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); _mediaManager.getEpisodenMedia(savedEpisode); } // TODO fetch cast savedSeason.setDataValue("episodes", episodes); seasons.push(savedSeason); } savedEntry.setDataValue("seasons", seasons); } // + end of: seasons & episodes for tv series // ? Credits const creditData = await fetchEntryCredits(data.id, is_tvseries); if (!creditData) { throw new InternalServerError(`Couldn't fetch entry credits data`); } const allCredits = [ ...creditData.cast.map((c) => ({ ...c, cast_type: "cast" })), ...creditData.crew.map((c) => ({ ...c, cast_type: "crew" })), ]; const tmdbIds = [...new Set(allCredits.map((c) => c.id))]; // — FETCH EXISTING PEOPLE — const existingPeopleList = await People.findAll({ where: { tmdb_id: tmdbIds }, }); const existingPeopleMap = Object.fromEntries( existingPeopleList.map((p) => [p.tmdb_id, p]), ); // — CREATE NEW PEOPLE — const newPeopleData = tmdbIds .filter((id) => !existingPeopleMap[id]) .map((id) => { const credit = allCredits.find((c) => c.id === id); return { tmdb_id: credit.id, name: credit.name, gender: credit.gender || null, popularity: credit.popularity, known_for_department: credit.known_for_department || null, profile_path: credit.profile_path, adult: credit.adult || false, last_fetch: new Date(), }; }); if (newPeopleData.length) { console.log(`[PEOPLE] Adding ${newPeopleData.length} new people...`); } const createdPeople = await People.bulkCreate(newPeopleData); for (const person of createdPeople) { console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`); existingPeopleMap[person.tmdb_id] = person; } // — BUILD NEW CREDITS — const newCredits = []; for (const c of allCredits) { const person = existingPeopleMap[c.id]; if (!person) continue; // Detect TV aggregate format (roles/jobs arrays) vs movie flat format. const character = c.cast_type === "cast" ? Array.isArray(c.roles) ? c.roles .map((r) => r.character) .filter(Boolean) .join("; ") || null : c.character || null : null; const job = c.cast_type === "crew" ? Array.isArray(c.jobs) ? c.jobs .map((j) => j.job) .filter(Boolean) .join("; ") || null : c.job || null : null; const tmdbCreditId = Array.isArray(c.roles) ? c.roles?.[0]?.credit_id : Array.isArray(c.jobs) ? c.jobs?.[0]?.credit_id : c.credit_id; newCredits.push({ entry_id: savedEntry.id, people_id: person.id, tmdb_credit_id: tmdbCreditId, character, order: c.cast_type === "cast" ? c.order : null, episode_count: c.total_episode_count ?? null, profile_path: person.profile_path, adult: person.adult, cast_type: c.cast_type, department: c.cast_type === "crew" ? c.department || null : null, job, }); } await Credit.bulkCreate(newCredits); console.log( `[CREDITS] Inserted ${newCredits.length} credits for entry ${savedEntry.id}`, ); savedEntry.credit_fetched = true; // Extract director name from processed credits (handles both movie & TV aggregate format) const directorCredit = allCredits.find((c) => { if (c.cast_type !== "crew") return false; const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job]; return jobs.includes("Director"); }); savedEntry.director = directorCredit?.name || null; await savedEntry.save(); // ? media const downloadedImages = await _mediaManager.getEntryMedia( data.id, is_tvseries, ); // console.log(`entry service, downloaded images: `, downloadedImages) for (const image of downloadedImages) { await Media.create({ mediaable: "entry", mediaableId: savedEntry.id, type: image.type, path: image.path, isLocal: true, isSelected: true, }); _mediaOptimizerService.doGeneratePreview( "entries", image.type + "s", image.path, ); } // const currentGenresNames = await data.genres.map(genre => genre.name); // savedEntry.setDataValue('entryId', ids); // savedEntry.setDataValue('entryRating', ratings); // savedEntry.setDataValue('genres', currentGenresNames); savedEntry = await this.getEntryById(savedEntry.id, plain); return savedEntry; } async updateEntryById(id, entryData, plain = true) { if (!id) { throw new BadRequestError("Entry id not provided"); } // ? checking if the provied id is valid const oldEntry = await Entry.findByPk(id); if (!oldEntry) { throw new NotFoundError("Entry with the provided id was not found"); } await oldEntry.update(entryData); const updatedEntry = await this.getEntryById(id, plain); return updatedEntry; } async updateEntryRatings(id, entryRatingsData) { if (!id) { throw new BadRequestError("Entry id not provided"); } let entry = await Entry.findByPk(id, { include: [{ model: EntryRating, as: "entryRating" }], }); if (!entry) { throw new NotFoundError("Entry with the provided id was not found"); } if (entry.entryRating.id != entryRatingsData.id) { throw new BadRequestError("EntryRatings id does not match"); } entry.entryRating.user_rating = entryRatingsData.user_rating ?? entry.entryRating.user_rating; entry.entryRating.tmdb_rating = entryRatingsData.tmdb_rating ?? entry.entryRating.tmdb_rating; entry.entryRating.imdb_rating = entryRatingsData.imdb_rating ?? entry.entryRating.imdb_rating; entry.entryRating.rotten_tomatoes_rating = entryRatingsData.rotten_tomatoes_rating ?? entry.entryRating.rotten_tomatoes_rating; return await entry.entryRating.save(); } async updateEntryIds(id, entryIdsData) { if (!id) { throw new BadRequestError("Entry id not provided"); } let entry = await Entry.findByPk(id, { include: [{ model: EntryId, as: "entryId" }], }); if (!entry) { throw new NotFoundError("Entry with the provided id was not found"); } if (entry.entryRating.id != entryRatingsData.id) { throw new BadRequestError("EntryIds id does not match"); } entry.entryId.tmdb_id = entryIdsData.tmdb_id ?? entry.entryId.tmdb_id; entry.entryId.imdb_id = entryIdsData.imdb_id ?? entry.entryId.imdb_id; entry.entryId.tvdb_id = entryIdsData.tvdb_id ?? entry.entryId.tvdb_id; await entry.entryId.save(); } async deleteEntryById(id) { if (!id) { throw new BadRequestError("Entry id not provided"); } const deletedCount = await Entry.destroy({ where: { id: id }, }); if (deletedCount == 0) { throw new NotFoundError("Entry with the provided id was not found"); } return deletedCount; } async getEntrySeasons(id) { if (!id) { throw new BadRequestError("Entry id not provided"); } const entry = await Entry.findByPk(id); if (!entry) { throw new NotFoundError("Entry with the provided id was not found"); } const seasons = await Season.findAll({ where: { entry_id: id, }, include: [ { model: Episode, as: "episodes", include: [{ model: Media, as: "medias" }], }, { model: Media, as: "medias" }, ], order: [ ["season_number", "ASC"], [{ model: Episode, as: "episodes" }, "episode_number", "ASC"], ], }); return seasons; } } module.exports = new EntryService();