Files
Showy/backend/routes/entry.routes.js
T

466 lines
13 KiB
JavaScript

const express = require('express');
const entryRouter = express.Router();
const path = require('path');
const { fetchEntryData, fetchCollectionData } = require('../services/tmdbService');
const { saveEntry, refrechEntry, SyncSeriesData } = require('../services/models-services/entryService');
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService');
const { entryPicturesUpload } = require('../services/mutlerStorageLocations');
const { generatePreview, doGeneratePreview } = require('../services/mediaService');
const { Sequelize } = require('sequelize');
const Entry = require('../models/Entry');
const EntryId = require('../models/EntryId');
const EntryRating = require('../models/EntryRating');
const Genre = require('../models/Genre');
const EntrySeen = require('../models/EntrySeen');
const Season = require('../models/Season');
const Media = require('../models/Media');
const Episode = require('../models/Episode');
const UserCollection = require('../models/Collection');
const { upsertOfficialCollection } = require('../services/models-services/collectionService');
const { logToFile } = require('../services/logService');
// ! /entries
// * GET - ALL ENTRIES
entryRouter.get('/', async (req, res) => {
const { page, pageSize } = req.body;
const entries = await Entry.findAll({
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Media, as: 'medias' },
{ model: Season, as: 'seasons' },
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre ID
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
}));
res.status(200).json(entriesWithGenreNames);
});
// * GET - SYNC ALL ENTIRES DATA
entryRouter.get('/sync-series', async (req, res, next) => {
try {
const entries = await SyncSeriesData();
res.status(201).json(entries);
} catch (error) {
next(error)
}
});
// * GET ENTRY BY ID
entryRouter.get('/:id', async (req, res) => {
try {
const { id } = req.params;
if (id == null) { // ! entry id not provided
res.status(404).json({ message: '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: UserCollection, as: 'collections',
include: [
{ model: Media, as: 'medias' }
]
},
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre 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) { // ! entry not found
res.status(404).json({ message: 'Entry not found' });
}
const entryData = entry.get({ plain: true });
const genres = entryData.genres.map(genre => genre.name);
entryData.genres = genres;
res.status(200).json(entryData);
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error);
}
});
// * GET - Get seasons of an entry
entryRouter.get('/:id/seasons', async (req, res) => {
try {
const { id } = req.params;
if (id == null) { // ! entry id not provided
res.status(404).json({ message: 'Entry id not provided' });
}
const entry = await Entry.findByPk(id);
if (!entry) {
res.status(404).json({ message: 'Entry not found' });
}
const seasons = await Season.findAll({
where: {
entry_id: id
},
attributes: ['id', 'season_number'],
include: [
{ model: Episode, as: 'episodes', attributes: ['id', 'episode_number'], }
],
order: [
['season_number', 'ASC'],
[{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'],
]
})
if (seasons.length == 0) { // ! no content
res.status(404).json({ message: 'No seasons' });
}
res.status(200).json(seasons);
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error);
}
});
// * POST - CREATE ENTRY
entryRouter.post('/', async (req, res) => {
const { tmdb_id, is_tvserie } = req.body;
const entryData = await fetchEntryData(tmdb_id, is_tvserie);
const entry = await saveEntry(entryData);
if (entryData.belongs_to_collection) {
upsertOfficialCollection(entryData.belongs_to_collection.id);
}
res.status(201).json(entry);
});
// ! import routes
entryRouter.post('/bulk-import-movies', async (req, res) => {
const { movies } = req.body;
let entries = [];
try {
entries = await bulkImportMovies(movies);
} catch (error) {
res.status(500);
}
res.status(201).json(entries);
});
entryRouter.post('/bulk-import-tmdb', async (req, res) => {
const { values } = req.body;
let entries = [];
try {
entries = await bulkImportTmdb(values);
} catch (error) {
res.status(500);
}
res.status(201).json(entries);
});
entryRouter.post('/bulk-import-episodes-seen', async (req, res) => {
const { values } = req.body;
let createdRows = 0;
try {
createdRows = await bulkImportEpisodes(values);
console.log(`Episodes Seen - counts ${episodes.length}`)
} catch (error) {
res.status(500);
}
res.status(201).json(createdRows);
});
// + import routes end
// * PUT - ENTRY UPDATE
entryRouter.put('/:id', async (req, res) => {
const { id } = req.params;
const { favorit, hidden, watchlist } = req.body;
// ? checking if the provied id is valid
const oldEntry = await Entry.findByPk(id);
if (!oldEntry)
return res.status(404).json({ message: `Entry with the provided id was not found` });
// ? updating
await oldEntry.update({
favorit: favorit,
watchlist: watchlist,
hidden: hidden
});
// ? returning a new entry with updated values
let includes = [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ 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(id, {
include: includes,
order: [
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
]
});
const entryData = updatedEntry.get({ plain: true });
const genres = entryData.genres.map(genre => genre.name);
entryData.genres = genres;
res.status(201).json(entryData);
});
// * GET - REQUEST ENTRY REFRECH
entryRouter.get('/:id/refresh', async (req, res, next) => {
const { id } = req.params;
try {
const entry = await refrechEntry(id);
res.status(201).json(entry);
} catch (error) {
next(error)
}
});
// * GET - REQUEST ENTRY REFRECH
entryRouter.get('/:id/fetch-collection', async (req, res, next) => {
const { id } = req.params;
try {
const oldEntry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' }
]
})
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (entryData.belongs_to_collection) {
let collectionData = entryData.belongs_to_collection;
const [oldCollection, createdCollection] = await UserCollection.findOrCreate({
where: { tmdbId: collectionData.id },
defaults: {
name: collectionData.name,
posterPath: collectionData.poster_path,
backdropPath: collectionData.backdrop_path,
}
});
let userCollection = oldCollection || createdCollection;
if (userCollection) {
collectionData = await fetchCollectionData(collectionData.id);
const partIds = collectionData.parts.map(part => part.id);
const entries = await Entry.findAll({
include: [{
model: EntryId,
as: 'entryId',
where: {
tmdb_id: {
[Sequelize.Op.in]: partIds
}
}
}]
});
await userCollection.setEntries(entries);
await userCollection.update({ description: collectionData.overview })
}
res.status(201).json(userCollection);
}
} catch (error) {
next(error)
}
});
// ! ENTRY MEDIA
// * POST - ADD NEW ENTRY MEDIA (poster/backdrop/logo)
const upload = entryPicturesUpload.fields([
{ name: 'poster', maxCount: 1 },
{ name: 'backdrop', maxCount: 1 },
{ name: 'logo', maxCount: 1 }
]);
entryRouter.post('/:id/media', upload, async (req, res) => {
const { id } = req.params;
if (!req.files) {
return res.status(400).json({ message: 'No files uploaded' });
}
const entry = await Entry.findByPk(id);
if (!entry) {
return res.status(404).json({ message: 'Entry not found' });
}
// Function to handle media creation based on uploaded file type
const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]);
if (fileType) {
const file = req.files[fileType][0];
const createdMedia = await Media.create({
mediaable: 'entry',
mediaableId: id,
type: fileType,
path: file.filename,
isLocal: true,
isSelected: false,
isCustom: true
});
// ? generating low resolution preview
// const fileNameWithoutExt = file.filename.split('.')[0];
// const originalPath = file.path;
// let previewWidth = 342; // ? poster preview width
// if (fileType == 'backdrop') previewWidth = 780;
// if (fileType == 'logo') previewWidth = 300;
// const previewPath = path.join(file.destination, `${fileNameWithoutExt}_preview.jpg`);
// generatePreview(originalPath, previewPath, previewWidth);
doGeneratePreview('entries', fileType + 's', file.filename).then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
const msg = `Media Route | Generated Entry Preview`
logToFile(msg);
}).catch((err) => {
const msg = `Media Route | Error Generating Entry Preview`
logToFile(msg);
});
return res.status(200).json(createdMedia);
}
return res.status(400).json({ message: 'Invalid media type' });
});
// * PUT - SET ENTRY MEDIA AS SELECTED
entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => {
const entryId = req.params.entryId;
const mediaId = req.params.mediaId;
const entry = await Entry.findByPk(entryId);
if (!entry) {
return res.status(404).json({ message: 'Entry not found' });
}
const media = await Media.findByPk(mediaId);
if (!media) {
return res.status(404).json({ message: 'Media not found' });
}
await Media.update(
{ isSelected: false },
{
where: {
mediaableId: entryId,
type: media.type
}
}
);
const updatedMedia = await media.update({ isSelected: true });
return res.status(200).json(updatedMedia);
});
// * DELETE - DELETE AND ENTRY MEDIA
entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => {
const mediaId = req.params.mediaId;
// ? just before deleting we need to check if the deleted media was the one selected
// ? if so select a new one if there is, then delete
const media = await Media.findByPk(mediaId);
if (media && media.isSelected) {
let otherMedia = await Media.findOne({
where: {
entryId: media.entryId,
type: media.type,
isSelected: false
}
});
// ? if found select the first one
if (otherMedia) {
otherMedia.update({ isSelected: true });
}
// return res.status(404).json({ message: 'Media not found' });
}
await Media.destroy({ where: { id: mediaId } })
res.status(200).json();
});
// * DELETE - ENTRY BY ID
entryRouter.delete('/:id', async (req, res) => {
const { id } = req.params;
try {
const numDeleted = await Entry.destroy({
where: { id: id }
});
if (numDeleted) {
res.status(200).json({ message: `Entry with ID ${id} deleted.` });
} else {
res.status(404).json({ message: `Entry with ID ${id} not found.` });
}
} catch (error) {
res.status(500).json({ message: `Error deleting entry with ID ${id}.`, error: error.message });
}
});
module.exports = entryRouter;