const moment = require("../utils/moment.js"); const { Op } = require("sequelize"); const Entry = require("../models/Entry.js"); const Episode = require("../models/Episode.js"); const Season = require("../models/Season.js"); const EntryGenre = require("../models/EntryGenre.js"); const EntryId = require("../models/EntryId.js"); const EntryRating = require("../models/EntryRating.js"); const EntrySeen = require("../models/EntrySeen.js"); const Media = require("../models/Media.js"); const Genre = require("../models/Genre.js"); const BadRequestError = require("../errors/BadRequestError"); const NotFoundError = require("../errors/NotFoundError.js"); const ValidationError = require("../errors/ValidationError.js"); const { fetchEntryData, fetchSeasonData } = require("./tmdbService.js"); const { logToFile } = require("./logService.js"); const collectionManager = require('./collectionManager.js'); const entryService = require("./entryService"); const mediaManager = require("./mediaManager.js"); const _collectionManager = collectionManager; const _entryService = entryService; const _mediaManager = mediaManager; class EntryManager { constructor() { if (!EntryManager.instance) { EntryManager.instance = this; } return EntryManager.instance; } // todo: change fetchEntryData to TMDBService.fetchEntryData() async fetchAndSaveNewEntry(id, type, fetchCollection = true, plain = true) { if (!id) { throw new BadRequestError("Entry id not provided"); } if (typeof type !== "boolean") { throw new BadRequestError(`Invalid type: ${type}. Expected a boolean value.`); } // * 1 - fetch entry data const entryData = await fetchEntryData(id, type); if (!entryData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } // * 2 - insert the entry into db const entry = await _entryService.createEntry(entryData, plain); // * 3 - created the related collection if (entryData.belongs_to_collection && fetchCollection) { await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id); } return entry; } // todo: change fetchEntryData to TMDBService.fetchEntryData() // todo: change fetchEntryData to TMDBService.fetchSeasonData() async refrechEntryById(id, plain = true) { if (!id) { throw new BadRequestError("Entry id not provided"); } // ? checking if the provied id is valid // ! note: the includes are required for the update const oldEntry = await _entryService.getEntryById(id, false); if (!oldEntry) { throw new NotFoundError("Entry not found"); } // ? getting new data from TMDB const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); if (!entryData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } // ! 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); // * updating ids // TODO: get more ids await oldEntry.entryId.update({ imdb_id: entryData.imdb_id, }); // * updating ratings await oldEntry.entryRating.update({ tmdb_rating: entryData.vote_average }); // * updating genres 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 }) }); // * 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 let seasonData = await fetchSeasonData(entryData.id, season.season_number); // Fetch existing season if it exists (using tmdb_id) let existingSeason = await Season.findOne({ where: { tmdb_id: season.id } }); // 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(); } else { // Create a new season existingSeason = await Season.create({ tmdb_id: seasonData.id, 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, }); } // * Update or insert episodes for the season for (const episode of seasonData.episodes) { // Fetch existing episode data if it exists let existingEpisode = await Episode.findOne({ where: { tmdb_id: episode.id, } }); // 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(); } else { // Create a new episode await Episode.create({ tmdb_id: episode.id, 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, }); } } } } // * Cast // ? Only fetch if the cast count is 0 or less than max_cast // TODO add cast refrech // if (!oldEntry.casts || oldEntry.casts.length == 0 || oldEntry.casts.length < oldEntry.max_cast) { // } // * Media // ? Only fetch if a Poster, Backdrop or a Logo is missing // ? only get missing media types // ? count media by type let availableMedia = { 'posters': 0, 'logos': 0, 'backdrops': 0 }; for (let i = 0; i < oldEntry.medias.length; i++) { availableMedia[oldEntry.medias[i].type + 's'] += 1; } // ? if the count of a media type == 0, the add the type to mediaToGet let mediaToGet = []; for (let key in availableMedia) { if (availableMedia[key] == 0) mediaToGet.push(key); } let downloadedImages; if (mediaToGet.length != 0) { downloadedImages = await _mediaManager.getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet); } if (downloadedImages) { for (const image of downloadedImages) { await Media.create({ mediaable: 'entry', mediaableId: oldEntry.id, type: image.type, path: image.path, isLocal: true, isSelected: true }); } } // ? fetch collection if (entryData.belongs_to_collection) { await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id); } // + end of: refrech logic // ! returning the refreshed entry const refreshedEntry = await _entryService.getEntryById(id, plain); return refreshedEntry; } /** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today */ async SyncSeriesData() { const today = moment().format('YYYY-MM-DD'); const entries = await Entry.findAll({ where: { is_tvseries: true, autoSync: true, last_fetch: { [Op.ne]: today }, status: { [Op.notIn]: [ 'Ended', 'Canceled' ] }, }, }); logToFile(`Started syncing ${entries.length} Tv-Series`); const results = await Promise.all( entries.map(entry => this.SyncSerieData(entry.id)) ); logToFile(`Syncing Tv-Series Finished`); return results; } async SyncSerieData(entryId) { const oldEntry = await Entry.findByPk(entryId, { include: [ { model: EntryId, as: 'entryId' }, { model: EntryRating, as: 'entryRating' }, { model: EntrySeen, as: 'entrySeen' }, { model: Season, as: 'seasons' }, { model: Media, as: 'medias' }, { model: Genre, as: 'genres', attributes: ['id'], through: { attributes: [] } } ] }); logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`) if (!oldEntry) throw NotFoundError('Entry Not Found'); const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); if (!entryData) throw ValidationError(`Couldn't Fetch Entry Data`); // ! 1 - Normal Data let newData = { title: entryData.title || entryData.name, original_title: entryData.original_title || entryData.original_name, release_date: entryData.release_date || entryData.first_air_date, 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() }; await oldEntry.update(newData); // ! 2 - Ids // TODO: get more ids await oldEntry.entryId.update({ imdb_id: entryData.imdb_id, }); // ! 3 - Ratings await oldEntry.entryRating.update({ tmdb_rating: entryData.vote_average }); // ! 4 - Genres const currentGenresIds = oldEntry.genres.map(genre => genre.id); entryData.genres.forEach(async (genre) => { // ? only assing the genre if its not already asigned if (!currentGenresIds.includes(genre.id)) { await EntryGenre.create({ genre_id: genre.id, entry_id: oldEntry.id }) } }); // ! 5 - Seasons // ? only update the last seasons available + season 0 (specials) if (oldEntry.is_tvseries) { const latestAvailableSeason = await Math.max(...oldEntry.seasons.map(s => s.season_number)); for (const season of entryData.seasons) { if (season.season_number != 0 && season.season_number != latestAvailableSeason) continue; // ? fetch new season data from tmdb let seasonData = await fetchSeasonData(oldEntry.entryId.tmdb_id, season.season_number); // * find or create the season const [oldSeason, createdSeason] = await Season.findOrCreate({ where: { tmdb_id: season.id }, defaults: { tmdb_id: seasonData.id, 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, } }); // ? if the season already exist then just update it with new data if (!createdSeason) { await oldSeason.update({ tmdb_id: seasonData.id, 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, }); } // * forging updated/created season into a variable let existingSeason = oldSeason || createdSeason; // ! 6 - Episodes for (const episode of seasonData.episodes) { // * find or create the episode const [oldEpisode, createdEpisode] = await Episode.findOrCreate({ where: { tmdb_id: episode.id }, defaults: { 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, } }); // ? if the episode already exist then just update it with new data if (!createdEpisode) { await oldEpisode.update({ tmdb_id: episode.id, 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, }); } } } } await oldEntry.reload(); return oldEntry; } } module.exports = new EntryManager();