const path = require("path"); const { v4: uuidv4 } = require("uuid"); const Entry = require("../models/Entry"); const BadRequestError = require("../errors/BadRequestError"); const NotFoundError = require("../errors/NotFoundError"); const configService = require("./configService"); const tmdbService = require("./tmdbService"); const mediaService = require("./mediaService"); const mediaDownloaderService = require("./mediaDownloaderService"); const mediaOptimizerService = require("./mediaOptimizerService"); const Season = require("../models/Season"); const storageService = require("./storageService"); const Media = require("../models/Media"); const _configService = configService; const _mediaService = mediaService; const _tmdbService = tmdbService; const _mediaOptimizerService = mediaOptimizerService; const _mediaDownloaderService = mediaDownloaderService; const _storageService = storageService; class MediaManager { constructor() { if (!MediaManager.instance) { MediaManager.instance = this; } return MediaManager.instance; } async saveMedia(entryId, files) { if (!files) { throw new BadRequestError("No media uploaded"); } const entry = await Entry.findByPk(entryId); if (!entry) { throw new NotFoundError("Entry not found"); } const fileType = ["poster", "backdrop", "logo"].find( (type) => req.files[type], ); if (!fileType) { throw new BadRequestError("Invalid media type"); } // * 1 - save the media into database const file = req.files[fileType][0]; const createdMedia = await _mediaService.createMedia({ mediaable: "entry", mediaableId: id, type: fileType, path: file.filename, isLocal: true, isSelected: false, isCustom: true, }); // * 2 - generating low resolution preview _mediaOptimizerService .generatePreviewFiles("entries", fileType + "s", file.filename) .then((result) => { const stream = fs.createReadStream(filePath); stream.pipe(res); const msg = `Media Route | Generated Entry Preview`; logToFile(msg); }) .catch((err) => { const msg = `Media Route | Error Generating Entry Preview`; logToFile(msg); }); return createdMedia; } async getEntryMedia( tmdb_id, is_tvserie, includes = ["posters", "logos", "backdrops"], ) { // Fetching entry media const mediaData = await _tmdbService.fetchEntryMedia(tmdb_id, is_tvserie); if (!mediaData) { throw new InternalServerError(`Counldn't fetch data from TMDB`); } // Local variables for this function invocation let downloadTasks = []; let downloadedImages = []; _configService.createMediaFolders(); // Ensuring directories exist // Getting the userDataPath to store the images const dataPath = _configService.getSettings().userDataPath; // Handling different media types const mediaTypes = [ { type: "posters", dir: path.join(dataPath, "images", "entries", "posters"), }, { type: "logos", dir: path.join(dataPath, "images", "entries", "logos") }, { type: "backdrops", dir: path.join(dataPath, "images", "entries", "backdrops"), }, ]; mediaTypes.forEach(({ type, dir }) => { if (!includes.includes(type)) return; // ? the media type is not requested if (mediaData[type] && mediaData[type].length) { const selectedMedia = _mediaDownloaderService.findPreferredMedia( mediaData[type], ); if (selectedMedia) { _mediaDownloaderService.scheduleDownloads( selectedMedia, type.slice(0, -1), dir, downloadTasks, downloadedImages, ); } } }); // Wait for all downloads to complete await Promise.all(downloadTasks) .then(() => { console.log("Downloaded images:", downloadedImages); }) .catch((err) => { console.error("Error downloading entry images:", err); }); return downloadedImages; } async getSeasonMedia(season) { if (!season.poster_path) return; const url = `https://image.tmdb.org/t/p/original${season.poster_path}`; const file = await _mediaDownloaderService.downloadFile(url); const uniqueFilename = uuidv4(); const extension = season.poster_path.split(".").pop(); const filename = `${uniqueFilename}.${extension}`; const dataPath = _configService.getSettings().userDataPath; const fullFilePath = path.join( dataPath, "images", "seasons", "posters", filename, ); _storageService .storeFile(file, fullFilePath) .then(async () => { await Media.create({ mediaable: "season", mediaableId: season.id, type: "poster", path: filename, isLocal: true, isSelected: true, }); console.log(`File created for season: ${filename}`); }) .catch(); } async getEpisodenMedia(episode) { if (!episode.still_path) return; const url = `https://image.tmdb.org/t/p/original${episode.still_path}`; const file = await _mediaDownloaderService.downloadFile(url); const uniqueFilename = uuidv4(); const extension = episode.still_path.split(".").pop(); const filename = `${uniqueFilename}.${extension}`; const dataPath = _configService.getSettings().userDataPath; const fullFilePath = path.join( dataPath, "images", "episodes", "stills", filename, ); _storageService .storeFile(file, fullFilePath) .then(async () => { await Media.create({ mediaable: "episode", mediaableId: episode.id, type: "still", path: filename, isLocal: true, isSelected: true, }); console.log(`File created for episode: ${filename}`); }) .catch(); } } module.exports = new MediaManager();