Director field, search, and collection improvements

Backend: Added director column to Entry model, set during creation and
refresh. Maintenance endpoint to scan/fix missing directors. Reverted
expensive credit JOIN in getAllEntries.

Frontend: @director: search prefix for Library and Watchlist. Director
rendered on EntryDetailsPage via useEntryCredits. Fixed home page cards
to link directly to EntryDetailsPage when entry is in library. Added
TmdbCastsPage for TMDB cast browsing. Persisted collection sort order
and gray-out-unseen toggle. Tooltip component now theme-aware.
This commit is contained in:
X4Lo committed 2026-06-18 20:09:11 +01:00
1 parent 8671184dc5
commit 5a0328a17f
16 files changed
+1679 -629

No files matched your search

+193 -107
View File
@@ -17,9 +17,13 @@ const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError.js");
const ValidationError = require("../errors/ValidationError.js");
const { fetchEntryData, fetchSeasonData, fetchEntryCredits } = require("./tmdbService.js");
const {
fetchEntryData,
fetchSeasonData,
fetchEntryCredits,
} = require("./tmdbService.js");
const { logToFile } = require("./logService.js");
const collectionManager = require('./collectionManager.js');
const collectionManager = require("./collectionManager.js");
const entryService = require("./entryService");
const mediaManager = require("./mediaManager.js");
const networkService = require("./networkService.js");
@@ -30,7 +34,6 @@ const _entryService = entryService;
const _mediaManager = mediaManager;
const _networkService = networkService;
class EntryManager {
constructor() {
if (!EntryManager.instance) {
EntryManager.instance = this;
@@ -45,7 +48,9 @@ class EntryManager {
}
if (typeof type !== "boolean") {
throw new BadRequestError(`Invalid type: ${type}. Expected a boolean value.`);
throw new BadRequestError(
`Invalid type: ${type}. Expected a boolean value.`,
);
}
// * 1 - fetch entry data
@@ -57,10 +62,19 @@ class EntryManager {
// * 2 - insert the entry into db
const entry = await _entryService.createEntry(entryData, plain);
console.log('Entry created with ID:', entry.id, 'and title:', entry.title, 'and is_tvseries:', entry.is_tvseries);
console.log(
"Entry created with ID:",
entry.id,
"and title:",
entry.title,
"and is_tvseries:",
entry.is_tvseries,
);
// * 3 - created the related collection
if (entryData.belongs_to_collection && fetchCollection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
await _collectionManager.fetchAndSaveCollection(
entryData.belongs_to_collection.id,
);
}
return entry;
@@ -84,7 +98,10 @@ class EntryManager {
}
// ? getting new data from TMDB
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
const entryData = await fetchEntryData(
oldEntry.entryId.tmdb_id,
oldEntry.is_tvseries,
);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
@@ -99,14 +116,17 @@ class EntryManager {
tagline: entryData.tagline || null,
storyline: entryData.overview,
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
country:
entryData.production_countries.length > 0
? entryData.production_countries[0].name
: null,
status: entryData.status,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date()
last_fetch: new Date(),
};
const savedEntry = await _entryService.updateEntryById(id, newData, false);
@@ -119,11 +139,11 @@ class EntryManager {
// * updating ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
tmdb_rating: entryData.vote_average,
});
// * updating genres
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
entryData.genres.forEach(async (genre) => {
// if the entry already has this genre then skip
if (currentGenresIds.includes(genre.id)) return;
@@ -131,19 +151,20 @@ class EntryManager {
// otherwise assign the genre to the entry
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
entry_id: savedEntry.id,
});
});
// * networks
if (entryData.networks) {
const oldNetworksIds = oldEntry.networks.map(network => network.id);
const oldNetworksIds = oldEntry.networks.map((network) => network.id);
for (const networkData of entryData.networks) {
// If the entry already has this network, skip it
if (oldNetworksIds.includes(networkData.id)) continue;
// Create or update the network
const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData);
const [oldNetwork, newNetwork] =
await _networkService.createOrUpdateNetwork(networkData);
let network = oldNetwork || newNetwork;
if (!network) {
throw new NotFoundError("Network not found");
@@ -162,16 +183,17 @@ class EntryManager {
// * Update or insert seasons for the entry
for (const season of entryData.seasons) {
// fetch new season data from tmdb
let seasonData = await fetchSeasonData(entryData.id, season.season_number);
let seasonData = await fetchSeasonData(
entryData.id,
season.season_number,
);
// Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({
where: {
tmdb_id: season.id
tmdb_id: season.id,
},
include: [
{ model: Media, as: 'medias' }
]
include: [{ model: Media, as: "medias" }],
});
// If the season exists, update it; otherwise, create a new season
@@ -215,9 +237,7 @@ class EntryManager {
where: {
tmdb_id: episode.id,
},
include: [
{ model: Media, as: 'medias' }
]
include: [{ model: Media, as: "medias" }],
});
// If the episode exists, update it; otherwise, create a new episode
@@ -259,32 +279,39 @@ class EntryManager {
// * Credits
// if (!oldEntry.cast_fetched || oldEntry.credits.length === 0) {
if (true) {
const creditData = await fetchEntryCredits(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
const creditData = await fetchEntryCredits(
oldEntry.entryId.tmdb_id,
oldEntry.is_tvseries,
);
if (!creditData) {
throw new InternalServerError(`Couldn't fetch entry crew data`);
}
const allCredits = [
...creditData.cast.map(c => ({ ...c, cast_type: "cast" })),
...creditData.crew.map(c => ({ ...c, cast_type: "crew" }))
...creditData.cast.map((c) => ({ ...c, cast_type: "cast" })),
...creditData.crew.map((c) => ({ ...c, cast_type: "crew" })),
];
const tmdbIds = [...new Set(allCredits.map(c => c.id))];
const tmdbIds = [...new Set(allCredits.map((c) => c.id))];
// -------------------------
// FETCH EXISTING PEOPLE
// -------------------------
const existingPeopleList = await People.findAll({ where: { tmdb_id: tmdbIds } });
const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p]));
const existingPeopleList = await People.findAll({
where: { tmdb_id: tmdbIds },
});
const existingPeopleMap = Object.fromEntries(
existingPeopleList.map((p) => [p.tmdb_id, p]),
);
// -------------------------
// CREATE NEW PEOPLE
// -------------------------
const newPeopleData = tmdbIds
.filter(id => !existingPeopleMap[id])
.map(id => {
const credit = allCredits.find(c => c.id === id);
.filter((id) => !existingPeopleMap[id])
.map((id) => {
const credit = allCredits.find((c) => c.id === id);
return {
tmdb_id: credit.id,
name: credit.name,
@@ -293,7 +320,7 @@ class EntryManager {
known_for_department: credit.known_for_department || null,
profile_path: credit.profile_path,
adult: credit.adult || false,
last_fetch: new Date()
last_fetch: new Date(),
};
});
@@ -304,7 +331,9 @@ class EntryManager {
const createdPeople = await People.bulkCreate(newPeopleData);
for (const person of createdPeople) {
console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`);
console.log(
`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`,
);
existingPeopleMap[person.tmdb_id] = person;
}
@@ -328,31 +357,36 @@ class EntryManager {
if (peopleToUpdate.length) {
await People.bulkCreate(
peopleToUpdate.map(p => ({
peopleToUpdate.map((p) => ({
id: p.id,
tmdb_id: p.tmdb_id,
popularity: p.popularity,
last_fetch: p.last_fetch
last_fetch: p.last_fetch,
})),
{
updateOnDuplicate: ["popularity", "last_fetch"]
}
updateOnDuplicate: ["popularity", "last_fetch"],
},
);
console.log(`[PEOPLE] Updated popularity for ${peopleToUpdate.length} people`);
console.log(
`[PEOPLE] Updated popularity for ${peopleToUpdate.length} people`,
);
}
// -------------------------
// FETCH EXISTING CREDITS FOR ENTRY
// -------------------------
const existingCreditsList = await Credit.findAll({
where: { entry_id: oldEntry.id }
where: { entry_id: oldEntry.id },
});
const existingCreditsMap = new Map();
for (const credit of existingCreditsList) {
// unique key: people_id + cast_type (scoped to entry_id already)
existingCreditsMap.set(`${credit.people_id}_${credit.cast_type}`, credit);
existingCreditsMap.set(
`${credit.people_id}_${credit.cast_type}`,
credit,
);
}
const creditsToInsert = [];
@@ -367,17 +401,25 @@ class EntryManager {
// For TV series (aggregate_credits), character/job are nested inside roles[]/jobs[].
// Detect TV format by presence of roles/jobs arrays rather than relying on is_tvseries.
const character = c.cast_type === "cast"
? (Array.isArray(c.roles)
? (c.roles.map(r => r.character).filter(Boolean).join("; ") || null)
: (c.character || null))
: null;
const character =
c.cast_type === "cast"
? Array.isArray(c.roles)
? c.roles
.map((r) => r.character)
.filter(Boolean)
.join("; ") || null
: c.character || null
: null;
const job = c.cast_type === "crew"
? (Array.isArray(c.jobs)
? (c.jobs.map(j => j.job).filter(Boolean).join("; ") || null)
: (c.job || null))
: null;
const job =
c.cast_type === "crew"
? Array.isArray(c.jobs)
? c.jobs
.map((j) => j.job)
.filter(Boolean)
.join("; ") || null
: c.job || null
: null;
const tmdbCreditId = Array.isArray(c.roles)
? c.roles?.[0]?.credit_id
@@ -396,32 +438,35 @@ class EntryManager {
adult: person.adult,
cast_type: c.cast_type,
department: c.cast_type === "crew" ? c.department || null : null,
job
job,
};
if (!existingCredit) {
creditsToInsert.push(newCreditData);
console.log(
`[CREDIT] INSERT ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`
`[CREDIT] INSERT ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`,
);
} else {
// check if update needed
let changed = false;
if (existingCredit.order !== newCreditData.order) changed = true;
if (existingCredit.character !== newCreditData.character) changed = true;
if (existingCredit.department !== newCreditData.department) changed = true;
if (existingCredit.character !== newCreditData.character)
changed = true;
if (existingCredit.department !== newCreditData.department)
changed = true;
if (existingCredit.job !== newCreditData.job) changed = true;
if (existingCredit.episode_count !== newCreditData.episode_count) changed = true;
if (existingCredit.episode_count !== newCreditData.episode_count)
changed = true;
if (changed) {
creditsToUpdate.push({
id: existingCredit.id,
...newCreditData
...newCreditData,
});
console.log(
`[CREDIT] UPDATE ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`
`[CREDIT] UPDATE ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`,
);
}
}
@@ -432,7 +477,9 @@ class EntryManager {
// -------------------------
if (creditsToInsert.length) {
await Credit.bulkCreate(creditsToInsert);
console.log(`[CREDITS] Inserted ${creditsToInsert.length} new credits for entry ${oldEntry.id}`);
console.log(
`[CREDITS] Inserted ${creditsToInsert.length} new credits for entry ${oldEntry.id}`,
);
}
// -------------------------
@@ -440,15 +487,34 @@ class EntryManager {
// -------------------------
if (creditsToUpdate.length) {
await Credit.bulkCreate(creditsToUpdate, {
updateOnDuplicate: ["order", "character", "episode_count", "department", "job", "profile_path", "adult"]
updateOnDuplicate: [
"order",
"character",
"episode_count",
"department",
"job",
"profile_path",
"adult",
],
});
console.log(`[CREDITS] Updated ${creditsToUpdate.length} credits for entry ${oldEntry.id}`);
console.log(
`[CREDITS] Updated ${creditsToUpdate.length} credits for entry ${oldEntry.id}`,
);
}
if (!creditsToInsert.length && !creditsToUpdate.length) {
console.log(`[CREDITS] No changes for entry ${oldEntry.id}`);
}
// Set director from processed credits
const directorCredit = allCredits.find(
(c) => c.cast_type === "crew" && c.job === "Director",
);
if (directorCredit) {
oldEntry.director = directorCredit.name || null;
await oldEntry.save();
}
}
// * Media
@@ -457,12 +523,12 @@ class EntryManager {
// ? count media by type
let availableMedia = {
'posters': 0,
'logos': 0,
'backdrops': 0
posters: 0,
logos: 0,
backdrops: 0,
};
for (let i = 0; i < oldEntry.medias.length; i++) {
availableMedia[oldEntry.medias[i].type + 's'] += 1;
availableMedia[oldEntry.medias[i].type + "s"] += 1;
}
// ? if the count of a media type == 0, the add the type to mediaToGet
@@ -473,25 +539,31 @@ class EntryManager {
let downloadedImages;
if (mediaToGet.length != 0) {
downloadedImages = await _mediaManager.getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
downloadedImages = await _mediaManager.getEntryMedia(
entryData.id,
oldEntry.is_tvseries,
mediaToGet,
);
}
if (downloadedImages) {
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaable: "entry",
mediaableId: oldEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
isSelected: true,
});
}
}
// ? fetch collection
if (entryData.belongs_to_collection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
await _collectionManager.fetchAndSaveCollection(
entryData.belongs_to_collection.id,
);
}
// + end of: refrech logic
@@ -527,7 +599,10 @@ class EntryManager {
const lastFetchDate = new Date(entry.last_fetch);
const currentDate = new Date();
const diffInHours = (currentDate - lastFetchDate) / (1000 * 60 * 60);
if (diffInHours > 24 && !(entry.is_tvseries && entry.status === 'Ended')) {
if (
diffInHours > 24 &&
!(entry.is_tvseries && entry.status === "Ended")
) {
doRefrech = true;
}
}
@@ -541,21 +616,18 @@ class EntryManager {
}
/** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today
*/
*/
async SyncSeriesData() {
const today = moment().format('YYYY-MM-DD');
const today = moment().format("YYYY-MM-DD");
const entries = await Entry.findAll({
where: {
is_tvseries: true,
autoSync: true,
last_fetch: {
[Op.ne]: today
[Op.ne]: today,
},
status: {
[Op.notIn]: [
'Ended',
'Canceled'
]
[Op.notIn]: ["Ended", "Canceled"],
},
},
});
@@ -563,7 +635,7 @@ class EntryManager {
logToFile(`Started syncing ${entries.length} Tv-Series`);
const results = await Promise.all(
entries.map(entry => this.SyncSerieData(entry.id))
entries.map((entry) => this.SyncSerieData(entry.id)),
);
logToFile(`Syncing Tv-Series Finished`);
@@ -573,31 +645,34 @@ class EntryManager {
async SyncSerieData(entryId) {
const oldEntry = await Entry.findByPk(entryId, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
{ model: EntrySeen, as: "entrySeen" },
{ model: Season, as: "seasons" },
{ model: Media, as: "medias" },
{
model: Genre,
as: 'genres',
attributes: ['id'],
as: "genres",
attributes: ["id"],
through: {
attributes: []
}
}
]
attributes: [],
},
},
],
});
logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`)
logToFile(
`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`,
);
if (!oldEntry)
throw NotFoundError('Entry Not Found');
if (!oldEntry) throw NotFoundError("Entry Not Found");
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
const entryData = await fetchEntryData(
oldEntry.entryId.tmdb_id,
oldEntry.is_tvseries,
);
if (!entryData)
throw new ValidationError(`Couldn't Fetch Entry Data`);
if (!entryData) throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data
let newData = {
@@ -608,14 +683,17 @@ class EntryManager {
tagline: entryData.tagline || null,
storyline: entryData.overview,
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
country:
entryData.production_countries.length > 0
? entryData.production_countries[0].name
: null,
status: entryData.status,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date()
last_fetch: new Date(),
};
await oldEntry.update(newData);
@@ -628,30 +706,39 @@ class EntryManager {
// ! 3 - Ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
tmdb_rating: entryData.vote_average,
});
// ! 4 - Genres
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
entryData.genres.forEach(async (genre) => {
// ? only assing the genre if its not already asigned
if (!currentGenresIds.includes(genre.id)) {
await EntryGenre.create({
genre_id: genre.id,
entry_id: oldEntry.id
})
entry_id: oldEntry.id,
});
}
});
// ! 5 - Seasons
// ? only update the last seasons available + season 0 (specials)
if (oldEntry.is_tvseries) {
const latestAvailableSeason = await Math.max(...oldEntry.seasons.map(s => s.season_number));
const latestAvailableSeason = await Math.max(
...oldEntry.seasons.map((s) => s.season_number),
);
for (const season of entryData.seasons) {
if (season.season_number != 0 && season.season_number != latestAvailableSeason) continue;
if (
season.season_number != 0 &&
season.season_number != latestAvailableSeason
)
continue;
// ? fetch new season data from tmdb
let seasonData = await fetchSeasonData(oldEntry.entryId.tmdb_id, season.season_number);
let seasonData = await fetchSeasonData(
oldEntry.entryId.tmdb_id,
season.season_number,
);
// * find or create the season
const [oldSeason, createdSeason] = await Season.findOrCreate({
@@ -668,7 +755,7 @@ class EntryManager {
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
}
},
});
// ? if the season already exist then just update it with new data
@@ -706,7 +793,7 @@ class EntryManager {
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
}
},
});
// ? if the episode already exist then just update it with new data
@@ -732,7 +819,6 @@ class EntryManager {
return oldEntry;
}
}
module.exports = new EntryManager();
+114 -94
View File
@@ -26,7 +26,6 @@ const _mediaOptimizerService = mediaOptimizerService;
const _networkService = networkService;
class EntryService {
constructor() {
if (!EntryService.instance) {
EntryService.instance = this;
@@ -37,26 +36,23 @@ class EntryService {
async getAllEntries() {
const entries = await Entry.findAll({
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Media, as: 'medias' },
{ model: Season, as: 'seasons' },
{ model: Network, as: 'networks' },
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
{ model: Media, as: "medias" },
{ model: Season, as: "seasons" },
{ model: Network, as: "networks" },
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre name
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
]
as: "genres",
attributes: ["name"],
through: { attributes: [] },
},
],
});
// converting genres from object list to string list
const entriesWithGenreNames = entries.map(entry => ({
const entriesWithGenreNames = entries.map((entry) => ({
...entry.get({ plain: true }),
genres: entry.genres.map(genre => genre.name) // Convert genre objects to string array
genres: entry.genres.map((genre) => genre.name),
}));
return entriesWithGenreNames;
@@ -78,31 +74,35 @@ class EntryService {
let entry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Network, as: 'networks' },
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
{ model: EntrySeen, as: "entrySeen" },
{ model: Season, as: "seasons" },
{ model: Media, as: "medias" },
{ model: Network, as: "networks" },
{
model: Cast, as: 'credits',
where: { cast_type: 'cast' },
order: [['episode_count', 'DESC']],
model: Cast,
as: "credits",
order: [
["cast_type", "ASC"],
["order", "ASC"],
],
limit: 10,
include: [{ model: People, as: 'person' }]
include: [{ model: People, as: "person" }],
},
{
model: Collection, as: 'collections',
include: [{ model: Media, as: 'medias' }]
model: Collection,
as: "collections",
include: [{ model: Media, as: "medias" }],
},
{
model: Genre,
as: 'genres',
attributes: ['name', 'id'],
through: { attributes: [] }
}
as: "genres",
attributes: ["name", "id"],
through: { attributes: [] },
},
],
order: [[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC']]
order: [[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"]],
});
if (!entry) {
@@ -111,7 +111,7 @@ class EntryService {
if (plain) {
const plainEntry = entry.get({ plain: true });
plainEntry.genres = plainEntry.genres.map(g => g.name);
plainEntry.genres = plainEntry.genres.map((g) => g.name);
return plainEntry;
}
@@ -130,28 +130,28 @@ class EntryService {
throw new BadRequestError("Entry id not provided");
}
const entry = await Entry.findByPk(id, { attributes: ['id'] });
const entry = await Entry.findByPk(id, { attributes: ["id"] });
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found");
}
const credits = await Credit.findAll({
where: { entry_id: id },
include: [{ model: People, as: 'person' }],
include: [{ model: People, as: "person" }],
order: [
['cast_type', 'ASC'],
['order', 'ASC'],
['episode_count', 'DESC'],
["cast_type", "ASC"],
["order", "ASC"],
["episode_count", "DESC"],
],
});
return credits.map(c => c.get({ plain: true }));
return credits.map((c) => c.get({ plain: true }));
}
async createEntry(data, plain = true) {
// creating the object
var is_tvseries = data.release_date == null ? true : false;
console.log('entryService > createEntry > is_tvseries: ', is_tvseries);
console.log("entryService > createEntry > is_tvseries: ", is_tvseries);
let movie = Entry.build({
title: data.title || data.name,
@@ -162,7 +162,10 @@ class EntryService {
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
is_tvseries: is_tvseries,
watchlist: true,
@@ -173,12 +176,12 @@ class EntryService {
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date()
last_fetch: new Date(),
});
let savedEntry = await movie.save();
console.log('entryService > createEntry > savedEntry: ', savedEntry);
console.log("entryService > createEntry > savedEntry: ", savedEntry);
// ? ids
await EntryId.create({
@@ -191,15 +194,16 @@ class EntryService {
data.genres.forEach(async (genre) => {
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
entry_id: savedEntry.id,
});
});
// ? networks
if (data.networks) {
for (const networkData of data.networks) {
// Create or update the network
const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData);
const [oldNetwork, newNetwork] =
await _networkService.createOrUpdateNetwork(networkData);
let network = oldNetwork || newNetwork;
if (!network) {
throw new NotFoundError("Network not found");
@@ -239,7 +243,7 @@ class EntryService {
poster_path: seasonData.poster_path,
banner_path: null,
})
});
_mediaManager.getSeasonMedia(savedSeason);
@@ -269,10 +273,10 @@ class EntryService {
// TODO fetch cast
savedSeason.setDataValue('episodes', episodes);
seasons.push(savedSeason)
savedSeason.setDataValue("episodes", episodes);
seasons.push(savedSeason);
}
savedEntry.setDataValue('seasons', seasons);
savedEntry.setDataValue("seasons", seasons);
}
// + end of: seasons & episodes for tv series
@@ -283,21 +287,23 @@ class EntryService {
}
const allCredits = [
...creditData.cast.map(c => ({ ...c, cast_type: 'cast' })),
...creditData.crew.map(c => ({ ...c, cast_type: 'crew' })),
...creditData.cast.map((c) => ({ ...c, cast_type: "cast" })),
...creditData.crew.map((c) => ({ ...c, cast_type: "crew" })),
];
const tmdbIds = [...new Set(allCredits.map(c => c.id))];
const tmdbIds = [...new Set(allCredits.map((c) => c.id))];
const existingPeopleList = await People.findAll({
where: { tmdb_id: tmdbIds },
});
const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p]));
const existingPeopleMap = Object.fromEntries(
existingPeopleList.map((p) => [p.tmdb_id, p]),
);
const newPeopleData = tmdbIds
.filter(id => !existingPeopleMap[id])
.map(id => {
const credit = allCredits.find(c => c.id === id);
.filter((id) => !existingPeopleMap[id])
.map((id) => {
const credit = allCredits.find((c) => c.id === id);
return {
tmdb_id: credit.id,
name: credit.name,
@@ -306,7 +312,7 @@ class EntryService {
known_for_department: credit.known_for_department || null,
profile_path: credit.profile_path,
adult: credit.adult || false,
last_fetch: new Date()
last_fetch: new Date(),
};
});
@@ -315,41 +321,55 @@ class EntryService {
existingPeopleMap[person.tmdb_id] = person;
}
const newCredits = allCredits.map(c => {
const newCredits = allCredits.map((c) => {
const person = existingPeopleMap[c.id];
return {
entry_id: savedEntry.id,
people_id: person.id,
tmdb_credit_id: c.credit_id,
character: c.cast_type === 'cast' ? c.character : null,
order: c.cast_type === 'cast' ? c.order : null,
character: c.cast_type === "cast" ? c.character : null,
order: c.cast_type === "cast" ? c.order : null,
profile_path: person.profile_path || null,
adult: person.adult || false,
cast_type: c.cast_type,
department: c.cast_type === 'crew' ? c.department || null : null,
job: c.cast_type === 'crew' ? c.job || null : null,
department: c.cast_type === "crew" ? c.department || null : null,
job: c.cast_type === "crew" ? c.job || null : null,
};
});
await Credit.bulkCreate(newCredits);
savedEntry.credit_fetched = true;
// Extract director name from credits
const directorData = allCredits.find(
(c) => c.cast_type === "crew" && c.job === "Director",
);
savedEntry.director = directorData?.name || null;
await savedEntry.save();
// ? media
const downloadedImages = await _mediaManager.getEntryMedia(data.id, is_tvseries);
const downloadedImages = await _mediaManager.getEntryMedia(
data.id,
is_tvseries,
);
// console.log(`entry service, downloaded images: `, downloadedImages)
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaable: "entry",
mediaableId: savedEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
isSelected: true,
});
_mediaOptimizerService.doGeneratePreview('entries', image.type + 's', image.path);
_mediaOptimizerService.doGeneratePreview(
"entries",
image.type + "s",
image.path,
);
}
// const currentGenresNames = await data.genres.map(genre => genre.name);
@@ -372,7 +392,7 @@ class EntryService {
const oldEntry = await Entry.findByPk(id);
if (!oldEntry) {
throw new NotFoundError("Entry with the provided id was not found")
throw new NotFoundError("Entry with the provided id was not found");
}
await oldEntry.update(entryData);
@@ -388,23 +408,26 @@ class EntryService {
}
let entry = await Entry.findByPk(id, {
include: [
{ model: EntryRating, as: 'entryRating' },
]
include: [{ model: EntryRating, as: "entryRating" }],
});
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found")
throw new NotFoundError("Entry with the provided id was not found");
}
if (entry.entryRating.id != entryRatingsData.id) {
throw new BadRequestError("EntryRatings id does not match");
}
entry.entryRating.user_rating = entryRatingsData.user_rating ?? entry.entryRating.user_rating;
entry.entryRating.tmdb_rating = entryRatingsData.tmdb_rating ?? entry.entryRating.tmdb_rating;
entry.entryRating.imdb_rating = entryRatingsData.imdb_rating ?? entry.entryRating.imdb_rating;
entry.entryRating.rotten_tomatoes_rating = entryRatingsData.rotten_tomatoes_rating ?? entry.entryRating.rotten_tomatoes_rating;
entry.entryRating.user_rating =
entryRatingsData.user_rating ?? entry.entryRating.user_rating;
entry.entryRating.tmdb_rating =
entryRatingsData.tmdb_rating ?? entry.entryRating.tmdb_rating;
entry.entryRating.imdb_rating =
entryRatingsData.imdb_rating ?? entry.entryRating.imdb_rating;
entry.entryRating.rotten_tomatoes_rating =
entryRatingsData.rotten_tomatoes_rating ??
entry.entryRating.rotten_tomatoes_rating;
return await entry.entryRating.save();
}
@@ -415,13 +438,11 @@ class EntryService {
}
let entry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' },
]
include: [{ model: EntryId, as: "entryId" }],
});
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found")
throw new NotFoundError("Entry with the provided id was not found");
}
if (entry.entryRating.id != entryRatingsData.id) {
@@ -441,11 +462,11 @@ class EntryService {
}
const deletedCount = await Entry.destroy({
where: { id: id }
where: { id: id },
});
if (deletedCount == 0) {
throw new NotFoundError("Entry with the provided id was not found")
throw new NotFoundError("Entry with the provided id was not found");
}
return deletedCount;
@@ -458,30 +479,29 @@ class EntryService {
const entry = await Entry.findByPk(id);
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found")
throw new NotFoundError("Entry with the provided id was not found");
}
const seasons = await Season.findAll({
where: {
entry_id: id
entry_id: id,
},
include: [
{
model: Episode, as: 'episodes', include: [
{ model: Media, as: 'medias' }
]
model: Episode,
as: "episodes",
include: [{ model: Media, as: "medias" }],
},
{ model: Media, as: 'medias' }
{ model: Media, as: "medias" },
],
order: [
['season_number', 'ASC'],
[{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'],
]
})
["season_number", "ASC"],
[{ model: Episode, as: "episodes" }, "episode_number", "ASC"],
],
});
return seasons;
}
}
module.exports = new EntryService();
+123 -51
View File
@@ -1,18 +1,18 @@
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 { logToFile } = require('./logService');
const configService = require('./configService');
const { logToFile } = require("./logService");
const configService = require("./configService");
const _configService = configService;
class MaintenanceService {
constructor() {
if (!MaintenanceService.instance) {
MaintenanceService.instance = this;
@@ -21,26 +21,36 @@ class MaintenanceService {
}
/**
* 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`
*/
* 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'),
"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'),
"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')
"season;poster": path.join(dataPath, "images", "seasons", "posters"),
"episode;still": path.join(dataPath, "images", "episodes", "stills"),
};
let missingFiles = [];
@@ -49,26 +59,32 @@ class MaintenanceService {
if (!mediaTypeFolder[folderType]) continue;
const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path)
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,
posters: 0,
logos: 0,
backdrops: 0,
stills: 0,
};
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();
}
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}}`)
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;
}
@@ -83,30 +99,40 @@ class MaintenanceService {
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]
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'),
"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'),
"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')
"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,
posters: 0,
logos: 0,
backdrops: 0,
stills: 0,
};
// Iterate over each media type directory and check for orphan files
@@ -119,14 +145,13 @@ 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);
@@ -138,8 +163,14 @@ class MaintenanceService {
}
}
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}}`)
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;
}
@@ -151,18 +182,22 @@ 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',
required: false,
}],
include: [
{
model: Credit,
as: "roles",
required: false,
},
],
});
const orphans = allPeople.filter(p => (!p.roles || p.roles.length === 0) && !p.pinned);
const orphans = allPeople.filter(
(p) => (!p.roles || p.roles.length === 0) && !p.pinned,
);
if (!dry) {
for (const person of orphans) {
@@ -177,6 +212,43 @@ class MaintenanceService {
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 };
}
}
module.exports = new MaintenanceService();