Files
Showy/backend/services/entryManager.js
T
Mohammed Abad ce01dc34fa feat(backend): fix credit duplicates, support multi-role TV credits, fix collection upload
- Fix credit dedup key to people_id + cast_type (scoped to entry_id)
- Detect aggregate_credits format via Array.isArray(c.roles) instead of is_tvseries flag
- Join multiple roles/jobs with "; " instead of taking only the first
- Add episode_count field to Credit model from total_episode_count
- Increase character and job columns to VARCHAR(500)
- Deselect existing collection posters/backdrops before inserting new upload
- Updated docs-vault
- Updated some agents files
2026-04-23 16:51:18 +01:00

739 lines
24 KiB
JavaScript

const moment = require("../utils/moment.js");
const { Op } = require("sequelize");
const Entry = require("../models/Entry.js");
const Episode = require("../models/Episode.js");
const Season = require("../models/Season.js");
const EntryGenre = require("../models/EntryGenre.js");
const EntryId = require("../models/EntryId.js");
const EntryRating = require("../models/EntryRating.js");
const EntrySeen = require("../models/EntrySeen.js");
const Media = require("../models/Media.js");
const Genre = require("../models/Genre.js");
const People = require("../models/People.js");
const Credit = require("../models/Credit.js");
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 { logToFile } = require("./logService.js");
const collectionManager = require('./collectionManager.js');
const entryService = require("./entryService");
const mediaManager = require("./mediaManager.js");
const networkService = require("./networkService.js");
const InternalServerError = require("../errors/InternalServerError.js");
const _collectionManager = collectionManager;
const _entryService = entryService;
const _mediaManager = mediaManager;
const _networkService = networkService;
class EntryManager {
constructor() {
if (!EntryManager.instance) {
EntryManager.instance = this;
}
return EntryManager.instance;
}
// todo: change fetchEntryData to TMDBService.fetchEntryData()
async fetchAndSaveNewEntry(id, type, fetchCollection = true, plain = true) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
if (typeof type !== "boolean") {
throw new BadRequestError(`Invalid type: ${type}. Expected a boolean value.`);
}
// * 1 - fetch entry data
const entryData = await fetchEntryData(id, type);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// * 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);
// * 3 - created the related collection
if (entryData.belongs_to_collection && fetchCollection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
}
return entry;
}
// todo: change fetchEntryData to TMDBService.fetchEntryData()
// todo: change fetchEntryData to TMDBService.fetchSeasonData()
// todo: change fetchEntryData to TMDBService.fetchEntryCredits()
// todo: change fetchEntryData to TMDBService.fetchPersonDetails()
async refrechEntryById(id, plain = true) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
// ? checking if the provied id is valid
// ! note: the includes are required for the update
const oldEntry = await _entryService.getEntryById(id, false);
if (!oldEntry) {
throw new NotFoundError("Entry not found");
}
// ? getting new data from TMDB
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// ! the refrech logic
let newData = {
title: entryData.title || entryData.name,
original_title: entryData.original_title || entryData.original_name,
release_date: entryData.release_date || entryData.first_air_date,
release_status: entryData.status,
runtime: entryData.runtime || null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
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()
};
const savedEntry = await _entryService.updateEntryById(id, newData, false);
// * updating ids
// TODO: get more ids
await oldEntry.entryId.update({
imdb_id: entryData.imdb_id,
});
// * updating ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
});
// * updating genres
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;
// otherwise assign the genre to the entry
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
});
// * networks
if (entryData.networks) {
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);
let network = oldNetwork || newNetwork;
if (!network) {
throw new NotFoundError("Network not found");
}
// Associate the new network with the entry
await oldEntry.addNetwork(network);
}
}
// * For TV-Series (Seasons & Episodes)
if (oldEntry.is_tvseries) {
// ? Only refrech if the series's status is not 'Ended'
// ? and atleast 48 hours has passed
// * 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);
// Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({
where: {
tmdb_id: season.id
},
include: [
{ model: Media, as: 'medias' }
]
});
// If the season exists, update it; otherwise, create a new season
if (existingSeason) {
// Update existing season data
existingSeason.tmdb_id = seasonData.id;
existingSeason.name = seasonData.name;
existingSeason.overview = seasonData.overview;
existingSeason.episode_count = seasonData.episodes.length;
existingSeason.air_date = seasonData.air_date;
existingSeason.tmdb_rating = seasonData.vote_average;
existingSeason.poster_path = seasonData.poster_path;
existingSeason.banner_path = null;
// Save the updated season
await existingSeason.save();
} else {
// Create a new season
existingSeason = await Season.create({
tmdb_id: seasonData.id,
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
}
if (!existingSeason.medias || existingSeason.medias.length == 0)
_mediaManager.getSeasonMedia(existingSeason);
// * Update or insert episodes for the season
for (const episode of seasonData.episodes) {
// Fetch existing episode data if it exists
let existingEpisode = await Episode.findOne({
where: {
tmdb_id: episode.id,
},
include: [
{ model: Media, as: 'medias' }
]
});
// If the episode exists, update it; otherwise, create a new episode
if (existingEpisode) {
// Update existing episode data
existingEpisode.tmdb_id = episode.tmdb_id;
existingEpisode.name = episode.name;
existingEpisode.overview = episode.overview;
existingEpisode.episode_type = episode.episode_type;
existingEpisode.runtime = episode.runtime;
existingEpisode.air_date = episode.air_date;
existingEpisode.tmdb_rating = episode.vote_average;
existingEpisode.still_path = episode.still_path;
// Updated episode
await existingEpisode.save();
} else {
// Create a new episode
existingEpisode = await Episode.create({
tmdb_id: episode.id,
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
}
if (!existingEpisode.medias || existingEpisode.medias.length == 0)
_mediaManager.getEpisodenMedia(existingEpisode);
}
}
}
// * Credits
// if (!oldEntry.cast_fetched || oldEntry.credits.length === 0) {
if (true) {
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" }))
];
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]));
// -------------------------
// CREATE NEW PEOPLE
// -------------------------
const newPeopleData = tmdbIds
.filter(id => !existingPeopleMap[id])
.map(id => {
const credit = allCredits.find(c => c.id === id);
return {
tmdb_id: credit.id,
name: credit.name,
gender: credit.gender || null,
popularity: credit.popularity,
known_for_department: credit.known_for_department || null,
profile_path: credit.profile_path,
adult: credit.adult || false,
last_fetch: new Date()
};
});
if (newPeopleData.length) {
console.log(`[PEOPLE] Adding ${newPeopleData.length} new people...`);
}
const createdPeople = await People.bulkCreate(newPeopleData);
for (const person of createdPeople) {
console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`);
existingPeopleMap[person.tmdb_id] = person;
}
// -------------------------
// UPDATE EXISTING PEOPLE POPULARITY
// -------------------------
const peopleToUpdate = [];
for (const credit of allCredits) {
const existingPerson = existingPeopleMap[credit.id];
if (!existingPerson) continue;
// only update if changed
if (existingPerson.popularity !== credit.popularity) {
existingPerson.popularity = credit.popularity;
existingPerson.last_fetch = new Date();
// TODO: update person photo and add a new field to track the last photo update
peopleToUpdate.push(existingPerson);
}
}
if (peopleToUpdate.length) {
await People.bulkCreate(
peopleToUpdate.map(p => ({
id: p.id,
tmdb_id: p.tmdb_id,
popularity: p.popularity,
last_fetch: p.last_fetch
})),
{
updateOnDuplicate: ["popularity", "last_fetch"]
}
);
console.log(`[PEOPLE] Updated popularity for ${peopleToUpdate.length} people`);
}
// -------------------------
// FETCH EXISTING CREDITS FOR ENTRY
// -------------------------
const existingCreditsList = await Credit.findAll({
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);
}
const creditsToInsert = [];
const creditsToUpdate = [];
for (const c of allCredits) {
const person = existingPeopleMap[c.id];
if (!person) continue;
const key = `${person.id}_${c.cast_type}`;
const existingCredit = existingCreditsMap.get(key);
// 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 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
: Array.isArray(c.jobs)
? c.jobs?.[0]?.credit_id
: c.credit_id;
const newCreditData = {
entry_id: oldEntry.id,
people_id: person.id,
tmdb_credit_id: tmdbCreditId,
character,
order: c.cast_type === "cast" ? c.order : null,
episode_count: c.total_episode_count ?? null,
profile_path: person.profile_path,
adult: person.adult,
cast_type: c.cast_type,
department: c.cast_type === "crew" ? c.department || null : null,
job
};
if (!existingCredit) {
creditsToInsert.push(newCreditData);
console.log(
`[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.job !== newCreditData.job) changed = true;
if (existingCredit.episode_count !== newCreditData.episode_count) changed = true;
if (changed) {
creditsToUpdate.push({
id: existingCredit.id,
...newCreditData
});
console.log(
`[CREDIT] UPDATE ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`
);
}
}
}
// -------------------------
// INSERT NEW CREDITS
// -------------------------
if (creditsToInsert.length) {
await Credit.bulkCreate(creditsToInsert);
console.log(`[CREDITS] Inserted ${creditsToInsert.length} new credits for entry ${oldEntry.id}`);
}
// -------------------------
// UPDATE EXISTING CREDITS
// -------------------------
if (creditsToUpdate.length) {
await Credit.bulkCreate(creditsToUpdate, {
updateOnDuplicate: ["order", "character", "episode_count", "department", "job", "profile_path", "adult"]
});
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}`);
}
}
// * Media
// ? Only fetch if a Poster, Backdrop or a Logo is missing
// ? only get missing media types
// ? count media by type
let availableMedia = {
'posters': 0,
'logos': 0,
'backdrops': 0
};
for (let i = 0; i < oldEntry.medias.length; i++) {
availableMedia[oldEntry.medias[i].type + 's'] += 1;
}
// ? if the count of a media type == 0, the add the type to mediaToGet
let mediaToGet = [];
for (let key in availableMedia) {
if (availableMedia[key] == 0) mediaToGet.push(key);
}
let downloadedImages;
if (mediaToGet.length != 0) {
downloadedImages = await _mediaManager.getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
}
if (downloadedImages) {
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaableId: oldEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
});
}
}
// ? fetch collection
if (entryData.belongs_to_collection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
}
// + end of: refrech logic
// ! returning the refreshed entry
const refreshedEntry = await _entryService.getEntryById(id, plain);
return refreshedEntry;
}
/**
* Retrieves an entry by its ID and refreshes it if needed.
*
* An entry is refreshed if:
* - It has never been fetched before (`last_fetch` is null or undefined), or
* - The last fetch was more than 24 hours ago.
*
* If a refresh is required, it logs the operation and calls `refrechEntryById`.
*
* @async
* @function getUpdatedEntry
* @param {number} id - The ID of the entry to retrieve.
* @returns {Promise<Object>} The entry object, either current or refreshed.
*/
async getUpdatedEntry(id) {
let entry = await _entryService.getEntryById(id, false);
let doRefrech = false;
if (!entry.last_fetch) {
doRefrech = true;
} else {
// check if the last fetch was more than 24 hours ago
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')) {
doRefrech = true;
}
}
if (doRefrech) {
logToFile(`Refrech Entry: ${entry.id} - ${entry.title}`);
entry = await this.refrechEntryById(id, true);
}
return entry;
}
/** 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 entries = await Entry.findAll({
where: {
is_tvseries: true,
autoSync: true,
last_fetch: {
[Op.ne]: today
},
status: {
[Op.notIn]: [
'Ended',
'Canceled'
]
},
},
});
logToFile(`Started syncing ${entries.length} Tv-Series`);
const results = await Promise.all(
entries.map(entry => this.SyncSerieData(entry.id))
);
logToFile(`Syncing Tv-Series Finished`);
return results;
}
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: Genre,
as: 'genres',
attributes: ['id'],
through: {
attributes: []
}
}
]
});
logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`)
if (!oldEntry)
throw NotFoundError('Entry Not Found');
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData)
throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data
let newData = {
title: entryData.title || entryData.name,
original_title: entryData.original_title || entryData.original_name,
release_date: entryData.release_date || entryData.first_air_date,
runtime: entryData.runtime || null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
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()
};
await oldEntry.update(newData);
// ! 2 - Ids
// TODO: get more ids
await oldEntry.entryId.update({
imdb_id: entryData.imdb_id,
});
// ! 3 - Ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
});
// ! 4 - Genres
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
})
}
});
// ! 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));
for (const season of entryData.seasons) {
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);
// * find or create the season
const [oldSeason, createdSeason] = await Season.findOrCreate({
where: { tmdb_id: season.id },
defaults: {
tmdb_id: seasonData.id,
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
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
if (!createdSeason) {
await oldSeason.update({
tmdb_id: seasonData.id,
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
}
// * forging updated/created season into a variable
let existingSeason = oldSeason || createdSeason;
// ! 6 - Episodes
for (const episode of seasonData.episodes) {
// * find or create the episode
const [oldEpisode, createdEpisode] = await Episode.findOrCreate({
where: { tmdb_id: episode.id },
defaults: {
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
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
if (!createdEpisode) {
await oldEpisode.update({
tmdb_id: episode.id,
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
}
}
}
}
await oldEntry.reload();
return oldEntry;
}
}
module.exports = new EntryManager();