const path = require('path'); const fsPromises = require('fs').promises; const fs = require('fs'); const Media = require("../models/Media"); const People = require("../models/People"); const Credit = require("../models/Credit"); const { logToFile } = require('./logService'); const configService = require('./configService'); const _configService = configService; class MaintenanceService { constructor() { if (!MaintenanceService.instance) { MaintenanceService.instance = this; } return MaintenanceService.instance; } /** * Delete orphan media records from database, * these are media records that exist in the database * but do not have a file in the `user data folder`. * @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false` */ async deleteOrphanMediaRecords(dry = false) { const allMedia = await Media.findAll(); const dataPath = await _configService.getMediaFolder(); const mediaTypeFolder = { 'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'), 'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'), 'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'), 'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'), 'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops'), 'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'), 'episode;still': path.join(dataPath, 'images', 'episodes', 'stills') }; let missingFiles = []; for (let i = 0; i < allMedia.length; i++) { const folderType = `${allMedia[i].mediaable};${allMedia[i].type.replace("_preview", "")}`; if (!mediaTypeFolder[folderType]) continue; const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path) if (!fs.existsSync(filePath)) { missingFiles.push(allMedia[i]); } } let removed = { 'posters': 0, 'logos': 0, 'backdrops': 0, 'stills': 0, }; for (let i = 0; i < missingFiles.length; i++) { removed[missingFiles[i].type + 's'] += 1; if (!dry) missingFiles[i].destroy(); } if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) return removed; } /** * Delete orphan files from media folder data, * orphan files are files that exist in the `folder data` * but do not have an instance in the database * @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false` */ async deleteOrphanFiles(dry = false) { const dataPath = _configService.getMediaFolder(); // ? Getting the name (without extention) of all media in database const allMedia = (await Media.findAll()).map(m => { return m.path.split('.')[0] }); // ? Loop trough the files of the images folder and check // ? if a file doesnt exist in the allMedia array and mark it to delete const mediaTypeFolder = { 'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'), 'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'), 'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'), 'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'), 'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops'), 'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'), 'episode;still': path.join(dataPath, 'images', 'episodes', 'stills') }; // * counter let removed = { 'posters': 0, 'logos': 0, 'backdrops': 0, 'stills': 0, }; // Iterate over each media type directory and check for orphan files for (let folderType in mediaTypeFolder) { const directory = mediaTypeFolder[folderType]; try { // ? getting all files inside that folder const files = await fsPromises.readdir(directory).then(); // console.log(`found ${files.length} files in ${directory}`); // Check each file in the directory for (let file of files) { // preparing the file name const fileName = file.split('.')[0].replace("_preview", ""); const isInDatabase = allMedia.includes(fileName); // if the file isn't in database even on other extentions then delete it if (!isInDatabase) { removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files if (!dry) { const filePath = path.join(directory, file); await fsPromises.unlink(filePath); } } } } catch (err) { console.error(`Error handling files in ${directory}:`, err); } } if (dry) logToFile(`Run a dry orphan files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) else logToFile(`Run an orphan files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) return removed; } /** * Delete orphan people from the database. * Orphan people are those not linked to any entry via credits * AND not manually pinned. * @param {boolean} [dry=false] - if true only return the count */ async deleteOrphanPeople(dry = false) { const { Sequelize } = require('sequelize'); // Find all people who have no credits and are not pinned const allPeople = await People.findAll({ include: [{ model: Credit, as: 'roles', required: false, }], }); const orphans = allPeople.filter(p => (!p.roles || p.roles.length === 0) && !p.pinned); if (!dry) { for (const person of orphans) { await person.destroy(); } } const count = orphans.length; if (dry) logToFile(`Run a dry orphan people check, found: ${count}`); else logToFile(`Run orphan people cleanup, deleted: ${count}`); return { count }; } } module.exports = new MaintenanceService();