Add impossible seen dates maintenance endpoint

- Backend: fixImpossibleSeenDates scan/fix in maintenanceService
  detects movies with EntrySeen date before release_date, adds
  them to a "Movies with impossible seen date" collection
- Frontend: ImpossibleSeenDatesSection in SettingsPage with
  Scan and Fix buttons
- Updated API docs (Clients + Reference), cleaned up removed
  migrateSeenWith references
This commit is contained in:
X4Lo committed 2026-06-25 21:38:31 +01:00
1 parent 3df2e2ce3e
commit d984210dd9
8 files changed
+294 -124

No files matched your search

+11 -1
View File
@@ -1,4 +1,4 @@
const maintenanceService = require('../services/maintenanceService');
const maintenanceService = require("../services/maintenanceService");
const _maintenanceService = maintenanceService;
@@ -68,6 +68,16 @@ class MaintenanceController {
const result = await _maintenanceService.autoFixWatchStatuses();
return res.status(200).json(result);
}
async getImpossibleSeenDates(req, res) {
const result = await _maintenanceService.fixImpossibleSeenDates(true);
return res.status(200).json(result);
}
async fixImpossibleSeenDates(req, res) {
const result = await _maintenanceService.fixImpossibleSeenDates();
return res.status(200).json(result);
}
}
module.exports = new MaintenanceController();
+25 -13
View File
@@ -1,67 +1,79 @@
const express = require('express');
const express = require("express");
const maintenanceRouter = express.Router();
const maintenanceController = require('../controllers/maintenanceController');
const maintenanceController = require("../controllers/maintenanceController");
// ! /maintenance
// * GET - Orphan files
maintenanceRouter.get('/orphan-files', maintenanceController.getOrpanFiles);
maintenanceRouter.get("/orphan-files", maintenanceController.getOrpanFiles);
// * GET - Missing files
maintenanceRouter.get(
'/orphan-media-records',
"/orphan-media-records",
maintenanceController.getOrphanMediaRecords,
);
// * DELETE - Orphan files
maintenanceRouter.delete(
'/orphan-files',
"/orphan-files",
maintenanceController.deleteOrpanFiles,
);
// * DELETE - Missing files
maintenanceRouter.delete(
'/orphan-media-records',
"/orphan-media-records",
maintenanceController.deleteOrphanMediaRecords,
);
// * GET - Orphan people (dry run)
maintenanceRouter.get('/orphan-people', maintenanceController.getOrphanPeople);
maintenanceRouter.get("/orphan-people", maintenanceController.getOrphanPeople);
// * DELETE - Orphan people
maintenanceRouter.delete(
'/orphan-people',
"/orphan-people",
maintenanceController.deleteOrphanPeople,
);
// * GET - Missing directors count
maintenanceRouter.get(
'/missing-directors',
"/missing-directors",
maintenanceController.getMissingDirectors,
);
// * POST - Fix missing directors
maintenanceRouter.post(
'/missing-directors',
"/missing-directors",
maintenanceController.fixMissingDirectors,
);
// * GET - Duplicate credits count
maintenanceRouter.get(
'/duplicate-credits',
"/duplicate-credits",
maintenanceController.getDuplicateCredits,
);
// * DELETE - Clean duplicate credits
maintenanceRouter.delete(
'/duplicate-credits',
"/duplicate-credits",
maintenanceController.cleanDuplicateCredits,
);
// * POST - Auto-fix watch statuses based on watched episodes
maintenanceRouter.post(
'/auto-fix-watch-statuses',
"/auto-fix-watch-statuses",
maintenanceController.autoFixWatchStatuses,
);
// * GET - Scan impossible seen dates (movies watched before release)
maintenanceRouter.get(
"/impossible-seen-dates",
maintenanceController.getImpossibleSeenDates,
);
// * POST - Fix impossible seen dates (add to collection)
maintenanceRouter.post(
"/impossible-seen-dates",
maintenanceController.fixImpossibleSeenDates,
);
module.exports = maintenanceRouter;
+150 -69
View File
@@ -1,14 +1,14 @@
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');
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 Media = require("../models/Media");
const People = require("../models/People");
const Credit = require("../models/Credit");
const Entry = require("../models/Entry");
const { logToFile } = require('./logService');
const configService = require('./configService');
const { logToFile } = require("./logService");
const configService = require("./configService");
const _configService = configService;
@@ -32,30 +32,30 @@ class MaintenanceService {
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'),
"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(
"collection;poster": path.join(
dataPath,
'images',
'collections',
'posters',
"images",
"collections",
"posters",
),
'collection;backdrop': path.join(
"collection;backdrop": path.join(
dataPath,
'images',
'collections',
'backdrops',
"images",
"collections",
"backdrops",
),
'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'),
'episode;still': path.join(dataPath, 'images', 'episodes', 'stills'),
"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', '')}`;
const folderType = `${allMedia[i].mediaable};${allMedia[i].type.replace("_preview", "")}`;
if (!mediaTypeFolder[folderType]) continue;
@@ -73,7 +73,7 @@ class MaintenanceService {
};
for (let i = 0; i < missingFiles.length; i++) {
removed[missingFiles[i].type + 's'] += 1;
removed[missingFiles[i].type + "s"] += 1;
if (!dry) missingFiles[i].destroy();
}
@@ -100,31 +100,31 @@ class MaintenanceService {
// ? Getting the name (without extention) of all media in database
const allMedia = (await Media.findAll()).map((m) => {
return m.path.split('.')[0];
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'),
"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(
"collection;poster": path.join(
dataPath,
'images',
'collections',
'posters',
"images",
"collections",
"posters",
),
'collection;backdrop': path.join(
"collection;backdrop": path.join(
dataPath,
'images',
'collections',
'backdrops',
"images",
"collections",
"backdrops",
),
'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'),
'episode;still': path.join(dataPath, 'images', 'episodes', 'stills'),
"season;poster": path.join(dataPath, "images", "seasons", "posters"),
"episode;still": path.join(dataPath, "images", "episodes", "stills"),
};
// * counter
@@ -146,12 +146,12 @@ class MaintenanceService {
// Check each file in the directory
for (let file of files) {
// preparing the file name
const fileName = file.split('.')[0].replace('_preview', '');
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
removed[folderType.split(";")[1] + "s"]++; // Increment the count of removed files
if (!dry) {
const filePath = path.join(directory, file);
await fsPromises.unlink(filePath);
@@ -182,14 +182,14 @@ class MaintenanceService {
* @param {boolean} [dry=false] - if true only return the count
*/
async deleteOrphanPeople(dry = false) {
const { Sequelize } = require('sequelize');
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',
as: "roles",
required: false,
},
],
@@ -222,9 +222,9 @@ class MaintenanceService {
include: [
{
model: Credit,
as: 'credits',
where: { cast_type: 'crew', job: 'Director' },
include: [{ model: People, as: 'person', attributes: ['name'] }],
as: "credits",
where: { cast_type: "crew", job: "Director" },
include: [{ model: People, as: "person", attributes: ["name"] }],
required: false,
},
],
@@ -257,20 +257,20 @@ class MaintenanceService {
* @param {boolean} [dry=false] - if true only count, if false also delete
*/
async cleanDuplicateCredits(dry = false) {
const { Sequelize } = require('sequelize');
const { Sequelize } = require("sequelize");
const duplicates = 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'],
"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'),
group: ["entry_id", "people_id", "cast_type", "character", "job"],
having: Sequelize.literal("COUNT(id) > 1"),
raw: true,
});
@@ -280,7 +280,7 @@ class MaintenanceService {
if (!dry) {
for (const row of duplicates) {
const idList = row.ids
.split(',')
.split(",")
.map(Number)
.sort((a, b) => a - b);
// Keep the newest (highest ID), delete the older ones
@@ -312,23 +312,23 @@ class MaintenanceService {
}
async autoFixWatchStatuses() {
const Episode = require('../models/Episode');
const EpisodeSeen = require('../models/EpisodeSeen');
const Season = require('../models/Season');
const { Op } = require('sequelize');
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',
as: "seasons",
where: { season_number: { [Op.gt]: 0 } },
include: [
{
model: Episode,
as: 'episodes',
include: [{ model: EpisodeSeen, as: 'episodeSeens' }],
as: "episodes",
include: [{ model: EpisodeSeen, as: "episodeSeens" }],
},
],
},
@@ -356,16 +356,16 @@ class MaintenanceService {
const hasSomeWatched = watchedEpisodes > 0;
// Completed but not all watched → downgrade to watching
if (entry.watch_status === 'completed' && !allWatched) {
entry.watch_status = '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';
if (allWatched && entry.watch_status !== "completed") {
entry.watch_status = "completed";
await entry.save();
toCompleted++;
continue;
@@ -373,7 +373,7 @@ class MaintenanceService {
// Has some watched but no status → watching
if (hasSomeWatched && !entry.watch_status) {
entry.watch_status = 'watching';
entry.watch_status = "watching";
await entry.save();
toWatching++;
continue;
@@ -381,7 +381,7 @@ class MaintenanceService {
// In watchlist with no status → plan to watch
if (entry.watchlist && !entry.watch_status) {
entry.watch_status = 'plan_to_watch';
entry.watch_status = "plan_to_watch";
await entry.save();
toPlanToWatch++;
}
@@ -396,6 +396,87 @@ class MaintenanceService {
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 };
}
}
module.exports = new MaintenanceService();