Back: renamed some services

This commit is contained in:
X4Lo committed 2024-09-10 19:06:05 +01:00
1 parent b35ab48b4f
commit f683e7d00e
2 files changed
+225 -28

No files matched your search

@@ -1,18 +1,21 @@
const Entry = require('../models/Entry.js') const Entry = require('../../models/Entry.js')
const EntryId = require('../models/EntryId.js') const EntryId = require('../../models/EntryId.js')
const EntryRating = require('../models/EntryRating.js'); const EntryRating = require('../../models/EntryRating.js');
const Season = require('../models/Season.js'); const Season = require('../../models/Season.js');
const EntryGenre = require('../models/EntryGenre.js'); const EntryGenre = require('../../models/EntryGenre.js');
const EntrySeen = require('../models/EntrySeen.js'); const EntrySeen = require('../../models/EntrySeen.js');
const Episode = require('../models/Episode.js'); const Episode = require('../../models/Episode.js');
const Media = require('../models/Media.js'); const Media = require('../../models/Media.js');
const Genre = require('../../models/Genre.js');
const NotFoundError = require('../errors/NotFoundError.js'); const NotFoundError = require('../../errors/NotFoundError.js');
const InternalServerError = require('../errors/InternalServerError.js'); const InternalServerError = require('../../errors/InternalServerError.js');
const { fetchSeasonData, fetchEntryData } = require('./tmdbService.js'); const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js');
const { getEntryMedia } = require('./mediaService.js'); const { getEntryMedia } = require('../mediaService.js');
const Genre = require('../models/Genre.js'); const { logToFile } = require('../logService.js');
const { ValidationError, Op } = require('sequelize');
const moment = require('../../utils/moment.js');
async function saveEntry(data) { async function saveEntry(data) {
try { try {
@@ -132,11 +135,11 @@ async function saveEntry(data) {
console.log(`entry service, downloaded images: `, downloadedImages) console.log(`entry service, downloaded images: `, downloadedImages)
for (const image of downloadedImages) { for (const image of downloadedImages) {
await Media.create({ await Media.create({
entry_id: savedEntry.id, entryId: savedEntry.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
is_local: true, isLocal: true,
is_selected: true isSelected: true
}) })
} }
@@ -492,9 +495,10 @@ async function refrechEntry(entryId) {
// if (!oldEntry.casts || oldEntry.casts.length == 0 || oldEntry.casts.length < oldEntry.max_cast) { // 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 // * Media
// ? Only fetch if a Poster, Backdrop or a Logo is missing
let downloadedImages; let downloadedImages;
if (oldEntry.medias.length == 0) { if (oldEntry.medias.length < 3) {
// ? if no media is available, directly get all // ? if no media is available, directly get all
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries); downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries);
} else { } else {
@@ -524,12 +528,12 @@ async function refrechEntry(entryId) {
if (downloadedImages) { if (downloadedImages) {
for (const image of downloadedImages) { for (const image of downloadedImages) {
await Media.create({ await Media.create({
entry_id: oldEntry.id, entryId: oldEntry.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
is_local: true, isLocal: true,
is_selected: true isSelected: true
}) });
} }
} }
@@ -566,6 +570,197 @@ async function refrechEntry(entryId) {
return entryData; return entryData;
} }
/** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today
*/
async function SyncSeriesData() {
const today = moment().format('YYYY-MM-DD');
const entries = await Entry.findAll({
where: {
is_tvseries: 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 => SyncSerieData(entry.id))
);
logToFile(`Syncing Tv-Series Finished`);
return results;
}
async function 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 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;
}
async function getEntry(id) { async function getEntry(id) {
return Entry.findByPk(id); return Entry.findByPk(id);
} }
@@ -584,4 +779,6 @@ module.exports = {
refrechEntry, refrechEntry,
getEntry, getEntry,
deleteEntry, deleteEntry,
SyncSeriesData,
SyncSerieData,
} }
@@ -1,9 +1,9 @@
const Entry = require('../models/Entry.js') const Entry = require('../../models/Entry.js')
const EntryId = require('../models/EntryId.js') const EntryId = require('../../models/EntryId.js')
const EntryRating = require('../models/EntryRating.js'); const EntryRating = require('../../models/EntryRating.js');
const Season = require('../models/Season.js'); const Season = require('../../models/Season.js');
const EntryGenre = require('../models/EntryGenre.js'); const EntryGenre = require('../../models/EntryGenre.js');
const EntrySeen = require('../models/EntrySeen.js'); const EntrySeen = require('../../models/EntrySeen.js');
async function saveSeason(entryId) { async function saveSeason(entryId) {
// fetch data from tmdb // fetch data from tmdb