const { Sequelize } = require("sequelize"); const Collection = require("../models/Collection"); const Entry = require("../models/Entry"); const EntryId = require("../models/EntryId"); const Media = require("../models/Media"); const BadRequestError = require("../errors/BadRequestError"); const InternalServerError = require("../errors/InternalServerError"); const NotFoundError = require("../errors/NotFoundError"); const { fetchEntryData, fetchCollectionData } = require("./tmdbService"); const { logToFile } = require("./logService"); const mediaDownloaderService = require("./mediaDownloaderService"); const collectionService = require("./collectionService"); const mediaOptimizerService = require("./mediaOptimizerService.js"); const _collectionService = collectionService; const _mediaDownloaderService = mediaDownloaderService; const _mediaOptimizerService = mediaOptimizerService; class CollectionManager { constructor() { if (!CollectionManager.instance) { CollectionManager.instance = this; } return CollectionManager.instance; } /** * Fetches a collection from TMDB, saves it, links related entries, downloads media, and generates previews. * * @param {number} collectionTMDBId - The TMDB ID of the collection to fetch. * @throws {InternalServerError} If the collection data couldn't be fetched from TMDB. * @throws {NotFoundError} If the collection is not found after creation/update. * @returns {Promise} The updated collection object. */ async fetchAndSaveCollection(collectionTMDBId) { // * 1 - fetch collection data const collectionData = await fetchCollectionData(collectionTMDBId); if (!collectionData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } // * 2 - insert/update collection const [oldCollection, createdCollection] = await _collectionService.createOrUpdateCollection(collectionData); // * 3 - link related entries to the collection let collection = oldCollection || createdCollection; if (!collection) { throw new NotFoundError("Collection not found"); } const partIds = collectionData.parts.map((part) => part.id); const entries = await Entry.findAll({ include: [ { model: EntryId, as: "entryId", where: { tmdb_id: { [Sequelize.Op.in]: partIds, }, }, }, ], }); await collection.setEntries(entries); // * 4 - download collection media // ? downloading const downloadedImages = await _mediaDownloaderService.downloadCollectionMedia(collection); // ? generating preview & inserting data for (const image of downloadedImages) { // ? generating preview _mediaOptimizerService .doGeneratePreview("collections", image.type + "s", image.path) .then((result) => { const msg = `Collection Service | Generated Collection Preview`; console.log(msg); logToFile(msg); }) .catch((err) => { const msg = `Collection Service | Error Generating Collection Preview`; console.log(msg); console.log(err); logToFile(msg); logToFile(err); }); // ? inserting data await Media.create({ mediaable: "collection", mediaableId: collection.id, type: image.type, path: image.path, isLocal: true, isSelected: true, }); } // * 5 - return the collection return await _collectionService.getCollectionById(collection.id); } /** * Fetches the corresponding collection for a given entry (movie) if it is missing. * If the entry belongs to a collection, the collection is fetched and saved. * * @param {number} id - The ID of the entry to search for. * @throws {BadRequestError} If the entry ID is not provided. * @throws {NotFoundError} If the entry is not found. * @throws {InternalServerError} If entry data couldn't be fetched from TMDB. * @returns {Promise} The collection object or null if the entry does not belong to any collection. */ async fetchCollectionByEntryId(id) { if (!id) { throw new BadRequestError("Entry id not provided"); } const oldEntry = await Entry.findByPk(id, { include: [{ model: EntryId, as: "entryId" }], }); if (!oldEntry) { throw new NotFoundError("Entry not found"); } const entryData = await fetchEntryData( oldEntry.entryId.tmdb_id, oldEntry.is_tvseries, ); if (!entryData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } // ? entry doesn't belong to a collection if (!entryData.belongs_to_collection) { return null; } let collectionData = entryData.belongs_to_collection; const collection = await this.fetchAndSaveCollection(collectionData.id); return collection; } /** * Fetches missing parts (entries) for an existing collection and updates its overview. * Links new entries to the collection. * * @param {number} collectionId - The ID of the collection to update. * @throws {BadRequestError} If the collection ID is not provided. * @throws {NotFoundError} If the collection is not found. * @throws {InternalServerError} If collection data couldn't be fetched from TMDB. * @returns {Promise} No return value. */ async getCollectionParts(collectionId) { if (!collectionId) { throw new BadRequestError("Collection id not provided"); } // * 1 - check if collection with given id exists const collection = await Collection.findByPk(collectionId); if (!collection) { throw new NotFoundError("Collection not found"); } // * 2 - fetch collection data const collectionData = await fetchCollectionData(collection.tmdbId); if (!collectionData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } // * 3 - fetch missing entries and save them and linked already // * existing ones to the collection const partIds = collectionData.parts.map((part) => part.id); // ? get all the related entries that are already in the library const entries = await Entry.findAll({ include: [ { model: EntryId, as: "entryId", where: { tmdb_id: { [Sequelize.Op.in]: partIds, }, }, }, ], }); // ? link entries already existing in the library await collection.setEntries(entries); // ? fetch and save missing entries, then link them to the collection collectionData.parts.forEach(async (part) => { if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) { const isTvSeries = false; const _entryManager = require("./entryManager.js"); const entry = await _entryManager.fetchAndSaveNewEntry( part.id, isTvSeries, false, ); await collection.addEntries([entry.id]); } }); } } module.exports = new CollectionManager();