453 lines
13 KiB
JavaScript
453 lines
13 KiB
JavaScript
const Collection = require("../models/Collection");
|
|
const Entry = require("../models/Entry");
|
|
const EntryId = require("../models/EntryId");
|
|
const EntryRating = require("../models/EntryRating");
|
|
const EntrySeen = require("../models/EntrySeen");
|
|
const EntryGenre = require("../models/EntryGenre.js");
|
|
const Genre = require("../models/Genre");
|
|
const Media = require("../models/Media");
|
|
const Season = require("../models/Season");
|
|
const Episode = require("../models/Episode");
|
|
|
|
const BadRequestError = require("../errors/BadRequestError");
|
|
const NotFoundError = require("../errors/NotFoundError");
|
|
|
|
const mediaOptimizerService = require("./mediaOptimizerService.js");
|
|
const mediaManager = require("./mediaManager.js");
|
|
const { fetchSeasonData, fetchEntryCredits } = require("./tmdbService.js");
|
|
const Network = require("../models/Network.js");
|
|
const networkService = require("./networkService.js");
|
|
const Cast = require("../models/Credit.js");
|
|
const People = require("../models/People.js");
|
|
const Credit = require("../models/Credit.js");
|
|
|
|
const _mediaManager = mediaManager;
|
|
const _mediaOptimizerService = mediaOptimizerService;
|
|
const _networkService = networkService;
|
|
|
|
class EntryService {
|
|
|
|
constructor() {
|
|
if (!EntryService.instance) {
|
|
EntryService.instance = this;
|
|
}
|
|
return EntryService.instance;
|
|
}
|
|
|
|
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: Genre,
|
|
as: 'genres',
|
|
attributes: ['name'], // Only fetch the genre name
|
|
through: {
|
|
attributes: [] // Do not fetch any attributes from the join table
|
|
}
|
|
}
|
|
]
|
|
});
|
|
|
|
// converting genres from object list to string list
|
|
const entriesWithGenreNames = entries.map(entry => ({
|
|
...entry.get({ plain: true }),
|
|
genres: entry.genres.map(genre => genre.name) // Convert genre objects to string array
|
|
}));
|
|
|
|
return entriesWithGenreNames;
|
|
}
|
|
|
|
async getEntryById(id, plain = true) {
|
|
if (!id) {
|
|
throw new BadRequestError("Entry id not provided");
|
|
}
|
|
|
|
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: Cast, as: 'credits',
|
|
include: [
|
|
{ model: People, as: 'person' }
|
|
]
|
|
},
|
|
{
|
|
model: Collection, as: 'collections',
|
|
include: [
|
|
{ model: Media, as: 'medias' }
|
|
]
|
|
},
|
|
{
|
|
model: Genre,
|
|
as: 'genres',
|
|
attributes: ['name', 'id'],
|
|
through: {
|
|
attributes: [] // Do not fetch any attributes from the join table
|
|
}
|
|
}
|
|
],
|
|
order: [
|
|
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
|
|
]
|
|
});
|
|
|
|
if (!entry) {
|
|
throw new NotFoundError("Entry with the provided id was not found")
|
|
}
|
|
|
|
if (plain) {
|
|
const plainEntry = entry.get({ plain: true });
|
|
const genres = plainEntry.genres.map(genre => genre.name);
|
|
|
|
plainEntry.genres = genres;
|
|
|
|
return plainEntry;
|
|
} else {
|
|
return entry;
|
|
}
|
|
}
|
|
|
|
async createEntry(data, plain = true) {
|
|
// 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()
|
|
});
|
|
|
|
let savedEntry = await movie.save();
|
|
|
|
// ? 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
|
|
})
|
|
});
|
|
|
|
// ? networks
|
|
if (data.networks) {
|
|
for (const networkData of data.networks) {
|
|
// 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 savedEntry.addNetwork(network);
|
|
}
|
|
}
|
|
|
|
// ? 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,
|
|
})
|
|
|
|
_mediaManager.getSeasonMedia(savedSeason);
|
|
|
|
// * 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);
|
|
_mediaManager.getEpisodenMedia(savedEpisode);
|
|
}
|
|
|
|
// TODO fetch cast
|
|
|
|
savedSeason.setDataValue('episodes', episodes);
|
|
seasons.push(savedSeason)
|
|
}
|
|
savedEntry.setDataValue('seasons', seasons);
|
|
}
|
|
// + end of: seasons & episodes for tv series
|
|
|
|
// ? Credits
|
|
const creditData = await fetchEntryCredits(data.id, is_tvseries);
|
|
if (!creditData) {
|
|
throw new InternalServerError(`Couldn't fetch entry credits 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))];
|
|
|
|
const existingPeopleList = await People.findAll({
|
|
where: { tmdb_id: tmdbIds },
|
|
});
|
|
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);
|
|
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()
|
|
};
|
|
});
|
|
|
|
const createdPeople = await People.bulkCreate(newPeopleData);
|
|
for (const person of createdPeople) {
|
|
existingPeopleMap[person.tmdb_id] = person;
|
|
}
|
|
|
|
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,
|
|
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,
|
|
};
|
|
});
|
|
|
|
await Credit.bulkCreate(newCredits);
|
|
|
|
savedEntry.credit_fetched = true;
|
|
await savedEntry.save();
|
|
|
|
// ? media
|
|
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',
|
|
mediaableId: savedEntry.id,
|
|
type: image.type,
|
|
path: image.path,
|
|
isLocal: true,
|
|
isSelected: true
|
|
});
|
|
|
|
_mediaOptimizerService.doGeneratePreview('entries', image.type + 's', image.path);
|
|
}
|
|
|
|
// const currentGenresNames = await data.genres.map(genre => genre.name);
|
|
|
|
// savedEntry.setDataValue('entryId', ids);
|
|
// savedEntry.setDataValue('entryRating', ratings);
|
|
// savedEntry.setDataValue('genres', currentGenresNames);
|
|
|
|
savedEntry = await this.getEntryById(savedEntry.id, plain);
|
|
|
|
return savedEntry;
|
|
}
|
|
|
|
async updateEntryById(id, entryData, plain = true) {
|
|
if (!id) {
|
|
throw new BadRequestError("Entry id not provided");
|
|
}
|
|
|
|
// ? checking if the provied id is valid
|
|
const oldEntry = await Entry.findByPk(id);
|
|
|
|
if (!oldEntry) {
|
|
throw new NotFoundError("Entry with the provided id was not found")
|
|
}
|
|
|
|
await oldEntry.update(entryData);
|
|
|
|
const updatedEntry = await this.getEntryById(id, plain);
|
|
|
|
return updatedEntry;
|
|
}
|
|
|
|
async updateEntryRatings(id, entryRatingsData) {
|
|
if (!id) {
|
|
throw new BadRequestError("Entry id not provided");
|
|
}
|
|
|
|
let entry = await Entry.findByPk(id, {
|
|
include: [
|
|
{ model: EntryRating, as: 'entryRating' },
|
|
]
|
|
});
|
|
|
|
if (!entry) {
|
|
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;
|
|
|
|
return await entry.entryRating.save();
|
|
}
|
|
|
|
async updateEntryIds(id, entryIdsData) {
|
|
if (!id) {
|
|
throw new BadRequestError("Entry id not provided");
|
|
}
|
|
|
|
let entry = await Entry.findByPk(id, {
|
|
include: [
|
|
{ model: EntryId, as: 'entryId' },
|
|
]
|
|
});
|
|
|
|
if (!entry) {
|
|
throw new NotFoundError("Entry with the provided id was not found")
|
|
}
|
|
|
|
if (entry.entryRating.id != entryRatingsData.id) {
|
|
throw new BadRequestError("EntryIds id does not match");
|
|
}
|
|
|
|
entry.entryId.tmdb_id = entryIdsData.tmdb_id ?? entry.entryId.tmdb_id;
|
|
entry.entryId.imdb_id = entryIdsData.imdb_id ?? entry.entryId.imdb_id;
|
|
entry.entryId.tvdb_id = entryIdsData.tvdb_id ?? entry.entryId.tvdb_id;
|
|
|
|
await entry.entryId.save();
|
|
}
|
|
|
|
async deleteEntryById(id) {
|
|
if (!id) {
|
|
throw new BadRequestError("Entry id not provided");
|
|
}
|
|
|
|
const deletedCount = await Entry.destroy({
|
|
where: { id: id }
|
|
});
|
|
|
|
if (deletedCount == 0) {
|
|
throw new NotFoundError("Entry with the provided id was not found")
|
|
}
|
|
|
|
return deletedCount;
|
|
}
|
|
|
|
async getEntrySeasons(id) {
|
|
if (!id) {
|
|
throw new BadRequestError("Entry id not provided");
|
|
}
|
|
|
|
const entry = await Entry.findByPk(id);
|
|
if (!entry) {
|
|
throw new NotFoundError("Entry with the provided id was not found")
|
|
}
|
|
|
|
const seasons = await Season.findAll({
|
|
where: {
|
|
entry_id: id
|
|
},
|
|
include: [
|
|
{
|
|
model: Episode, as: 'episodes', include: [
|
|
{ model: Media, as: 'medias' }
|
|
]
|
|
},
|
|
{ model: Media, as: 'medias' }
|
|
],
|
|
order: [
|
|
['season_number', 'ASC'],
|
|
[{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'],
|
|
]
|
|
})
|
|
|
|
return seasons;
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = new EntryService(); |