587 lines
17 KiB
JavaScript
587 lines
17 KiB
JavaScript
const Entry = require('../models/Entry.js')
|
|
const EntryId = require('../models/EntryId.js')
|
|
const EntryRating = require('../models/EntryRating.js');
|
|
const Season = require('../models/Season.js');
|
|
const EntryGenre = require('../models/EntryGenre.js');
|
|
const EntrySeen = require('../models/EntrySeen.js');
|
|
const Episode = require('../models/Episode.js');
|
|
const Media = require('../models/Media.js');
|
|
|
|
const NotFoundError = require('../errors/NotFoundError.js');
|
|
const InternalServerError = require('../errors/InternalServerError.js');
|
|
|
|
const { fetchSeasonData, fetchEntryData } = require('./tmdbService.js');
|
|
const { getEntryMedia } = require('./mediaService.js');
|
|
const Genre = require('../models/Genre.js');
|
|
|
|
async function saveEntry(data) {
|
|
try {
|
|
if (data == null) return;
|
|
|
|
// creating the object
|
|
var is_tvseries = data.release_date == null ? true : false;
|
|
|
|
let movie = Entry.build({
|
|
title: data.title || data.name,
|
|
original_title: data.original_title || data.original_name,
|
|
release_date: data.release_date || data.first_air_date,
|
|
release_status: data.status,
|
|
runtime: data.runtime || null,
|
|
|
|
tagline: data.tagline || null,
|
|
storyline: data.overview,
|
|
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
|
|
|
is_tvseries: is_tvseries,
|
|
watchlist: true,
|
|
status: data.status,
|
|
|
|
genres: data.genre_ids,
|
|
|
|
poster_path: data.poster_path,
|
|
banner_path: data.backdrop_path,
|
|
|
|
last_fetch: new Date()
|
|
});
|
|
|
|
const savedEntry = await movie.save();
|
|
|
|
// ? ids
|
|
const ids = await EntryId.create({
|
|
entry_id: savedEntry.id,
|
|
tmdb_id: data.id,
|
|
imdb_id: data.imdb_id,
|
|
});
|
|
|
|
// ? genres
|
|
data.genres.forEach(async (genre) => {
|
|
await EntryGenre.create({
|
|
genre_id: genre.id,
|
|
entry_id: savedEntry.id
|
|
})
|
|
});
|
|
|
|
// ? ratings
|
|
const ratings = await EntryRating.create({
|
|
entry_id: savedEntry.id,
|
|
user_rating: 0,
|
|
tmdb_rating: data.vote_average,
|
|
});
|
|
|
|
// ! seasons & episodes for tv series
|
|
if (is_tvseries) {
|
|
// * seasons
|
|
let seasons = [];
|
|
for (const season of data.seasons) {
|
|
let seasonData = await fetchSeasonData(data.id, season.season_number);
|
|
const savedSeason = await Season.create({
|
|
tmdb_id: seasonData.id,
|
|
|
|
entry_id: savedEntry.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,
|
|
})
|
|
|
|
// * episodes
|
|
let episodes = [];
|
|
for (const episode of seasonData.episodes) {
|
|
const savedEpisode = await Episode.create({
|
|
tmdb_id: episode.id,
|
|
|
|
season_id: savedSeason.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,
|
|
});
|
|
|
|
episodes.push(savedEpisode);
|
|
}
|
|
|
|
// TODO fetch cast
|
|
|
|
savedSeason.setDataValue('episodes', episodes);
|
|
seasons.push(savedSeason)
|
|
}
|
|
savedEntry.setDataValue('seasons', seasons);
|
|
}
|
|
// + end of: seasons & episodes for tv series
|
|
|
|
// ? cast
|
|
|
|
|
|
// ? images
|
|
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
|
|
console.log(`entry service, downloaded images: `, downloadedImages)
|
|
for (const image of downloadedImages) {
|
|
await Media.create({
|
|
entry_id: savedEntry.id,
|
|
type: image.type,
|
|
path: image.path,
|
|
is_local: true,
|
|
is_selected: true
|
|
})
|
|
}
|
|
|
|
|
|
const currentGenresNames = await data.genres.map(genre => genre.name);
|
|
|
|
savedEntry.setDataValue('entryId', ids);
|
|
savedEntry.setDataValue('entryRating', ratings);
|
|
savedEntry.setDataValue('genres', currentGenresNames);
|
|
|
|
return savedEntry;
|
|
} catch (error) {
|
|
console.log(`Error saving entry (in entry serive): `, error);
|
|
return null
|
|
}
|
|
}
|
|
|
|
async function updateEntry(oldEntry, data) {
|
|
let newData = {
|
|
title: data.title || data.name,
|
|
original_title: data.original_title || data.original_name,
|
|
release_date: data.release_date || data.first_air_date,
|
|
runtime: data.runtime || null,
|
|
|
|
tagline: data.tagline || null,
|
|
storyline: data.overview,
|
|
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
|
|
|
status: data.status,
|
|
|
|
poster_path: data.poster_path,
|
|
banner_path: data.backdrop_path,
|
|
};
|
|
|
|
const savedEntry = await oldEntry.update(newData);
|
|
|
|
// update ids
|
|
// TODO: get more ids
|
|
// [affectedCount, affectedRows]
|
|
const ids = await oldEntry.entryId.update({
|
|
imdb_id: data.imdb_id,
|
|
});
|
|
|
|
// update ratings
|
|
const ratings = await oldEntry.entryRating.update({
|
|
tmdb_rating: data.vote_average
|
|
});
|
|
|
|
// update genres
|
|
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
|
let currentGenresNames = [];
|
|
data.genres.forEach(async (genre) => {
|
|
// add genres names to an array so it can be returned with the entry object
|
|
currentGenresNames.push(genre.name);
|
|
|
|
// 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
|
|
})
|
|
});
|
|
|
|
// fetch entry-seens
|
|
const entrySeens = await EntrySeen.findAll({ where: { entry_id: oldEntry.id } });
|
|
|
|
// TODO: refrech seasons
|
|
if (oldEntry.is_tvseries) {
|
|
let updatedSeasons = [];
|
|
|
|
for (const season of data.seasons) {
|
|
// fetch new season data from tmdb
|
|
let seasonData = await fetchSeasonData(data.id, season.season_number);
|
|
|
|
// Fetch existing season if it exists (using tmdb_id)
|
|
let existingSeason = await Season.findOne({
|
|
where: {
|
|
tmdb_id: season.id
|
|
}
|
|
});
|
|
|
|
// 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
|
|
const savedSeason = 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,
|
|
});
|
|
|
|
// Add the newly created season to the list of updated seasons
|
|
existingSeason = savedSeason;
|
|
}
|
|
|
|
// Update or insert episodes for the season
|
|
let updatedEpisodes = [];
|
|
for (const episode of seasonData.episodes) {
|
|
// Fetch existing episode data if it exists
|
|
let existingEpisode = await Episode.findOne({
|
|
where: {
|
|
tmdb_id: episode.id,
|
|
}
|
|
});
|
|
|
|
// 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;
|
|
|
|
// Save the updated episode
|
|
await existingEpisode.save();
|
|
} else {
|
|
// Create a new episode
|
|
const savedEpisode = 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,
|
|
});
|
|
|
|
// Add the newly created episode to the list of updated episodes
|
|
existingEpisode = savedEpisode;
|
|
}
|
|
|
|
updatedEpisodes.push(existingEpisode);
|
|
}
|
|
|
|
// Update the episodes of the current season
|
|
existingSeason.setDataValue('episodes', updatedEpisodes);
|
|
updatedSeasons.push(existingSeason);
|
|
}
|
|
|
|
// Update the seasons of the movie
|
|
savedEntry.setDataValue('seasons', updatedSeasons);
|
|
}
|
|
|
|
|
|
savedEntry.setDataValue('entryId', ids);
|
|
savedEntry.setDataValue('entryRating', ratings);
|
|
savedEntry.setDataValue('genres', currentGenresNames);
|
|
savedEntry.setDataValue('entrySeen', entrySeens);
|
|
|
|
return savedEntry;
|
|
}
|
|
|
|
async function refrechEntry(entryId) {
|
|
// ? checking if the provied id is valid
|
|
// ! note: the includes are required for the update
|
|
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: []
|
|
}
|
|
}
|
|
]
|
|
});
|
|
|
|
if (!oldEntry) {
|
|
throw new NotFoundError("Entry not found");
|
|
}
|
|
|
|
// ? getting new data from TMDB
|
|
const data = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
|
if (data == null) {
|
|
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
|
}
|
|
|
|
// ! the refrech logic
|
|
let newData = {
|
|
title: data.title || data.name,
|
|
original_title: data.original_title || data.original_name,
|
|
release_date: data.release_date || data.first_air_date,
|
|
release_status: data.status,
|
|
runtime: data.runtime || null,
|
|
|
|
tagline: data.tagline || null,
|
|
storyline: data.overview,
|
|
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
|
|
|
status: data.status,
|
|
|
|
poster_path: data.poster_path,
|
|
banner_path: data.backdrop_path,
|
|
|
|
last_fetch: new Date()
|
|
};
|
|
|
|
const savedEntry = await oldEntry.update(newData);
|
|
|
|
// * updating ids
|
|
// TODO: get more ids
|
|
await oldEntry.entryId.update({
|
|
imdb_id: data.imdb_id,
|
|
});
|
|
|
|
// * updating ratings
|
|
await oldEntry.entryRating.update({
|
|
tmdb_rating: data.vote_average
|
|
});
|
|
|
|
// * updating genres
|
|
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
|
data.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
|
|
})
|
|
});
|
|
|
|
|
|
// * 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 data.seasons) {
|
|
// fetch new season data from tmdb
|
|
let seasonData = await fetchSeasonData(data.id, season.season_number);
|
|
|
|
// Fetch existing season if it exists (using tmdb_id)
|
|
let existingSeason = await Season.findOne({
|
|
where: {
|
|
tmdb_id: season.id
|
|
}
|
|
});
|
|
|
|
// 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
|
|
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,
|
|
});
|
|
}
|
|
|
|
// * 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,
|
|
}
|
|
});
|
|
|
|
// 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
|
|
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,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// * Cast
|
|
// ? Only fetch if the cast count is 0 or less than max_cast
|
|
// TODO add cast refrech
|
|
// if (!oldEntry.casts || oldEntry.casts.length == 0 || oldEntry.casts.length < oldEntry.max_cast) {
|
|
// }
|
|
|
|
// * Updating Media : Only fetch if a Poster, Backdrop or a Logo is missing
|
|
let downloadedImages;
|
|
if (oldEntry.medias.length == 0) {
|
|
// ? if no media is available, directly get all
|
|
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries);
|
|
} else {
|
|
// ? only get missing media types
|
|
let availableMedia = {
|
|
'posters': 0,
|
|
'logos': 0,
|
|
'backdrops': 0
|
|
};
|
|
|
|
// ? count media by type
|
|
for (let i = 0; i < oldEntry.medias.length; i++) {
|
|
availableMedia[oldEntry.medias[i].type] += 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(availableMedia[key]);
|
|
}
|
|
|
|
if (mediaToGet.length != 0) {
|
|
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries, mediaToGet);
|
|
}
|
|
}
|
|
|
|
if (downloadedImages) {
|
|
for (const image of downloadedImages) {
|
|
await Media.create({
|
|
entry_id: oldEntry.id,
|
|
type: image.type,
|
|
path: image.path,
|
|
is_local: true,
|
|
is_selected: true
|
|
})
|
|
}
|
|
}
|
|
|
|
// + end of: refrech logic
|
|
|
|
// ! returning the refreshed entry
|
|
let includes = [
|
|
{ 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: ['name'],
|
|
through: {
|
|
attributes: []
|
|
}
|
|
}
|
|
];
|
|
if (oldEntry.is_tvseries) includes.push({ model: Season, as: 'seasons' });
|
|
|
|
const updatedEntry = await Entry.findByPk(entryId, {
|
|
include: includes,
|
|
order: [
|
|
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
|
|
]
|
|
});
|
|
|
|
const entryData = updatedEntry.get({ plain: true });
|
|
entryData.genres = entryData.genres.map(genre => genre.name);
|
|
|
|
return entryData;
|
|
}
|
|
|
|
async function getEntry(id) {
|
|
return Entry.findByPk(id);
|
|
}
|
|
|
|
async function deleteEntry(id) {
|
|
await Entry.destroy({
|
|
where: {
|
|
id: id
|
|
}
|
|
});
|
|
}
|
|
|
|
module.exports = {
|
|
saveEntry,
|
|
updateEntry,
|
|
refrechEntry,
|
|
getEntry,
|
|
deleteEntry,
|
|
} |