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 Entry = require("../models/Entry"); const { Op } = require("sequelize"); 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 }; } /** * Count entries missing a director, and optionally fix them. * @param {boolean} [dry=false] - if true only count, if false also fix */ async fixMissingDirectors(dry = false) { const entries = await Entry.findAll({ where: { director: null }, include: [ { model: Credit, as: "credits", where: { cast_type: "crew", job: "Director" }, include: [{ model: People, as: "person", attributes: ["name"] }], required: false, }, ], }); const count = entries.length; let fixed = 0; if (!dry) { for (const entry of entries) { const dirName = entry.credits?.[0]?.person?.name || null; if (dirName) { entry.director = dirName; await entry.save(); fixed++; } } } if (dry) logToFile(`Dry missing directors check: ${count}`); else logToFile(`Fixed missing directors: ${fixed} of ${count}`); return { count, fixed }; } /** * Find and optionally remove duplicate credits. * * Pass 1: Role-level — same (entry, person, type, role). * Pass 2: Type-level — same (entry, person, type) but different roles. * Keeps the credit WITH a role; if both have roles, keeps newest ID. * * @param {boolean} [dry=false] - if true only count, if false also delete */ async cleanDuplicateCredits(dry = false) { const { Sequelize } = require("sequelize"); // ── Pass 1: Exact role-level duplicates ── const duplicateGroups = await Credit.findAll({ attributes: [ "entry_id", "people_id", "cast_type", "character", "job", [Sequelize.fn("COUNT", Sequelize.col("id")), "cnt"], [Sequelize.fn("GROUP_CONCAT", Sequelize.col("id")), "ids"], ], group: ["entry_id", "people_id", "cast_type", "character", "job"], having: Sequelize.literal("COUNT(id) > 1"), raw: true, }); let pass1Groups = duplicateGroups.length; let deletedCount = 0; if (!dry) { for (const row of duplicateGroups) { const idList = row.ids .split(",") .map(Number) .sort((a, b) => a - b); // Keep the newest (highest ID), delete the older ones const toDelete = idList.slice(0, -1); await Credit.destroy({ where: { id: toDelete } }); deletedCount += toDelete.length; } } const pass1Dupes = duplicateGroups.reduce( (sum, r) => sum + parseInt(r.cnt) - 1, 0, ); // ── Pass 2: Type-level duplicates (same person/entry/type, different roles) ── const typeDupes = await Credit.findAll({ attributes: [ "entry_id", "people_id", "cast_type", [Sequelize.fn("COUNT", Sequelize.col("id")), "cnt"], [Sequelize.fn("GROUP_CONCAT", Sequelize.col("id")), "ids"], [ Sequelize.fn( "GROUP_CONCAT", Sequelize.fn( "COALESCE", Sequelize.col("character"), Sequelize.col("job"), ), ), "roles", ], ], group: ["entry_id", "people_id", "cast_type"], having: Sequelize.literal("COUNT(id) > 1"), raw: true, }); let pass2Groups = typeDupes.length; let pass2Deleted = 0; if (!dry) { for (const row of typeDupes) { const idList = row.ids.split(",").map(Number); // Fetch these credits to inspect their roles const credits = await Credit.findAll({ where: { id: idList }, order: [["id", "DESC"]], }); // Separate: credits with roles vs without const withRole = credits.filter((c) => { if (c.cast_type === "cast") return c.character && c.character.trim(); return c.job && c.job.trim(); }); const withoutRole = credits.filter((c) => { if (c.cast_type === "cast") return !c.character || !c.character.trim(); return !c.job || !c.job.trim(); }); let keep; const toDelete = []; if (withRole.length > 0 && withoutRole.length > 0) { // Prefer the one WITH a role; keep the newest among those with roles. // Delete all without-role entries. keep = withRole[0]; // already sorted by id DESC toDelete.push(...withoutRole.map((c) => c.id)); // If there are multiple with-role, delete the older ones if (withRole.length > 1) { toDelete.push(...withRole.slice(1).map((c) => c.id)); } } else if (withRole.length > 1) { // All have roles — keep newest, delete older keep = withRole[0]; toDelete.push(...withRole.slice(1).map((c) => c.id)); } else { // None have roles — keep newest, delete older keep = withoutRole[0]; toDelete.push(...withoutRole.slice(1).map((c) => c.id)); } if (toDelete.length > 0) { await Credit.destroy({ where: { id: toDelete } }); pass2Deleted += toDelete.length; } } } const pass2Dupes = typeDupes.reduce( (sum, r) => sum + parseInt(r.cnt) - 1, 0, ); const totalGroups = pass1Groups + pass2Groups; const totalDupes = pass1Dupes + pass2Dupes; const totalDeleted = deletedCount + pass2Deleted; if (dry) { logToFile( `Dry duplicate credits: Pass1=${pass1Groups} groups (${pass1Dupes} dupes), Pass2=${pass2Groups} groups (${pass2Dupes} dupes) → ${totalGroups} groups, ${totalDupes} duplicates`, ); } else { logToFile( `Cleaned duplicate credits: Pass1=${pass1Groups} groups (${deletedCount} deleted), Pass2=${pass2Groups} groups (${pass2Deleted} deleted) → ${totalDeleted} total removed`, ); } return { groups: totalGroups, duplicates: totalDupes, deleted: totalDeleted, }; } async autoFixWatchStatuses() { const Episode = require("../models/Episode"); const EpisodeSeen = require("../models/EpisodeSeen"); const Season = require("../models/Season"); const { Op } = require("sequelize"); const tvEntries = await Entry.findAll({ where: { is_tvseries: true }, include: [ { model: Season, as: "seasons", where: { season_number: { [Op.gt]: 0 } }, include: [ { model: Episode, as: "episodes", include: [{ model: EpisodeSeen, as: "episodeSeens" }], }, ], }, ], }); let toCompleted = 0; let toWatching = 0; let toPlanToWatch = 0; for (const entry of tvEntries) { let totalEpisodes = 0; let watchedEpisodes = 0; for (const season of entry.seasons || []) { for (const ep of season.episodes || []) { totalEpisodes++; if (ep.episodeSeens && ep.episodeSeens.length > 0) { watchedEpisodes++; } } } const allWatched = totalEpisodes > 0 && watchedEpisodes === totalEpisodes; const hasSomeWatched = watchedEpisodes > 0; // Completed but not all watched → downgrade to watching if (entry.watch_status === "completed" && !allWatched) { entry.watch_status = "watching"; await entry.save(); toWatching++; continue; } // All watched → completed (unless already completed) if (allWatched && entry.watch_status !== "completed") { entry.watch_status = "completed"; await entry.save(); toCompleted++; continue; } // Has some watched but no status → watching if (hasSomeWatched && !entry.watch_status) { entry.watch_status = "watching"; await entry.save(); toWatching++; continue; } // In watchlist with no status → plan to watch if (entry.watchlist && !entry.watch_status) { entry.watch_status = "plan_to_watch"; await entry.save(); toPlanToWatch++; } } logToFile( `Auto-fixed watch statuses: ${toCompleted} completed, ${toWatching} watching, ${toPlanToWatch} plan_to_watch`, ); return { completed: toCompleted, watching: toWatching, planToWatch: toPlanToWatch, }; } /** * Find movies where an EntrySeen date is before the movie's release_date. * @param {boolean} [dry=false] - if true only return the entries, if false also add to collection */ async fixImpossibleSeenDates(dry = false) { const { Op } = require("sequelize"); const EntrySeen = require("../models/EntrySeen"); const UserCollectionEntry = require("../models/UserCollectionEntry"); const Collection = require("../models/Collection"); // Find movies with entry_seen before release_date const allMovies = await Entry.findAll({ where: { is_tvseries: false, release_date: { [Op.ne]: null }, }, include: [ { model: EntrySeen, as: "entrySeen", required: true, }, ], }); const impossibleEntries = []; for (const movie of allMovies) { for (const seen of movie.entrySeen || []) { if ( seen.date_seen && new Date(seen.date_seen) < new Date(movie.release_date) ) { impossibleEntries.push(movie); break; } } } if (!dry) { // Find or create the collection const COLLECTION_NAME = "Movies with impossible seen date"; let [collection] = await Collection.findOrCreate({ where: { name: COLLECTION_NAME, isUserCollection: true }, defaults: { name: COLLECTION_NAME, description: "Movies that have a watch date before their official release date.", isUserCollection: true, }, }); // Add entries that are not already in the collection let added = 0; for (const entry of impossibleEntries) { const exists = await UserCollectionEntry.findOne({ where: { user_collection_id: collection.id, entry_id: entry.id, }, }); if (!exists) { await UserCollectionEntry.create({ user_collection_id: collection.id, entry_id: entry.id, }); added++; } } logToFile( `Impossible seen dates: ${impossibleEntries.length} movies found, ${added} added to collection`, ); return { count: impossibleEntries.length, added }; } logToFile( `Dry impossible seen dates check: ${impossibleEntries.length} movies found`, ); return { count: impossibleEntries.length }; } /** * Entries due for a TMDB refresh: never fetched, or last fetched more than * `hours` ago. Entries with auto sync turned off are skipped. * @param {number} [hours=24] */ async getStaleEntries(hours = 24) { const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000); return Entry.findAll({ attributes: ["id", "title", "last_fetch"], where: { autoSync: { [Op.not]: false }, [Op.or]: [{ last_fetch: null }, { last_fetch: { [Op.lt]: cutoff } }], }, order: [["last_fetch", "ASC"]], }); } /** Current/last stale refresh job, for the status endpoint. */ getStaleRefreshStatus() { const job = this.staleRefreshJob; if (!job) return { running: false }; return { ...job, failed: job.failed.slice(-50) }; } /** * Starts refreshing every stale entry in the background, one at a time. * TMDB requests go through tmdbService's rate limiter, so a large library * is spread out instead of hammering the API. * @param {number} [hours=24] * @returns {Object} the job status, or `{ alreadyRunning: true, ... }` */ async startStaleRefresh(hours = 24) { if (this.staleRefreshJob?.running) { return { alreadyRunning: true, ...this.getStaleRefreshStatus() }; } const entries = await this.getStaleEntries(hours); const job = { running: true, cancelRequested: false, hours, total: entries.length, done: 0, succeeded: 0, failed: [], current: null, startedAt: new Date(), finishedAt: null, }; this.staleRefreshJob = job; logToFile(`Stale refresh started: ${entries.length} entries (> ${hours}h)`); // Required lazily: entryManager pulls in most of the services layer. const entryManager = require("./entryManager"); (async () => { for (const entry of entries) { if (job.cancelRequested) break; job.current = { id: entry.id, title: entry.title }; try { await entryManager.refrechEntryById(entry.id, false); job.succeeded++; } catch (error) { job.failed.push({ id: entry.id, title: entry.title, error: error.message, }); logToFile( `Stale refresh failed for entry ${entry.id} (${entry.title}): ${error.message}`, ); } job.done++; } job.running = false; job.current = null; job.finishedAt = new Date(); logToFile( `Stale refresh ${job.cancelRequested ? "cancelled" : "finished"}: ${job.succeeded} ok, ${job.failed.length} failed of ${job.total}`, ); })(); return this.getStaleRefreshStatus(); } cancelStaleRefresh() { if (this.staleRefreshJob?.running) { this.staleRefreshJob.cancelRequested = true; } return this.getStaleRefreshStatus(); } } module.exports = new MaintenanceService();