add media download service and started using it

This commit is contained in:
X4Lo committed 2024-05-18 15:28:42 +01:00
1 parent 78399912f7
commit 06be888123
12 files changed
+611 -77

No files matched your search

+1
View File
@@ -3,6 +3,7 @@
# Compiled output # Compiled output
/dist /dist
/dist_exe /dist_exe
/uploads
/tmp /tmp
/out-tsc /out-tsc
/bazel-out /bazel-out
+2
View File
@@ -1,9 +1,11 @@
const CustomError = require('../errors/CustomError'); const CustomError = require('../errors/CustomError');
module.exports = (err, req, res, next) => { module.exports = (err, req, res, next) => {
if (err instanceof CustomError) { if (err instanceof CustomError) {
res.status(err.statusCode()).json({ message: err.message }); res.status(err.statusCode()).json({ message: err.message });
} else { } else {
console.log(`📌 Error: `, err)
res.status(500).json({ message: 'Internal server error' }); res.status(500).json({ message: 'Internal server error' });
} }
}; };
+62 -48
View File
@@ -5,9 +5,10 @@ const EntryId = require('../models/EntryId');
const EntryRating = require('../models/EntryRating'); const EntryRating = require('../models/EntryRating');
const Genre = require('../models/Genre'); const Genre = require('../models/Genre');
const EntrySeen = require('../models/EntrySeen'); const EntrySeen = require('../models/EntrySeen');
const { saveEntry, updateEntry } = require('../services/entryService'); const { saveEntry, refrechEntry } = require('../services/entryService');
const Season = require('../models/Season'); const Season = require('../models/Season');
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService'); const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService');
const Media = require('../models/Media');
const entryRouter = express.Router(); const entryRouter = express.Router();
// ! /entries // ! /entries
@@ -19,6 +20,7 @@ entryRouter.get('/', async (req, res) => {
include: [ include: [
{ model: EntryId, as: 'entryId' }, { model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' }, { model: EntryRating, as: 'entryRating' },
{ model: Media, as: 'medias' },
{ {
model: Genre, model: Genre,
as: 'genres', as: 'genres',
@@ -54,6 +56,7 @@ entryRouter.get('/:id', async (req, res) => {
{ model: EntryRating, as: 'entryRating' }, { model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' }, { model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' }, { model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ {
model: Genre, model: Genre,
as: 'genres', as: 'genres',
@@ -155,6 +158,7 @@ entryRouter.put('/:id', async (req, res) => {
{ model: EntryId, as: 'entryId' }, { model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' }, { model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' }, { model: EntrySeen, as: 'entrySeen' },
{ model: Media, as: 'medias' },
{ {
model: Genre, model: Genre,
as: 'genres', as: 'genres',
@@ -180,63 +184,73 @@ entryRouter.put('/:id', async (req, res) => {
}); });
// * GET - REQUEST ENTRY REFRECH // * GET - REQUEST ENTRY REFRECH
entryRouter.get('/:id/refrech', async (req, res) => { entryRouter.get('/:id/refrech', async (req, res, next) => {
const { id } = req.params; const { id } = req.params;
// ? checking if the provied id is valid try {
// ! note: the includes are required for the update const entry = await refrechEntry(id);
const oldEntry = await Entry.findByPk(id, {
include: [ res.status(201).json(entry);
{ model: EntryId, as: 'entryId' }, } catch (error) {
{ model: EntryRating, as: 'entryRating' }, next(error)
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{
model: Genre,
as: 'genres',
attributes: ['id'],
through: {
attributes: []
} }
}
]
});
if (!oldEntry) // // ? checking if the provied id is valid
return res.status(404).json({ message: `Entry id not found` }); // // ! note: the includes are required for the update
// const oldEntry = 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: Genre,
// as: 'genres',
// attributes: ['id'],
// through: {
// attributes: []
// }
// }
// ]
// });
// ? getting new data from TMDB // if (!oldEntry)
const data = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); // return res.status(404).json({ message: `Entry id not found` });
if (data == null) return res.status(500).json({ message: `Counldn't fetch data from TMDB` });
// ? updating // // ? getting new data from TMDB
await updateEntry(oldEntry, data); // const data = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
// if (data == null) return res.status(500).json({ message: `Counldn't fetch data from TMDB` });
// ? returning a new entry with updated values // // ? updating
let includes = [ // await updateEntry(oldEntry, data);
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{
model: Genre,
as: 'genres',
attributes: ['name'],
through: {
attributes: []
}
}
];
if (oldEntry.is_tvseries) includes.push({ model: Season, as: 'seasons' });
const updatedEntry = await Entry.findByPk(id, { // // ? returning a new entry with updated values
include: includes // 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 entryData = updatedEntry.get({ plain: true }); // const updatedEntry = await Entry.findByPk(id, {
entryData.genres = entryData.genres.map(genre => genre.name); // include: includes
// });
res.status(201).json(entryData); // const entryData = updatedEntry.get({ plain: true });
// entryData.genres = entryData.genres.map(genre => genre.name);
// res.status(201).json(entryData);
}); });
// * DELETE - ENTRY BY ID // * DELETE - ENTRY BY ID
+3 -1
View File
@@ -6,6 +6,7 @@ const EntryId = require('../models/EntryId');
const EntryRating = require('../models/EntryRating'); const EntryRating = require('../models/EntryRating');
const Season = require('../models/Season'); const Season = require('../models/Season');
const Genre = require('../models/Genre'); const Genre = require('../models/Genre');
const Media = require('../models/Media');
const { Sequelize } = require('sequelize'); const { Sequelize } = require('sequelize');
const router = express.Router(); const router = express.Router();
@@ -51,6 +52,7 @@ router.get('/:id', async (req, res) => {
{ model: EntryId, as: 'entryId' }, { model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' }, { model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' }, { model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' }, { model: Genre, as: 'genres' },
], ],
through: { through: {
@@ -203,7 +205,7 @@ router.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
} }
// ? updating // ? updating
const updated = await collectionEntry.update({ order: newOrder }); await collectionEntry.update({ order: newOrder });
res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' }); res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' });
} catch (error) { } catch (error) {
+2 -1
View File
@@ -36,7 +36,7 @@ app.use('/api/v1/media/:category/:type', (req, res, next) => {
return res.status(404).send('Not Found'); return res.status(404).send('Not Found');
} }
if (!['banners', 'posters', 'others'].includes(type)) { if (!['backdrops', 'posters', 'others'].includes(type)) {
return res.status(404).send('Not Found'); return res.status(404).send('Not Found');
} }
@@ -51,6 +51,7 @@ app.use('/api/v1/media/:category/:type', (req, res, next) => {
app.use('/api/v1', routes); app.use('/api/v1', routes);
// ! Error handling middleware // ! Error handling middleware
const errorHandler = require('./middleware/errorHandler');
app.use(errorHandler); app.use(errorHandler);
// Start the server // Start the server
+248 -9
View File
@@ -4,8 +4,15 @@ 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 { fetchSeasonData } = require('./tmdbService.js');
const Episode = require('../models/Episode.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) { async function saveEntry(data) {
try { try {
@@ -18,6 +25,7 @@ async function saveEntry(data) {
title: data.title || data.name, title: data.title || data.name,
original_title: data.original_title || data.original_name, original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date, release_date: data.release_date || data.first_air_date,
release_status: data.status,
runtime: data.runtime || null, runtime: data.runtime || null,
tagline: data.tagline || null, tagline: data.tagline || null,
@@ -32,11 +40,20 @@ async function saveEntry(data) {
poster_path: data.poster_path, poster_path: data.poster_path,
banner_path: data.backdrop_path, banner_path: data.backdrop_path,
last_fetch: new Date()
}); });
const savedEntry = await movie.save(); const savedEntry = await movie.save();
// genres // ? 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) => { data.genres.forEach(async (genre) => {
await EntryGenre.create({ await EntryGenre.create({
genre_id: genre.id, genre_id: genre.id,
@@ -44,19 +61,16 @@ async function saveEntry(data) {
}) })
}); });
// ? ratings
const ratings = await EntryRating.create({ const ratings = await EntryRating.create({
entry_id: savedEntry.id, entry_id: savedEntry.id,
user_rating: 0, user_rating: 0,
tmdb_rating: data.vote_average, tmdb_rating: data.vote_average,
}); });
const ids = await EntryId.create({ // ! seasons & episodes for tv series
entry_id: savedEntry.id,
tmdb_id: data.id,
imdb_id: data.imdb_id,
});
if (is_tvseries) { if (is_tvseries) {
// * seasons
let seasons = []; let seasons = [];
for (const season of data.seasons) { for (const season of data.seasons) {
let seasonData = await fetchSeasonData(data.id, season.season_number); let seasonData = await fetchSeasonData(data.id, season.season_number);
@@ -78,7 +92,7 @@ async function saveEntry(data) {
banner_path: null, banner_path: null,
}) })
// save episodes // * episodes
let episodes = []; let episodes = [];
for (const episode of seasonData.episodes) { for (const episode of seasonData.episodes) {
const savedEpisode = await Episode.create({ const savedEpisode = await Episode.create({
@@ -108,6 +122,22 @@ async function saveEntry(data) {
} }
savedEntry.setDataValue('seasons', seasons); 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); const currentGenresNames = await data.genres.map(genre => genre.name);
@@ -286,6 +316,214 @@ async function updateEntry(oldEntry, data) {
return savedEntry; 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) {
// }
// * Media
// * Only fetch if a Poster, Backdrop or a Logo is missing
// + 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
});
const entryData = updatedEntry.get({ plain: true });
entryData.genres = entryData.genres.map(genre => genre.name);
return entryData;
}
async function getEntry(id) { async function getEntry(id) {
return Entry.findByPk(id); return Entry.findByPk(id);
} }
@@ -301,6 +539,7 @@ async function deleteEntry(id) {
module.exports = { module.exports = {
saveEntry, saveEntry,
updateEntry, updateEntry,
refrechEntry,
getEntry, getEntry,
deleteEntry, deleteEntry,
} }
+159
View File
@@ -0,0 +1,159 @@
const express = require('express');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const { fetchEntryMedia } = require('./tmdbService');
async function downloadImage(url, filePath) {
const response = await axios({
url: url,
method: 'GET',
responseType: 'stream'
});
const writer = fs.createWriteStream(filePath);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
async function getEntryMedia(tmdb_id, is_tvserie) {
console.log(`hello`);
let mediaData = await fetchEntryMedia(tmdb_id, is_tvserie);
if (mediaData == null) return null;
let downloadedImages = [];
// Ensuring directories exist
const posterDir = path.join(__dirname, '../../', 'uploads', 'entries', 'posters');
const backdropDir = path.join(__dirname, '../../', 'uploads', 'entries', 'backdrops');
const logoDir = path.join(__dirname, '../../', 'uploads', 'entries', 'logos');
fs.mkdirSync(posterDir, { recursive: true });
fs.mkdirSync(backdropDir, { recursive: true });
fs.mkdirSync(logoDir, { recursive: true });
const downloadTasks = [];
// * downloading poster original + w300 (for cards)
if (mediaData.posters && mediaData.posters.length) {
let selectedMedia = null;
for (let media of mediaData.posters) {
if (media.iso_639_1 == 'en') {
selectedMedia = media;
break;
}
}
if (selectedMedia == null) selectedMedia = mediaData.posters[0]
const uniqueFilename = uuidv4();
const extension = selectedMedia.file_path.split('.').pop();
let originalPosterUrl = `https://image.tmdb.org/t/p/original${selectedMedia.file_path}`;
let originalPosterFileName = `${uniqueFilename}.${extension}`;
let originalPosterFilePath = path.join(posterDir, originalPosterFileName);
downloadTasks.push(
downloadImage(originalPosterUrl, originalPosterFilePath)
.then(() => downloadedImages.push({ type: 'poster', path: `${originalPosterFileName}` }))
.catch(err => console.error('Error downloading poster:', err))
);
let cardPosterUrl = `https://image.tmdb.org/t/p/w300${selectedMedia.file_path}`;
let cardPosterFileName = `${uniqueFilename}_preview.${extension}`;
let cardPosterFilePath = path.join(posterDir, cardPosterFileName);
downloadTasks.push(
downloadImage(cardPosterUrl, cardPosterFilePath)
.then(() => { })
.catch(err => console.error('Error downloading preview poster:', err))
);
}
if (mediaData.logos && mediaData.logos.length) {
let selectedMedia = null;
for (let media of mediaData.logos) {
if (media.iso_639_1 == 'en') {
selectedMedia = media;
break;
}
}
if (selectedMedia == null) selectedMedia = mediaData.logos[0]
const uniqueFilename = uuidv4();
const extension = selectedMedia.file_path.split('.').pop();
let originalLogoUrl = `https://image.tmdb.org/t/p/original${selectedMedia.file_path}`;
let originalLogoFileName = `${uniqueFilename}.${extension}`;
let originalLogoFilePath = path.join(logoDir, originalLogoFileName);
downloadTasks.push(
downloadImage(originalLogoUrl, originalLogoFilePath)
.then(() => downloadedImages.push({ type: 'logo', path: `${originalLogoFileName}` }))
.catch(err => console.error('Error downloading logo:', err))
);
let cardLogoUrl = `https://image.tmdb.org/t/p/w300${selectedMedia.file_path}`;
let cardLogoFileName = `${uniqueFilename}_preview.${extension}`;
let cardLogoFilePath = path.join(logoDir, cardLogoFileName);
downloadTasks.push(
downloadImage(cardLogoUrl, cardLogoFilePath)
.then(() => { })
.catch(err => console.error('Error downloading preview logo:', err))
);
}
if (mediaData.backdrops && mediaData.backdrops.length) {
let selectedMedia = null;
for (let media of mediaData.backdrops) {
if (media.iso_639_1 == 'en') {
selectedMedia = media;
break;
}
}
if (selectedMedia == null) selectedMedia = mediaData.backdrops[0]
const uniqueFilename = uuidv4();
const extension = selectedMedia.file_path.split('.').pop();
let originalBackdropUrl = `https://image.tmdb.org/t/p/original${selectedMedia.file_path}`;
let originalBackdropFileName = `${uniqueFilename}.${extension}`;
let originalBackdropFilePath = path.join(backdropDir, originalBackdropFileName);
downloadTasks.push(
downloadImage(originalBackdropUrl, originalBackdropFilePath)
.then(() => downloadedImages.push({ type: 'backdrop', path: `${originalBackdropFileName}` }))
.catch(err => console.error('Error downloading backdrop:', err))
);
let cardBackdropUrl = `https://image.tmdb.org/t/p/w300${selectedMedia.file_path}`;
let cardBackdropFileName = `${uniqueFilename}_preview.${extension}`;
let cardBackdropFilePath = path.join(backdropDir, cardBackdropFileName);
downloadTasks.push(
downloadImage(cardBackdropUrl, cardBackdropFilePath)
.then(() => { })
.catch(err => console.error('Error downloading preview backdrop:', err))
);
}
// Wait for all downloads to complete
await Promise.all(downloadTasks).then(downloadedImages => {
// console.log('Downloaded images:', downloadedImages);
}).catch(err => {
console.error('Error downloading entry images: mediaService>promise all:', err);
});
return downloadedImages;
}
module.exports = {
getEntryMedia,
};
+19
View File
@@ -39,9 +39,28 @@ async function fetchSeasonData(tmdbTvId, seasonNumber) {
} }
} }
async function fetchEntryMedia(tmdb_id, is_tvserie) {
try {
let type = is_tvserie ? "tv" : "movie";
let url = `http://api.themoviedb.org/3/${type}/${tmdb_id}/images?api_key=${tmdb_apiKey}`
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) return console.log('Error fetching entry media.');
data = response.data;
})
return data;
} catch (error) {
console.log('Error fetching the entry media.', error)
return null;
}
}
module.exports = { module.exports = {
fetchEntryData, fetchEntryData,
fetchSeasonData, fetchSeasonData,
fetchEntryMedia,
} }
@@ -1,6 +1,6 @@
<div class="movie-card" @fadeInOut> <div class="movie-card" @fadeInOut>
<div class="card-head"> <div class="card-head">
<img class="card-img" [src]="getPostPath()" alt="Movie Poster"> <img class="card-img" [src]="posterPath" alt="Movie Poster">
<div class="card-overlay"> <div class="card-overlay">
<div class="rating"> <div class="rating">
@@ -1,6 +1,5 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { LibraryService } from '../../../../core/services/library.service';
import { Entry } from '../../../../shared/models/entry.model'; import { Entry } from '../../../../shared/models/entry.model';
import { trigger, transition, style, animate } from '@angular/animations'; import { trigger, transition, style, animate } from '@angular/animations';
import { UserCollectionService } from '../../../../core/services/userCollection.service'; import { UserCollectionService } from '../../../../core/services/userCollection.service';
@@ -27,14 +26,12 @@ export class UserCollectionGridCardComponent implements OnInit {
@Output() refrechEvent = new EventEmitter(); @Output() refrechEvent = new EventEmitter();
constructor( constructor(
private libraryService: LibraryService,
private userCollectionService: UserCollectionService, private userCollectionService: UserCollectionService,
public dialog: MatDialog, public dialog: MatDialog,
private router: Router private router: Router
) {} ) {}
ngOnInit(): void { ngOnInit(): void {}
}
get releaseYear(): number { get releaseYear(): number {
return new Date(this.entry.release_date).getFullYear(); return new Date(this.entry.release_date).getFullYear();
@@ -49,12 +46,35 @@ export class UserCollectionGridCardComponent implements OnInit {
return `https://www.themoviedb.org/${type}/${this.entry.entryId.tmdb_id}`; return `https://www.themoviedb.org/${type}/${this.entry.entryId.tmdb_id}`;
} }
getPostPath() { get posterPath() {
if (this.entry.poster_path == null) return 'https://pic.pnnet.dev/256x256'; // * Not in library, use TMDB poster
if (!this.entry.isInLibrary)
return `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
return `https://image.tmdb.org/t/p/w500` + this.entry.poster_path; // * Is in library: use a local poster
if (this.entry.medias) {
const selectedPosters = this.entry.medias.filter(
(m) => m.type == 'poster' && m.is_selected
);
if (
selectedPosters.length &&
selectedPosters[0] &&
selectedPosters[0].path
) {
const name = selectedPosters[0].path.split('.')[0];
const extention = selectedPosters[0].path.split('.')[1];
return `http://localhost:4000/api/v1/media/entries/posters/${name}_preview.${extention}`;
}
} }
// * No local poster available, Use TMDB poster
if (this.entry.poster_path)
return `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
// * No poster found, use default poster image as a last stand
return 'assets/images/default/default-poster.png';
}
removeEntryFromList() { removeEntryFromList() {
const dialogRef = this.dialog.open(ConfirmModalComponent, { const dialogRef = this.dialog.open(ConfirmModalComponent, {
@@ -78,7 +78,7 @@
<div class="col-md-8 right-col"> <div class="col-md-8 right-col">
<!-- Movie Title --> <!-- Movie Title -->
<div class="d-flex justify-content-between align-items-center "> <div class="d-flex justify-content-between align-items-center ">
<h2 class="title">{{this.entry.title}}</h2> <h2 class="title" (click)="redirectToTmdb()">{{this.entry.title}}</h2>
<!-- Interraction buttons --> <!-- Interraction buttons -->
<div class="row entry-actions"> <div class="row entry-actions">
@@ -70,7 +70,7 @@ export class EntryPageComponent implements OnInit {
this.route.data.subscribe( this.route.data.subscribe(
(data) => { (data) => {
this.entry = data['entry'] as Entry; this.entry = data['entry'] as Entry;
// console.log(this.entry); this.entry.isInLibrary = true;
if (this.entry.is_tvseries) { if (this.entry.is_tvseries) {
// ? sorting seasons // ? sorting seasons
@@ -98,6 +98,7 @@ export class EntryPageComponent implements OnInit {
{ {
tapToDismiss: true, tapToDismiss: true,
progressBar: true, progressBar: true,
positionClass: 'bottom-right',
progressAnimation: 'increasing', progressAnimation: 'increasing',
} }
); );
@@ -205,6 +206,7 @@ export class EntryPageComponent implements OnInit {
this.toastr.success('success', `Removed successfuly.`, { this.toastr.success('success', `Removed successfuly.`, {
tapToDismiss: true, tapToDismiss: true,
progressBar: true, progressBar: true,
positionClass: 'bottom-right',
progressAnimation: 'increasing', progressAnimation: 'increasing',
}); });
this.entry.entrySeen = this.entry.entrySeen.filter( this.entry.entrySeen = this.entry.entrySeen.filter(
@@ -279,7 +281,12 @@ export class EntryPageComponent implements OnInit {
next: (entry) => { next: (entry) => {
this.entry = entry; this.entry = entry;
// console.log(`Entry refreched: `, entry); // console.log(`Entry refreched: `, entry);
// TODO show updated notification this.toastr.success(`Movie refreshed successfuly.`, 'Success', {
tapToDismiss: true,
progressBar: true,
positionClass: 'bottom-right',
progressAnimation: 'increasing',
});
}, },
error: (error) => { error: (error) => {
// TODO show error notification // TODO show error notification
@@ -484,13 +491,45 @@ export class EntryPageComponent implements OnInit {
this.showAll = !this.showAll; this.showAll = !this.showAll;
} }
enlargePoster() { redirectToTmdb() {
let type = this.entry.is_tvseries ? 'tv' : 'movie';
window.open( window.open(
'https://image.tmdb.org/t/p/original' + this.entry.poster_path, `https://www.themoviedb.org/${type}/${this.entry.entryId.tmdb_id}`,
'_blank' '_blank'
); );
} }
enlargePoster() {
let poster;
// * Not in library, use TMDB poster
if (!this.entry.isInLibrary)
poster = `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
// * Is in library: use a local poster
if (!poster && this.entry.medias) {
const selectedPosters = this.entry.medias.filter(
(m) => m.type == 'poster' && m.is_selected
);
if (
selectedPosters.length &&
selectedPosters[0] &&
selectedPosters[0].path
) {
poster = `http://localhost:4000/api/v1/media/entries/posters/${selectedPosters[0].path}`;
}
}
// * No local poster available, Use TMDB poster
if (!poster && this.entry.poster_path)
poster = `https://image.tmdb.org/t/p/original` + this.entry.poster_path;
// * No poster found, use default poster image as a last stand
if (!poster) poster = 'assets/images/default/default-poster.png';
window.open(poster, '_blank');
}
// * getters // * getters
get status() { get status() {
return this.entry.status; return this.entry.status;
@@ -505,17 +544,55 @@ export class EntryPageComponent implements OnInit {
} }
get poster(): string { get poster(): string {
if (this.entry.poster_path == null) // * Not in library, use TMDB poster
return 'assets/images/default/default-poster.png'; if (!this.entry.isInLibrary)
return `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
return `https://image.tmdb.org/t/p/w500` + this.entry.poster_path; // * Is in library: use a local poster
if (this.entry.medias) {
const selectedPosters = this.entry.medias.filter(
(m) => m.type == 'poster' && m.is_selected
);
if (
selectedPosters.length &&
selectedPosters[0] &&
selectedPosters[0].path
) {
return `http://localhost:4000/api/v1/media/entries/posters/${selectedPosters[0].path}`;
}
}
// * No local poster available, Use TMDB poster
if (this.entry.poster_path)
return `https://image.tmdb.org/t/p/w300` + this.entry.poster_path;
// * No poster found, use default poster image as a last stand
return 'assets/images/default/default-poster.png';
} }
get banner(): string { get banner(): string {
if (this.entry.banner_path == null) // * Is in library: use a local backdrop
return 'assets/images/default/default-poster.png'; if (this.entry.medias) {
const selectedBackdrop = this.entry.medias.filter(
(m) => m.type == 'backdrop' && m.is_selected
);
if (
selectedBackdrop.length &&
selectedBackdrop[0] &&
selectedBackdrop[0].path
) {
return `http://localhost:4000/api/v1/media/entries/backdrops/${selectedBackdrop[0].path}`;
}
}
// * No local backdrop available, Use TMDB backdrop
if (this.entry.banner_path)
return `https://image.tmdb.org/t/p/w1280` + this.entry.banner_path; return `https://image.tmdb.org/t/p/w1280` + this.entry.banner_path;
// * No backdrop found, use default backdrop image as a last stand
return 'assets/images/default/default-poster.png';
} }
get nextEpisode() { get nextEpisode() {