Major rework of media handelling, and collections

This commit is contained in:
X4Lo committed 2024-09-13 21:27:01 +01:00
1 parent b42e055691
commit f7cb2bed53
37 files changed
+1120 -411

No files matched your search

+30 -6
View File
@@ -89,13 +89,37 @@ EntryGenre.belongsTo(Genre, { foreignKey: 'genre_id', as: 'genre' });
// Entry.hasMany(Media, { foreignKey: 'entryId', as: 'medias', onDelete: 'CASCADE', });
// Media.belongsTo(Entry, { foreignKey: 'entryId', as: 'entry' });
// * ENTRY & MEDIA - ONE TO MANY
Media.belongsTo(Entry, { foreignKey: 'mediaableId', as: 'entry', constraints: false, scope: { mediaable: 'entry' } });
Media.belongsTo(Collection, { foreignKey: 'mediaableId', as: 'collection', constraints: false, scope: { mediaable: 'collection' } });
Media.belongsTo(Entry, {
foreignKey: 'mediaableId',
as: 'entry',
constraints: false,
where: {
mediaable: 'entry'
}
});
// * ENTRY & COLLECTION - ONE TO MANY
Entry.hasMany(Media, { foreignKey: 'mediaableId', constraints: false, as: 'medias', scope: { mediaable: 'entry' } });
Collection.hasMany(Media, { foreignKey: 'mediaableId', constraints: false, as: 'medias', scope: { mediaable: 'collection' } });
Media.belongsTo(Collection, {
foreignKey: 'mediaableId',
as: 'collection',
constraints: false,
where: {
mediaable: 'collection'
}
});
Entry.hasMany(Media, {
foreignKey: 'mediaableId',
constraints: false,
as: 'medias',
scope: { mediaable: 'entry' }
});
Collection.hasMany(Media, {
foreignKey: 'mediaableId',
constraints: false,
as: 'medias',
scope: { mediaable: 'collection' }
});
// * ENTRY & SEASON - ONE TO MANY
Entry.hasMany(Season, { foreignKey: 'entry_id', as: 'seasons', onDelete: 'CASCADE', });
+9 -9
View File
@@ -4,7 +4,7 @@ const Entry = require('../models/Entry')
const EntryId = require('../models/EntryId')
const EntryRating = require('../models/EntryRating')
const EntrySeen = require('../models/EntrySeen');
const UserCollection = require('../models/UserCollection');
const UserCollection = require('../models/Collection');
const UserCollectionEntry = require('../models/UserCollectionEntry');
const Season = require('../models/Season');
const Episode = require('../models/Episode');
@@ -92,14 +92,14 @@ UserCollectionEntry.afterDestroy(async (instance, options) => {
// ? updating collection poster
// ? remove the poster if the collection is empty now
if (collectionsEntries.length == 0) {
updates.poster = null;
} else {
// ? replace poster it belonged to the removed entry
// if (userCollection.poster_path == entry.poster_path) {
// updates.poster_path = collectionsEntries[0].entry.poster_path;
// }
}
// if (collectionsEntries.length == 0) {
// updates.poster = null;
// } else {
// // ? replace poster it belonged to the removed entry
// // if (userCollection.poster_path == entry.poster_path) {
// // updates.poster_path = collectionsEntries[0].entry.poster_path;
// // }
// }
// ? updating order, only if the removed entry isn't placed at the end
let order = instance.order;
+13 -4
View File
@@ -1,7 +1,7 @@
const express = require('express');
const EntrySeen = require('../models/EntrySeen');
const Entry = require('../models/Entry');
const Media = require('../models/Media');
const Collection = require('../models/Collection');
const customMediaRouter = express.Router();
@@ -11,12 +11,21 @@ customMediaRouter.get('/', async (req, res) => {
const allCustomMedia = await Media.findAll({
where: {
isCustom: true
isCustom: true,
},
include: [
{ model: Entry, as: 'entry' }
{
model: Entry,
as: 'entry',
required: false // This ensures a LEFT OUTER JOIN
},
{
model: Collection,
as: 'collection',
required: false // This ensures a LEFT OUTER JOIN
}
]
})
});
res.status(200).json(allCustomMedia);
});
+29 -42
View File
@@ -6,7 +6,7 @@ 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 } = require('../services/mediaService');
const { generatePreview, doGeneratePreview } = require('../services/mediaService');
const { Sequelize } = require('sequelize');
const Entry = require('../models/Entry');
@@ -18,6 +18,8 @@ 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
@@ -77,7 +79,12 @@ entryRouter.get('/:id', async (req, res) => {
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: UserCollection, as: 'collections' },
{
model: UserCollection, as: 'collections',
include: [
{ model: Media, as: 'medias' }
]
},
{
model: Genre,
as: 'genres',
@@ -155,37 +162,7 @@ entryRouter.post('/', async (req, res) => {
const entry = await saveEntry(entryData);
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 })
}
upsertOfficialCollection(entryData.belongs_to_collection.id);
}
res.status(201).json(entry);
@@ -285,7 +262,7 @@ entryRouter.put('/:id', async (req, res) => {
});
// * GET - REQUEST ENTRY REFRECH
entryRouter.get('/:id/refrech', async (req, res, next) => {
entryRouter.get('/:id/refresh', async (req, res, next) => {
const { id } = req.params;
try {
@@ -382,15 +359,25 @@ entryRouter.post('/:id/media', upload, async (req, res) => {
});
// ? generating low resolution preview
const fileNameWithoutExt = file.filename.split('.')[0];
const originalPath = file.path;
// 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;
// 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);
// 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);
}
@@ -417,7 +404,7 @@ entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => {
{ isSelected: false },
{
where: {
entryId: entryId,
mediaableId: entryId,
type: media.type
}
}
+13 -11
View File
@@ -3,7 +3,8 @@ const path = require('path');
const fs = require('fs');
const { getSettings } = require('../services/settingsService');
const { generatePreview } = require('../services/mediaService');
const { generatePreview, doGeneratePreview } = require('../services/mediaService');
const { logToFile } = require('../services/logService');
const mediaRouter = express.Router();
@@ -43,21 +44,22 @@ mediaRouter.get('/:category/:type/:size/:fileName', (req, res, next) => {
// ? and generate a preview file, but still return 202 http code since the file
// ? is still generating
if (err && size == 'preview') {
const originalPath = path.join(mediaPath, fileName);
const previewFileName = fileName.split('.')[0] + '_preview.jpg'
const previewPath = path.join(mediaPath, previewFileName);
// const originalPath = path.join(mediaPath, fileName);
// const previewFileName = fileName.split('.')[0] + '_preview.jpg'
// const previewPath = path.join(mediaPath, previewFileName);
let previewWidth = 342;
if (type == 'backdrops') previewWidth = 780;
if (type == 'logos') previewWidth = 300;
// let previewWidth = 342;
// if (type == 'backdrops') previewWidth = 780;
// if (type == 'logos') previewWidth = 300;
generatePreview(originalPath, previewPath, previewWidth).then((result) => {
console.log(`generated a preview: `, previewFileName);
doGeneratePreview(category, type, fileName).then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
logToFile(`Media Route | Generated Preview`);
}).catch((err) => {
});;
logToFile(`Media Route | Error Generating Preview`);
logToFile(err);
});
// const stream = fs.createReadStream(filePath);
// stream.pipe(res);
// return res.status(202).send('Preview is still generating. Please try again later.');
+2 -2
View File
@@ -1,5 +1,5 @@
const express = require('express');
const userCollectionRoutes = require('./user-collection.routes');
const collectionRouter = require('./user-collection.routes');
const entryIdsRouter = require('./entry-ids.routes');
const entrySeenRouter = require('./entry-seen.routes');
const entryRouter = require('./entry.routes');
@@ -16,7 +16,7 @@ const episodeRouter = require('./episode.routes');
const router = express.Router();
router.use('/media', mediaRouter);
router.use('/entries', entryRouter);
router.use('/user-collections', userCollectionRoutes);
router.use('/collections', collectionRouter);
router.use('/entry-seen', entrySeenRouter);
router.use('/entry-ids', entryIdsRouter);
router.use('/entry-ratings', entryRatingsRouter);
+208 -88
View File
@@ -1,5 +1,10 @@
const express = require('express');
const UserCollection = require('../models/UserCollection');
const collectionRouter = express.Router();
const { doGeneratePreview } = require('../services/mediaService');
const { Sequelize } = require('sequelize');
const Collection = require('../models/Collection');
const UserCollectionEntry = require('../models/UserCollectionEntry');
const Entry = require('../models/Entry');
const EntryId = require('../models/EntryId');
@@ -8,58 +13,61 @@ const Season = require('../models/Season');
const Genre = require('../models/Genre');
const Media = require('../models/Media');
const { Sequelize } = require('sequelize');
const router = express.Router();
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const { getMediaFolder, generatePreview } = require('../services/mediaService');
const { getCollectionParts, upsertOfficialCollection } = require('../services/models-services/collectionService');
const { collectionPicturesUpload } = require('../services/mutlerStorageLocations');
const { logToFile } = require('../services/logService');
// ! /user-collections
// * GET - ALL UserCollections
router.get('/', async (req, res) => {
let userCollections; // Declare outside to broaden scope, albeit unnecessary in your given context
// ! /collections
// * GET - ALL COLLECTIONS
collectionRouter.get('/', async (req, res) => {
let collections; // Declare outside to broaden scope, albeit unnecessary in your given context
try {
userCollections = await UserCollection.findAll({
collections = await Collection.findAll({
include: [
{
model: Entry, as: 'entries',
include: { model: Media, as: 'medias' }
},
{ model: Media, as: 'medias' }
],
order: [['name', 'ASC']]
});
res.status(200).json(userCollections);
res.status(200).json(collections);
} catch (error) {
console.error("Error fetching UserCollections:", error); // More detailed error logging
res.status(500).json({ error: error.message });
}
});
// * GET - userCollection BY ID
router.get('/:id', async (req, res) => {
// * GET - COLLECTION BY ID
collectionRouter.get('/:id', async (req, res) => {
try {
const userCollection = await UserCollection.findByPk(req.params.id, {
include: [{
model: Entry,
as: 'entries',
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' },
],
through: {
model: UserCollectionEntry,
attributes: ['order'], // attributes (to include) from the join model
const collectionId = req.params.id;
const collection = await Collection.findByPk(collectionId, {
include: [
{
model: Entry,
as: 'entries',
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' },
],
through: {
model: UserCollectionEntry,
attributes: ['order'], // attributes (to include) from the join model
},
},
}],
{ model: Media, as: 'medias' },
],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});
if (userCollection) {
const collectionData = userCollection.get({ plain: true });
if (collection) {
const collectionData = collection.get({ plain: true });
for (let i = 0; i < collectionData.entries.length; i++) {
const genres = collectionData.entries[i].genres.map(genre => genre.name);
collectionData.entries[i].genres = genres
@@ -75,70 +83,173 @@ router.get('/:id', async (req, res) => {
}
});
// * POST - CREATE UserCollection
router.post('/', async (req, res) => {
// * POST - CREATE COLLECTION
collectionRouter.post('/', async (req, res) => {
try {
const { name, description, userRating, posterPath } = req.body;
const isUserCollection = true;
const newUserCollection = await UserCollection.create({ name, description, userRating, posterPath, isUserCollection });
const newUserCollection = await Collection.create({ name, description, userRating, posterPath, isUserCollection });
res.status(201).json(newUserCollection);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(getMediaFolder(), 'images', 'collections', 'posters'))
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split('.').pop();
cb(null, `${uniqueFilename}.${extension}`);
}
});
const upload = multer({ storage: storage });
// * PUT - UPDATE A UserCollection
router.put('/:id', upload.single('poster'), async (req, res) => {
// * PUT - UPDATE COLLECTION
const upload = collectionPicturesUpload.fields([
{ name: 'poster', maxCount: 1 },
{ name: 'backdrop', maxCount: 1 }
]);
collectionRouter.put('/:id', upload, async (req, res) => {
try {
const userCollectionId = req.params.id;
const { name, description, userRating, is_poster_link } = req.body;
const collectionId = req.params.id;
const { name, description, userRating } = req.body;
let posterPath = req.file ? req.file.filename : undefined;
const posterFile = req.files.poster ? req.files.poster[0] : undefined;
const backdropFile = req.files.backdrop ? req.files.backdrop[0] : undefined;
let posterPath = posterFile ? posterFile.filename : undefined;
let backdropPath = backdropFile ? backdropFile.filename : undefined;
const updateData = {
name,
description,
userRating: parseInt(userRating, 10),
isLocal: false,
};
if (posterPath) {
updateData.posterPath = posterPath;
updateData.isLocal = true;
// ? generating preview
doGeneratePreview("collections", 'posters', posterPath).then((result) => {
const msg = `Collection Service | Generated Collection Preview`;
logToFile(msg);
}).catch((err) => {
const msg = `Collection Service | Error Generating Collection Preview`;
logToFile(msg);
logToFile(err);
});
// ? generating preview
const fileNameWithoutExt = req.file.filename.split('.')[0];
const originalPath = req.file.path;
let previewWidth = 342; // ? poster preview width
const previewPath = path.join(req.file.destination, `${fileNameWithoutExt}_preview.jpg`);
generatePreview(originalPath, previewPath, previewWidth);
await Media.create({
mediaable: 'collection',
mediaableId: collectionId,
type: 'poster',
path: posterPath,
isLocal: true,
isSelected: true,
isCustom: true
})
}
const updated = await UserCollection.update(updateData, {
where: { id: userCollectionId }
if (backdropPath) {
// ? generating preview
doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => {
const msg = `Collection Routes | Generated Collection Preview`;
logToFile(msg);
}).catch((err) => {
const msg = `Collection Routes | Error Generating Collection Preview`;
logToFile(msg);
logToFile(err);
});
// ? inserting data
await Media.create({
mediaable: 'collection',
mediaableId: collectionId,
type: 'backdrop',
path: backdropPath,
isLocal: true,
isSelected: true,
isCustom: true
})
}
const oldCollection = await Collection.findByPk(collectionId, {
include: [{
model: Entry,
as: 'entries',
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' },
],
through: {
model: UserCollectionEntry,
attributes: ['order'], // attributes (to include) from the join model
},
},
{ model: Media, as: 'medias' },
],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});
if (!updated[0]) {
return res.status(404).json({ message: 'UserCollection not found' });
}
if (!oldCollection)
res.status(404).json({ message: 'Collection not found' });
if (updated) {
const updatedUserCollection = await UserCollection.findByPk(userCollectionId, {
include: [{
await oldCollection.update(updateData);
res.status(200).json(oldCollection);
} catch (error) {
console.log(`UserCollection update (put) error: `, error)
res.status(500).json({ error: error.message });
}
});
// * PUT - REFRESH COLLECTION
collectionRouter.put('/:id/refresh', async (req, res) => {
try {
const collectionId = req.params.id;
const oldCollection = await Collection.findByPk(collectionId);
const collection = await upsertOfficialCollection(oldCollection.tmdbId);
// const collection = await Collection.findByPk(collectionId, {
// include: [{
// model: Entry,
// as: 'entries',
// include: [
// { model: EntryId, as: 'entryId' },
// { model: EntryRating, as: 'entryRating' },
// { model: Season, as: 'seasons' },
// { model: Media, as: 'medias' },
// { model: Genre, as: 'genres' },
// ],
// through: {
// model: UserCollectionEntry,
// attributes: ['order'], // attributes (to include) from the join model
// },
// }],
// order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
// });
if (collection) {
const collectionData = collection.get({ plain: true });
for (let i = 0; i < collectionData.entries.length; i++) {
const genres = collectionData.entries[i].genres.map(genre => genre.name);
collectionData.entries[i].genres = genres
}
res.status(200).json(collectionData);
} else {
res.status(404).json({ message: 'Collection not found' });
}
} catch (error) {
console.log(`UserCollection update (put) error: `, error)
res.status(500).json({ error: error.message });
}
});
// * PUT - GET COLLECTION PARTS
collectionRouter.put('/:id/parts', async (req, res) => {
try {
const collectionId = req.params.id;
await getCollectionParts(collectionId);
const collection = await Collection.findByPk(collectionId, {
include: [
{
model: Entry,
as: 'entries',
include: [
@@ -152,13 +263,22 @@ router.put('/:id', upload.single('poster'), async (req, res) => {
model: UserCollectionEntry,
attributes: ['order'], // attributes (to include) from the join model
},
}],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});
},
{ model: Media, as: 'medias' },
],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});
res.status(200).json(updatedUserCollection);
if (collection) {
const collectionData = collection.get({ plain: true });
for (let i = 0; i < collectionData.entries.length; i++) {
const genres = collectionData.entries[i].genres.map(genre => genre.name);
collectionData.entries[i].genres = genres
}
res.status(200).json(collectionData);
} else {
res.status(404).json({ message: 'UserCollection not found' });
res.status(404).json({ message: 'Collection not found' });
}
} catch (error) {
console.log(`UserCollection update (put) error: `, error)
@@ -166,10 +286,10 @@ router.put('/:id', upload.single('poster'), async (req, res) => {
}
});
// * DELETE - A UserCollection
router.delete('/:id', async (req, res) => {
// * DELETE - DELETE COLLECTION
collectionRouter.delete('/:id', async (req, res) => {
try {
const deleted = await UserCollection.destroy({ where: { id: req.params.id } });
const deleted = await Collection.destroy({ where: { id: req.params.id } });
if (deleted) {
res.status(204).send();
} else {
@@ -180,8 +300,8 @@ router.delete('/:id', async (req, res) => {
}
});
// * POST - ADD ENTRY TO A UserCollection
router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
// * POST - ADD ENTRY TO A COLLECTION
collectionRouter.post('/:userCollectionId/entries/:entryId', async (req, res) => {
try {
const { userCollectionId, entryId } = req.params;
@@ -191,7 +311,7 @@ router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
});
// ? set a default poster if none exists
const userCollection = await UserCollection.findByPk(userCollectionId);
const userCollection = await Collection.findByPk(userCollectionId);
if (!userCollection.poster_path || userCollection.poster_path.trim() === '') {
const entry = await Entry.findByPk(entryId);
userCollection.poster_path = entry.poster_path;
@@ -205,8 +325,8 @@ router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
}
});
// * PATCH - UPDATE ENTRY ORDER IN UserCollection
router.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
// * PATCH - UPDATE ENTRY ORDER IN COLLECTION
collectionRouter.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
try {
const { userCollectionId, entryId } = req.params;
const { newOrder } = req.body;
@@ -233,8 +353,8 @@ router.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
}
});
// * DELETE - REMOVE AN ENTRY FROM A UserCollection
router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
// * DELETE - REMOVE AN ENTRY FROM A COLLECTION
collectionRouter.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
try {
const { userCollectionId, entryId } = req.params;
const deleted = await UserCollectionEntry.findOne({
@@ -258,13 +378,13 @@ router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
});
// * POST - CREATE UserCollection WITH ENTRY
router.post('/lists-with-entry', async (req, res) => {
collectionRouter.post('/lists-with-entry', async (req, res) => {
const { listDetails, entryId, entryOrder } = req.body; // Destructure needed properties from the request body
try {
const result = await sequelize.transaction(async (t) => {
// Step 1: Create the userCollection
const newUserCollection = await UserCollection.create(listDetails, { transaction: t });
const newUserCollection = await Collection.create(listDetails, { transaction: t });
// Step 2: Add an entry to the newly created userCollection
const newUserCollectionEntry = await UserCollectionEntry.create({
@@ -284,4 +404,4 @@ router.post('/lists-with-entry', async (req, res) => {
}
});
module.exports = router;
module.exports = collectionRouter;
+59 -26
View File
@@ -13,15 +13,21 @@ async function deleteMissingFilesEntries(dry = false) {
const dataPath = await getMediaFolder();
// Handling different media types
const mediaTypes = {
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
const mediaTypeFolder = {
'entryposter': path.join(dataPath, 'images', 'entries', 'posters'),
'entrylogo': path.join(dataPath, 'images', 'entries', 'logos'),
'entrybackdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
'collectionposter': path.join(dataPath, 'images', 'collections', 'posters'),
'collectionlogo': path.join(dataPath, 'images', 'collections', 'logos'),
'collectionbackdrop': path.join(dataPath, 'images', 'collections', 'backdrops')
};
let missingFiles = [];
for (let i = 0; i < allMedia.length; i++) {
let type = `${allMedia[i].type}`.replace("_preview", "");
const filePath = path.join(mediaTypes[type], allMedia[i].path)
const folderType = `${allMedia[i].mediaable}${allMedia[i].type.replace("_preview", "")}`;
const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path)
if (!fs.existsSync(filePath)) {
missingFiles.push(allMedia[i]);
}
@@ -33,40 +39,55 @@ async function deleteMissingFilesEntries(dry = false) {
'backdrops': 0
};
if (missingFiles.length == 0)
return removed;
// if (missingFiles.length == 0)
// return removed;
for (let i = 0; i < missingFiles.length; i++) {
removed[missingFiles[i].type] += 1;
removed[missingFiles[i].type + 's'] += 1;
if (!dry) missingFiles[i].destroy();
}
if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
return removed;
}
/**
* Delete orphan files from media folder data,
* orphan files are files that exist in the `folder data`
* but do not have an instance in the database
* @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false`
*/
async function deleteOrphanFiles(dry = false) {
// Getting the userDataPath to store the images
const dataPath = getMediaFolder();
// ? Getting the path of all media files and putting them in an array
const allMedia = (await Media.findAll()).map(m =>
path.join(dataPath, 'images', 'entries', m.type + 's', m.path)
);
// const allMedia = (await Media.findAll()).map(m => {
// if (m.mediaable == 'entry')
// return path.join(dataPath, 'images', 'entries', m.type + 's', m.path)
// else if (m.mediaable == 'collection')
// return path.join(dataPath, 'images', 'collections', m.type + 's', m.path)
// });
// ? Getting the name (without extention) of all media in database
const allMedia = (await Media.findAll()).map(m => {
return m.path.split('.')[0]
});
// ? Loop trough the files of the images folder and check
// ? if a file doesnt exist in the allMedia array and mark it to delete
const mediaTypeFolder = {
'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'),
'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'),
'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
let orphanFiles = [];
const mediaTypes = {
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'),
'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops')
};
// * counter
let removed = {
'posters': 0,
'logos': 0,
@@ -74,19 +95,31 @@ async function deleteOrphanFiles(dry = false) {
};
// Iterate over each media type directory and check for orphan files
for (let type in mediaTypes) {
const directory = mediaTypes[type];
for (let folderType in mediaTypeFolder) {
const directory = mediaTypeFolder[folderType];
try {
// ? getting all files inside that folder
const files = await fsPromises.readdir(directory).then();
// console.log(`${directory}, files count: ${files.length}`);
// Check each file in the directory
for (let file of files) {
const filePath = path.join(directory, file);
// Check if the constructed file path exists in the allMedia array
if (!allMedia.includes(filePath.replace("_preview", ""))) {
// If not, delete the file
// const filePath = path.join(directory, file);
// // Check if the constructed file path exists in the allMedia array
// // ? this step also takes into account preview files, by removing '_preview'
// // ? and verifying if the file path is in database
// const hasJpgFormat = allMedia.includes(filePath.replace("_preview.jpg", ".jpg"));
// const hasPngFormat = allMedia.includes(filePath.replace("_preview.jpg", ".png"));
// const hasGifFormat = allMedia.includes(filePath.replace("_preview.jpg", ".gif"));
// preparing the file name
const fileName = file.split('.')[0].replace("_preview", "");
const isInDatabase = allMedia.includes(fileName);
// if the file isn't in database even on other extentions then delete it
if (!isInDatabase) {
removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files
if (!dry) await fsPromises.unlink(filePath);
removed[type + 's']++; // Increment the count of removed files
}
}
} catch (err) {
+76 -17
View File
@@ -6,6 +6,7 @@ const { v4: uuidv4 } = require('uuid');
const { fetchEntryMedia } = require('./tmdbService');
const { getSettings } = require('./settingsService');
const sharp = require('sharp');
const { logToFile } = require('./logService');
async function downloadImage(url, filePath) {
const response = await axios({
@@ -66,6 +67,41 @@ async function getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos'
return downloadedImages;
}
async function downloadCollectionMedia(collection) {
if (!collection) return null;
// Local variables for this function invocation
let downloadTasks = [];
let downloadedImages = [];
createMediaFolders(); // Ensuring directories exist
// Getting the userDataPath to store the images
const settings = getSettings();
const dataPath = settings.userDataPath;
const hasPoster = collection.medias && collection.medias.filter((m) => m.type == 'poster').length != 0;
if (collection.posterPath && !hasPoster) {
const postersDir = path.join(dataPath, 'images', 'collections', 'posters')
scheduleDownloads({ file_path: collection.posterPath }, 'poster', postersDir, downloadTasks, downloadedImages);
}
const hasBackdrop = collection.medias && collection.medias.filter((m) => m.type == 'backdrop').length != 0;
if (collection.backdropPath && !hasBackdrop) {
const backdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops')
scheduleDownloads({ file_path: collection.backdropPath }, 'backdrop', backdropsDir, downloadTasks, downloadedImages);
}
// Wait for all downloads to complete
await Promise.all(downloadTasks).then(() => {
console.log('Downloaded images:', downloadedImages);
}).catch(err => {
console.error('Error downloading entry images:', err);
});
return downloadedImages;
}
// Utility to find the preferred media (English if available, otherwise the first one)
function findPreferredMedia(mediaArray, preferredLanguage = 'en') {
return mediaArray.find(media => media.iso_639_1 === preferredLanguage && !media.file_path.includes('.svg')) || mediaArray.find(media => !media.file_path.includes('.svg')) || mediaArray[0];
@@ -76,25 +112,22 @@ function scheduleDownloads(media, mediaType, mediaDir, downloadTasks, downloaded
const uniqueFilename = uuidv4();
const extension = media.file_path.split('.').pop();
const originalUrl = `https://image.tmdb.org/t/p/original${media.file_path}`;
const originalFileName = `${uniqueFilename}.${extension}`;
const originalFilePath = path.join(mediaDir, originalFileName);
const url = `https://image.tmdb.org/t/p/original${media.file_path}`;
const filename = `${uniqueFilename}.${extension}`;
const downloadPath = path.join(mediaDir, filename);
// Schedule download of the original image
downloadTasks.push(
downloadImage(originalUrl, originalFilePath)
.then(() => downloadedImages.push({ type: mediaType, path: originalFileName }))
.catch(err => console.error(`Error downloading ${mediaType}:`, err))
);
const previewUrl = `https://image.tmdb.org/t/p/w300${media.file_path}`;
const previewFileName = `${uniqueFilename}_preview.${extension}`;
const previewFilePath = path.join(mediaDir, previewFileName);
// Schedule download of the preview image
downloadTasks.push(
downloadImage(previewUrl, previewFilePath)
.catch(err => console.error(`Error downloading preview ${mediaType}:`, err))
downloadImage(url, downloadPath)
.then(() => {
logToFile(`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`)
downloadedImages.push({ type: mediaType, path: filename })
})
.catch(err => {
logToFile(`Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`)
logToFile(err)
console.error(`Error downloading ${mediaType}:`, err)
})
);
}
@@ -105,6 +138,28 @@ function generatePreview(originalPath, previewPath, previewWidth, previewQuality
.toFile(previewPath);
}
function doGeneratePreview(fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80) {
const dataPath = getSettings().userDataPath;
const mediaPath = path.join(dataPath, 'images', fileCategory, fileType);
const originalPath = path.join(mediaPath, originalFileName);
const fileNameWithoutExt = originalFileName.split('.')[0];
const previewFileName = fileNameWithoutExt + '_preview.jpg'
const previewPath = path.join(mediaPath, previewFileName);
if (previewWidth == 0) {
previewWidth = 342; // ? poster
if (fileType == 'backdrops') previewWidth = 780;
if (fileType == 'logos') previewWidth = 300;
}
return sharp(originalPath)
.resize({ width: previewWidth })
.jpeg({ quality: previewQuality })
.toFile(previewPath);
}
function getMediaFolder() {
return getSettings().userDataPath;
}
@@ -117,11 +172,13 @@ function createMediaFolders() {
const backdropDir = path.join(dataPath, 'images', 'entries', 'backdrops');
const logoDir = path.join(dataPath, 'images', 'entries', 'logos');
const collectionsPostersDir = path.join(dataPath, 'images', 'collections', 'posters');
const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops');
fs.mkdirSync(posterDir, { recursive: true });
fs.mkdirSync(backdropDir, { recursive: true });
fs.mkdirSync(logoDir, { recursive: true });
fs.mkdirSync(collectionsPostersDir, { recursive: true });
fs.mkdirSync(collectionsBackdropsDir, { recursive: true });
// console.log(`Created media folders.`);
}
@@ -130,5 +187,7 @@ module.exports = {
getEntryMedia,
createMediaFolders,
getMediaFolder,
generatePreview
generatePreview,
doGeneratePreview,
downloadCollectionMedia
};
@@ -0,0 +1,142 @@
const { Sequelize } = require("sequelize");
const Entry = require("../../models/Entry");
const EntryId = require("../../models/EntryId");
const UserCollection = require("../../models/Collection");
const { fetchCollectionData, fetchEntryData } = require("../tmdbService");
const { downloadCollectionMedia, doGeneratePreview } = require("../mediaService");
const Media = require("../../models/Media");
const Collection = require("../../models/Collection");
const { saveEntry } = require("./entryService");
const { logToFile } = require("../logService");
const EntryRating = require("../../models/EntryRating");
const Season = require("../../models/Season");
const Genre = require("../../models/Genre");
const UserCollectionEntry = require("../../models/UserCollectionEntry");
/**
* Creates or updates an official collection,
* it also create an association to all related library entries
* @collection_tmdbId tmdb id of the collection
*/
async function upsertOfficialCollection(collection_tmdbId) {
let collectionData = await fetchCollectionData(collection_tmdbId);
// * 1 - collection info
const [oldCollection, createdCollection] = await UserCollection.findOrCreate({
where: { tmdbId: collectionData.id },
defaults: {
name: collectionData.name,
posterPath: collectionData.poster_path,
backdropPath: collectionData.backdrop_path,
description: collectionData.overview
},
include: [{ model: Media, as: 'medias' }]
});
// * 2 - collection entries
let collection = oldCollection || createdCollection;
if (collection) {
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 collection.setEntries(entries);
// * 3 - collection media
// ? downloading
const downloadedImages = await downloadCollectionMedia(collection);
// ? generating preview & inserting data
for (const image of downloadedImages) {
// ? generating preview
doGeneratePreview('collections', image.type + 's', image.path).then((result) => {
const msg = `Collection Service | Generated Collection Preview`;
console.log(msg);
logToFile(msg);
}).catch((err) => {
const msg = `Collection Service | Error Generating Collection Preview`;
console.log(msg);
console.log(err);
logToFile(msg);
logToFile(err);
});
// ? inserting data
await Media.create({
mediaable: 'collection',
mediaableId: collection.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
})
}
}
return await Collection.findByPk(collection.id, {
include: [{
model: Entry,
as: 'entries',
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' },
],
through: {
model: UserCollectionEntry,
attributes: ['order'], // attributes (to include) from the join model
},
}],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});;
}
/**
* Adds the other parts of the collection to the library
* @collectionId id of the collection
*/
async function getCollectionParts(collectionId) {
const collection = await Collection.findByPk(collectionId);
const collectionData = await fetchCollectionData(collection.tmdbId);
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
}
}
}]
});
collectionData.parts.forEach(async (part) => {
if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) {
const isTvSeries = false;
const entryData = await fetchEntryData(part.id, isTvSeries);
const entry = await saveEntry(entryData);
await collection.addEntries([entry.id]);
}
});
}
module.exports = {
upsertOfficialCollection,
getCollectionParts,
}
@@ -1,3 +1,14 @@
const moment = require('../../utils/moment.js');
const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js');
const { getEntryMedia, doGeneratePreview } = require('../mediaService.js');
const { logToFile } = require('../logService.js');
const NotFoundError = require('../../errors/NotFoundError.js');
const InternalServerError = require('../../errors/InternalServerError.js');
const { ValidationError, Op } = require('sequelize');
const Collection = require('../../models/Collection.js');
const Entry = require('../../models/Entry.js')
const EntryId = require('../../models/EntryId.js')
const EntryRating = require('../../models/EntryRating.js');
@@ -8,15 +19,6 @@ const Episode = require('../../models/Episode.js');
const Media = require('../../models/Media.js');
const Genre = require('../../models/Genre.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 { logToFile } = require('../logService.js');
const { ValidationError, Op } = require('sequelize');
const moment = require('../../utils/moment.js');
async function saveEntry(data) {
try {
if (data == null) return;
@@ -132,7 +134,7 @@ async function saveEntry(data) {
// ? media
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
console.log(`entry service, downloaded images: `, downloadedImages)
// console.log(`entry service, downloaded images: `, downloadedImages)
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
@@ -141,7 +143,9 @@ async function saveEntry(data) {
path: image.path,
isLocal: true,
isSelected: true
})
});
doGeneratePreview('entries', image.type + 's', image.path);
}
@@ -348,27 +352,27 @@ async function refrechEntry(entryId) {
}
// ? getting new data from TMDB
const data = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (data == null) {
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (entryData == 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,
title: entryData.title || entryData.name,
original_title: entryData.original_title || entryData.original_name,
release_date: entryData.release_date || entryData.first_air_date,
release_status: entryData.status,
runtime: entryData.runtime || null,
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
status: data.status,
status: entryData.status,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date()
};
@@ -378,17 +382,17 @@ async function refrechEntry(entryId) {
// * updating ids
// TODO: get more ids
await oldEntry.entryId.update({
imdb_id: data.imdb_id,
imdb_id: entryData.imdb_id,
});
// * updating ratings
await oldEntry.entryRating.update({
tmdb_rating: data.vote_average
tmdb_rating: entryData.vote_average
});
// * updating genres
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
data.genres.forEach(async (genre) => {
entryData.genres.forEach(async (genre) => {
// if the entry already has this genre then skip
if (currentGenresIds.includes(genre.id)) return;
@@ -406,9 +410,9 @@ async function refrechEntry(entryId) {
// ? and atleast 48 hours has passed
// * Update or insert seasons for the entry
for (const season of data.seasons) {
for (const season of entryData.seasons) {
// fetch new season data from tmdb
let seasonData = await fetchSeasonData(data.id, season.season_number);
let seasonData = await fetchSeasonData(entryData.id, season.season_number);
// Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({
@@ -498,32 +502,27 @@ async function refrechEntry(entryId) {
// * Media
// ? Only fetch if a Poster, Backdrop or a Logo is missing
// ? only get missing media types
// ? count media by type
let availableMedia = {
'posters': 0,
'logos': 0,
'backdrops': 0
};
for (let i = 0; i < oldEntry.medias.length; i++) {
availableMedia[oldEntry.medias[i].type + 's'] += 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(key);
}
let downloadedImages;
if (oldEntry.medias.length < 3) {
// ? 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 (mediaToGet.length != 0) {
downloadedImages = await getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
}
if (downloadedImages) {
@@ -539,6 +538,12 @@ async function refrechEntry(entryId) {
}
}
// ? fetch collection
if (entryData.belongs_to_collection) {
const collectionService = require('./collectionService.js');
await collectionService.upsertOfficialCollection(entryData.belongs_to_collection.id);
}
// + end of: refrech logic
// ! returning the refreshed entry
@@ -548,6 +553,7 @@ async function refrechEntry(entryId) {
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Collection, as: 'collections' },
{
model: Genre,
as: 'genres',
@@ -566,8 +572,8 @@ async function refrechEntry(entryId) {
]
});
const entryData = updatedEntry.get({ plain: true });
entryData.genres = entryData.genres.map(genre => genre.name);
const plainEntry = updatedEntry.get({ plain: true });
plainEntry.genres = plainEntry.genres.map(genre => genre.name);
return entryData;
}
+21 -2
View File
@@ -12,8 +12,7 @@ const entryPicturesUpload = multer({
if (file.fieldname == 'backdrop') folder = 'backdrops';
if (file.fieldname == 'logo') folder = 'logos';
const settings = getSettings();
const dataPath = settings.userDataPath;
const dataPath = getSettings().userDataPath;
cb(null, path.join(dataPath, 'images', 'entries', folder));
},
@@ -25,7 +24,27 @@ const entryPicturesUpload = multer({
})
});
const collectionPicturesUpload = multer({
storage:
multer.diskStorage({
destination: function (req, file, cb) {
let folder = 'posters';
if (file.fieldname == 'backdrop') folder = 'backdrops';
if (file.fieldname == 'logo') folder = 'logos';
const dataPath = getSettings().userDataPath;
cb(null, path.join(dataPath, 'images', 'collections', folder));
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split('.').pop();
cb(null, `${uniqueFilename}.${extension}`);
}
})
});
module.exports = {
entryPicturesUpload,
collectionPicturesUpload,
}