From f7cb2bed53dfed103a3146530f2d829cf2a5e6e8 Mon Sep 17 00:00:00 2001 From: X4Lo Date: Fri, 13 Sep 2024 21:27:01 +0100 Subject: [PATCH] Major rework of media handelling, and collections --- angular.json | 4 +- backend/db/relations.js | 36 ++- backend/db/sequelizeHooks.js | 18 +- backend/routes/custom-media.routes.js | 17 +- backend/routes/entry.routes.js | 71 ++--- backend/routes/media.routes.js | 24 +- backend/routes/routes.js | 4 +- backend/routes/user-collection.routes.js | 296 ++++++++++++------ backend/services/maintenanceService.js | 85 +++-- backend/services/mediaService.js | 93 +++++- .../models-services/collectionService.js | 142 +++++++++ .../services/models-services/entryService.js | 118 +++---- backend/services/mutlerStorageLocations.js | 23 +- frontend/src/app/core/core.module.ts | 4 +- .../src/app/core/services/entry.service.ts | 2 +- .../core/services/userCollection.service.ts | 48 ++- .../collection-edit-modal.component.html | 16 +- .../collection-edit-modal.component.ts | 47 ++- .../collection-entry-table.component.ts | 4 +- .../collection-table-line.component.ts | 4 +- .../userCollection-grid-card.component.ts | 4 +- .../userCollection-info-page.component.html | 16 +- .../userCollection-info-page.component.ts | 56 +++- .../userCollections-list-item.component.html | 5 +- .../userCollections-list-item.component.ts | 152 ++++----- .../userCollections-page.component.html | 2 +- .../userCollections-page.component.ts | 85 ++++- .../entry/entry-page/entry-page.component.css | 30 +- .../entry-page/entry-page.component.html | 35 ++- .../entry/entry-page/entry-page.component.ts | 55 +++- .../media-page/media-page.component.html | 6 +- .../media/media-page/media-page.component.ts | 13 +- .../user-collections-modal.component.ts | 4 +- frontend/src/app/shared/models/entry.model.ts | 2 + frontend/src/app/shared/models/media.model.ts | 2 + .../app/shared/models/userCollection.model.ts | 8 + .../images/default/default-backdrop.png | Bin 0 -> 2080 bytes 37 files changed, 1120 insertions(+), 411 deletions(-) create mode 100644 backend/services/models-services/collectionService.js create mode 100644 frontend/src/assets/images/default/default-backdrop.png diff --git a/angular.json b/angular.json index 1091cc7..0456727 100644 --- a/angular.json +++ b/angular.json @@ -81,8 +81,8 @@ }, { "type": "anyComponentStyle", - "maximumWarning": "2kb", - "maximumError": "4kb" + "maximumWarning": "5000kb", + "maximumError": "5mb" } ], "outputHashing": "all" diff --git a/backend/db/relations.js b/backend/db/relations.js index 25a501c..7c715e1 100644 --- a/backend/db/relations.js +++ b/backend/db/relations.js @@ -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', }); diff --git a/backend/db/sequelizeHooks.js b/backend/db/sequelizeHooks.js index 4d7e434..9b4f2c4 100644 --- a/backend/db/sequelizeHooks.js +++ b/backend/db/sequelizeHooks.js @@ -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; diff --git a/backend/routes/custom-media.routes.js b/backend/routes/custom-media.routes.js index c6e5675..b0f5845 100644 --- a/backend/routes/custom-media.routes.js +++ b/backend/routes/custom-media.routes.js @@ -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); }); diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index fdeb713..4b2cf30 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -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 } } diff --git a/backend/routes/media.routes.js b/backend/routes/media.routes.js index 626f8c8..81029dc 100644 --- a/backend/routes/media.routes.js +++ b/backend/routes/media.routes.js @@ -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.'); diff --git a/backend/routes/routes.js b/backend/routes/routes.js index 1d16cd5..9d0c963 100644 --- a/backend/routes/routes.js +++ b/backend/routes/routes.js @@ -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); diff --git a/backend/routes/user-collection.routes.js b/backend/routes/user-collection.routes.js index ddb05fc..cf48347 100644 --- a/backend/routes/user-collection.routes.js +++ b/backend/routes/user-collection.routes.js @@ -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; diff --git a/backend/services/maintenanceService.js b/backend/services/maintenanceService.js index 19345d4..a5a6670 100644 --- a/backend/services/maintenanceService.js +++ b/backend/services/maintenanceService.js @@ -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) { diff --git a/backend/services/mediaService.js b/backend/services/mediaService.js index d106160..1522273 100644 --- a/backend/services/mediaService.js +++ b/backend/services/mediaService.js @@ -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 }; \ No newline at end of file diff --git a/backend/services/models-services/collectionService.js b/backend/services/models-services/collectionService.js new file mode 100644 index 0000000..bc16334 --- /dev/null +++ b/backend/services/models-services/collectionService.js @@ -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, +} \ No newline at end of file diff --git a/backend/services/models-services/entryService.js b/backend/services/models-services/entryService.js index f426092..3319e61 100644 --- a/backend/services/models-services/entryService.js +++ b/backend/services/models-services/entryService.js @@ -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; } diff --git a/backend/services/mutlerStorageLocations.js b/backend/services/mutlerStorageLocations.js index 60f9aa8..10de07e 100644 --- a/backend/services/mutlerStorageLocations.js +++ b/backend/services/mutlerStorageLocations.js @@ -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, } \ No newline at end of file diff --git a/frontend/src/app/core/core.module.ts b/frontend/src/app/core/core.module.ts index 6a405a8..2da5a00 100644 --- a/frontend/src/app/core/core.module.ts +++ b/frontend/src/app/core/core.module.ts @@ -4,7 +4,7 @@ import { CommonModule } from '@angular/common'; import { TmdbService } from './services/tmdb.service'; import { LibraryService } from './services/library.service'; import { EntryService } from './services/entry.service'; -import { UserCollectionService } from './services/userCollection.service'; +import { CollectionService } from './services/userCollection.service'; import { ToggleService } from './services/toggle.service'; import { SidebarComponent } from './components/sidebar/sidebar.component'; import { NavbarComponent } from './components/navbar/navbar.component'; @@ -32,7 +32,7 @@ import { SharedModule } from '../shared/shared.module'; LibraryService, EntryService, EntrySeenService, - UserCollectionService, + CollectionService, ToggleService, EpisodeService, EpisodeSeenService, diff --git a/frontend/src/app/core/services/entry.service.ts b/frontend/src/app/core/services/entry.service.ts index 810c740..37f86b1 100644 --- a/frontend/src/app/core/services/entry.service.ts +++ b/frontend/src/app/core/services/entry.service.ts @@ -65,7 +65,7 @@ export class EntryService { // update entry refrechEntryById(entryId: number) { return this.http.get( - `${this.backend_apiUrl}/${this.apiAction}/${entryId}/refrech` + `${this.backend_apiUrl}/${this.apiAction}/${entryId}/refresh` ); } diff --git a/frontend/src/app/core/services/userCollection.service.ts b/frontend/src/app/core/services/userCollection.service.ts index 5647c77..c21cbf6 100644 --- a/frontend/src/app/core/services/userCollection.service.ts +++ b/frontend/src/app/core/services/userCollection.service.ts @@ -9,9 +9,9 @@ import { environment } from '../../../environments/environment.prod'; @Injectable({ providedIn: 'root', }) -export class UserCollectionService { +export class CollectionService { private backend_apiUrl = environment.API_URL; - private apiAction = 'user-collections'; + private apiAction = 'collections'; constructor(private http: HttpClient) {} @@ -23,68 +23,84 @@ export class UserCollectionService { } // get a list by id - getCollection(userCollectionId: string) { + getCollection(collectionId: string) { return this.http.get( - `${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}` + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}` ); } // Create a new list - createCollection(userCollection: UserCollection): Observable { + createCollection(collection: UserCollection): Observable { return this.http.post( `${this.backend_apiUrl}/${this.apiAction}`, - userCollection + collection ); } // * PUT - update a collection updateCollection( - userCollectionId: number, + collectionId: number, formData: FormData ): Observable { return this.http.put( - `${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}`, + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}`, formData ); } + // * PUT - REFRESH COLLECTION + refreshCollection(collectionId: number): Observable { + return this.http.put( + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}/refresh`, + {} + ); + } + + // * PUT - GET COLLECTION PARTS + getCollectionParts(collectionId: number): Observable { + return this.http.put( + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}/parts`, + {} + ); + } + // Delete a list by ID - deleteCollection(userCollectionId: number): Observable { + deleteCollection(collectionId: number): Observable { return this.http.delete( - `${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}` + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}` ); } // Add an entry to a list addEntryToCollection( - userCollectionId: number, + collectionId: number, entryId: number ): Observable { return this.http.post( - `${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`, + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}/entries/${entryId}`, {} ); } // Update an entry's order in a list updateEntryOrder( - userCollectionId: string, + collectionId: string, entryId: number, newOrder: number ): Observable { return this.http.patch( - `${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`, + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}/entries/${entryId}`, { newOrder: newOrder } ); } // Remove an entry from a list removeEntryFromCollection( - userCollectionId: string, + collectionId: string, entryId: number ): Observable { return this.http.delete( - `${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}` + `${this.backend_apiUrl}/${this.apiAction}/${collectionId}/entries/${entryId}` ); } } diff --git a/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.html b/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.html index 140baf8..fd316ba 100644 --- a/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.html +++ b/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.html @@ -4,7 +4,7 @@
-
+
@@ -32,7 +32,19 @@
- + +
+ +
+ + +
+ +
+ +
diff --git a/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.ts b/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.ts index 10187f4..7fea237 100644 --- a/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.ts +++ b/frontend/src/app/features/collections/user-collection-info/collection-edit-modal/collection-edit-modal.component.ts @@ -35,6 +35,12 @@ import { export class CollectionEditModalComponent implements OnInit { form!: FormGroup; + posterFile: File | null = null; + backdropFile: File | null = null; + + posterPreview: string | ArrayBuffer | null = ''; + backdropPreview: string | ArrayBuffer | null = ''; + constructor( public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: any, @@ -48,20 +54,43 @@ export class CollectionEditModalComponent implements OnInit { description: [this.data.description], userRating: [this.data.userRating], poster: [null], + backdrop: [null], }); } - onFileChange(event: any) { - const file = event.target.files[0]; - this.form.patchValue({ poster: file }); - this.form.get('poster')?.updateValueAndValidity(); + onFileChange(event: Event, type: string) { + const file = (event.target as HTMLInputElement).files?.[0]; + if (!file) return; + + const reader = new FileReader(); + reader.onload = () => { + if (type == 'poster') { + this.posterFile = file; + // this.form.patchValue({ poster: file }); + // this.form.get('poster')?.updateValueAndValidity(); + this.posterPreview = reader.result; + } else if (type == 'backdrop') { + this.backdropFile = file; + // this.form.patchValue({ backdrop: file }); + // this.form.get('backdrop')?.updateValueAndValidity(); + this.backdropPreview = reader.result; + } + console.log(this.form); + }; + + reader.readAsDataURL(file); } + getCollectionPoster() {} + onConfirm(): void { if (this.form.invalid) return this.form.markAllAsTouched(); let formData = new FormData(); + if (this.posterFile) formData.append('poster', this.posterFile); + if (this.backdropFile) formData.append('backdrop', this.backdropFile); + formData.append('name', this.form.get('name')?.value.toString().trim()); formData.append('description', this.form.get('description')?.value || ''); formData.append( @@ -70,12 +99,10 @@ export class CollectionEditModalComponent implements OnInit { ); // Check and append file if it exists - const posterFile = this.form.get('poster')?.value; - if (posterFile) { - formData.append('poster', posterFile); - } - - formData.append('is_poster_link', 'false'); + // const posterFile = this.form.get('poster')?.value; + // if (posterFile) { + // formData.append('poster', posterFile); + // } this.dialogRef.close({ formData: formData }); } diff --git a/frontend/src/app/features/collections/user-collection-info/collection-entry-table/collection-entry-table.component.ts b/frontend/src/app/features/collections/user-collection-info/collection-entry-table/collection-entry-table.component.ts index 35d32b0..8acd1b0 100644 --- a/frontend/src/app/features/collections/user-collection-info/collection-entry-table/collection-entry-table.component.ts +++ b/frontend/src/app/features/collections/user-collection-info/collection-entry-table/collection-entry-table.component.ts @@ -1,6 +1,6 @@ import { Component, Input } from '@angular/core'; import { Entry } from '../../../../shared/models/entry.model'; -import { UserCollectionService } from '../../../../core/services/userCollection.service'; +import { CollectionService } from '../../../../core/services/userCollection.service'; import { CdkDragDrop, CdkDragEnd, @@ -30,7 +30,7 @@ export class CollectionEntryTableComponent { @Input() entries: Entry[] = []; @Input() collectionId: string = ''; - constructor(private userCollectionService: UserCollectionService) {} + constructor(private userCollectionService: CollectionService) {} refrechEventReceiver() { console.log('event recieved'); diff --git a/frontend/src/app/features/collections/user-collection-info/collection-table-line/collection-table-line.component.ts b/frontend/src/app/features/collections/user-collection-info/collection-table-line/collection-table-line.component.ts index 1e3d0c0..1f7d4d0 100644 --- a/frontend/src/app/features/collections/user-collection-info/collection-table-line/collection-table-line.component.ts +++ b/frontend/src/app/features/collections/user-collection-info/collection-table-line/collection-table-line.component.ts @@ -10,7 +10,7 @@ import { MatDialog } from '@angular/material/dialog'; import { LibraryService } from '../../../../core/services/library.service'; import { Entry } from '../../../../shared/models/entry.model'; import { trigger, transition, style, animate } from '@angular/animations'; -import { UserCollectionService } from '../../../../core/services/userCollection.service'; +import { CollectionService } from '../../../../core/services/userCollection.service'; import { Router } from '@angular/router'; import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component'; import { environment } from '../../../../../environments/environment.prod'; @@ -37,7 +37,7 @@ export class CollectionTableLineComponent implements OnInit { constructor( private libraryService: LibraryService, - private userCollectionService: UserCollectionService, + private userCollectionService: CollectionService, public dialog: MatDialog, private router: Router ) {} diff --git a/frontend/src/app/features/collections/user-collection-info/userCollection-grid-card/userCollection-grid-card.component.ts b/frontend/src/app/features/collections/user-collection-info/userCollection-grid-card/userCollection-grid-card.component.ts index b4f66ae..63e78a9 100644 --- a/frontend/src/app/features/collections/user-collection-info/userCollection-grid-card/userCollection-grid-card.component.ts +++ b/frontend/src/app/features/collections/user-collection-info/userCollection-grid-card/userCollection-grid-card.component.ts @@ -2,7 +2,7 @@ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Entry } from '../../../../shared/models/entry.model'; import { trigger, transition, style, animate } from '@angular/animations'; -import { UserCollectionService } from '../../../../core/services/userCollection.service'; +import { CollectionService } from '../../../../core/services/userCollection.service'; import { Router } from '@angular/router'; import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component'; import { environment } from '../../../../../environments/environment.prod'; @@ -27,7 +27,7 @@ export class UserCollectionGridCardComponent implements OnInit { @Output() refrechEvent = new EventEmitter(); constructor( - private userCollectionService: UserCollectionService, + private userCollectionService: CollectionService, public dialog: MatDialog, private router: Router ) {} diff --git a/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.html b/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.html index 691360b..acef434 100644 --- a/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.html +++ b/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.html @@ -29,7 +29,21 @@
  • Switch View
  • Delete
  • Share (as image)
  • -
  • View in TMDB
  • +
  • + Refresh + Information + +
  • +
  • + Get All + Parts + +
  • +
  • + View in + TMDB + +
  • diff --git a/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.ts b/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.ts index 2d008d0..3e27838 100644 --- a/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.ts +++ b/frontend/src/app/features/collections/user-collection-info/userCollection-info-page/userCollection-info-page.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; -import { UserCollectionService } from '../../../../core/services/userCollection.service'; +import { CollectionService } from '../../../../core/services/userCollection.service'; import { UserCollection } from '../../../../shared/models/userCollection.model'; import { DatePipe } from '@angular/common'; import { CollectionEntry } from '../../../../shared/models/dtos/collection-entry.dto'; @@ -25,7 +25,7 @@ export class UserCollectionInfoPageComponent implements OnInit { constructor( private route: ActivatedRoute, - private userCollectionService: UserCollectionService, + private userCollectionService: CollectionService, private screenshotService: ScreenshotService, private datePipe: DatePipe, public dialog: MatDialog, @@ -36,8 +36,8 @@ export class UserCollectionInfoPageComponent implements OnInit { const id = this.route.snapshot.paramMap.get('id'); if (id == null) return; // todo redirect if no id is provided - this.userCollectionService.getCollection(id.toString()).subscribe( - (data) => { + this.userCollectionService.getCollection(id.toString()).subscribe({ + next: (data) => { this.collection = data as unknown as UserCollection; this.collection.entries = this.collection.entries as CollectionEntry[]; @@ -48,10 +48,10 @@ export class UserCollectionInfoPageComponent implements OnInit { // this.collection // ); }, - (error) => { + error: (error) => { console.error('Error occurred:', error); - } - ); + }, + }); } getListId() { @@ -111,6 +111,7 @@ export class UserCollectionInfoPageComponent implements OnInit { description: this.collection.description, userRating: this.collection.userRating || 0, poster: this.collection.posterPath, + backdrop: this.collection.backdropPath, }, }); @@ -208,6 +209,47 @@ export class UserCollectionInfoPageComponent implements OnInit { }; } + refreshCollection() { + this.userCollectionService.refreshCollection(this.collection.id).subscribe({ + next: (data) => { + this.collection = data as unknown as UserCollection; + this.collection.entries = this.collection.entries as CollectionEntry[]; + + this.createdAt = this.getCreatedDate()?.toString() || ''; + this.updatedAt = this.getUpdatedAt()?.toString() || ''; + // console.log( + // `Collection "${this.collection.name}" received:`, + // this.collection + // ); + }, + error: (error) => { + console.error('Error occurred:', error); + }, + }); + } + + getCollectionParts() { + this.userCollectionService + .getCollectionParts(this.collection.id) + .subscribe({ + next: (data) => { + this.collection = data as unknown as UserCollection; + this.collection.entries = this.collection + .entries as CollectionEntry[]; + + this.createdAt = this.getCreatedDate()?.toString() || ''; + this.updatedAt = this.getUpdatedAt()?.toString() || ''; + // console.log( + // `Collection "${this.collection.name}" received:`, + // this.collection + // ); + }, + error: (error) => { + console.error('Error occurred:', error); + }, + }); + } + redirectToTMDB() { window.open( `https://www.themoviedb.org/collection/${this.collection.tmdbId}`, diff --git a/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.html b/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.html index 437fc68..0bd848a 100644 --- a/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.html +++ b/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.html @@ -1,8 +1,9 @@
    - List poster + Collection poster
    -
    {{list.name}}
    +
    {{collection.name}}
    diff --git a/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.ts b/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.ts index 85a2c49..f474982 100644 --- a/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.ts +++ b/frontend/src/app/features/collections/user-collections/userCollection-list-item/userCollections-list-item.component.ts @@ -1,6 +1,6 @@ import { Component, Input } from '@angular/core'; import { UserCollection } from '../../../../shared/models/userCollection.model'; -import { UserCollectionService } from '../../../../core/services/userCollection.service'; +import { CollectionService } from '../../../../core/services/userCollection.service'; import { Router } from '@angular/router'; import { trigger, transition, style, animate } from '@angular/animations'; import { environment } from '../../../../../environments/environment.prod'; @@ -25,97 +25,103 @@ import { Entry } from '../../../../shared/models/entry.model'; ], }) export class UserCollectionsListItemComponent { - @Input() list!: UserCollection; + @Input() collection!: UserCollection; - constructor( - private listService: UserCollectionService, - private router: Router - ) {} + constructor(private listService: CollectionService, private router: Router) {} - getCollectionPosterPath() { - if (this.list.isLocal) { - if (this.list.posterPath == null) - return 'assets/images/default/default-poster.png'; + // getCollectionPosterPath() { + // console.log(this.collection.medias); + // if (this.collection.medias.length != 0) { + // const selectedPosters = this.collection.medias.filter( + // (m) => m.type == 'poster' && m.isSelected + // ); + // let selectedPoster; + // if (selectedPosters.length != 0) { + // selectedPoster = selectedPosters[0].path; + // } else { + // selectedPoster = this.collection.medias[0].path; + // } - // * use the collection custom poster - return ( - environment.API_URL + - `/media/collections/posters/preview/` + - this.list.posterPath - ); - } else { - // * use the poster of the first entry in the collection if its no empty - if (this.list.entries.length != 0) { - return this.getEntryPosterPath(this.list.entries[0]); - } + // return ( + // environment.API_URL + + // `/media/collections/posters/preview/${selectedPoster}` + // ); + // } else if (this.collection.entries.length != 0) { + // // * use the poster of the first entry in the collection + // // * if the collection is empty + // return this.getEntryPosterPath(this.collection.entries[0]); + // } else if (this.collection.posterPath) { + // // * use first remote tmdb poster + // // * if collection has none and has no entry + // return `https://www.themoviedb.org/w1280/${this.collection.posterPath}`; + // } else { + // // * use default poster + // // * if collection has totaly no poster + // return 'assets/images/default/default-poster.png'; + // } + // } - return `https://www.themoviedb.org/w1280/${this.list.posterPath}`; - // * if the collection is empty - return 'assets/images/default/default-poster.png'; - } - } + // getCollectionBakcgroundPath() { + // return `https://www.themoviedb.org/w1280/${this.collection.backdropPath}`; - getCollectionBakcgroundPath() { - return `https://www.themoviedb.org/w1280/${this.list.backdropPath}`; + // // if (this.list.isLocal) { + // // if (this.list.backdropPath == null) + // // return 'assets/images/default/default-poster.png'; - // if (this.list.isLocal) { - // if (this.list.backdropPath == null) - // return 'assets/images/default/default-poster.png'; + // // // * use the collection custom poster + // // return ( + // // environment.API_URL + + // // `/media/collections/posters/preview/` + + // // this.list.posterPath + // // ); + // // } else { + // // // * use the poster of the first entry in the collection if its no empty + // // if (this.list.entries.length != 0) { + // // return this.getEntryPosterPath(this.list.entries[0]); + // // } - // // * use the collection custom poster - // return ( - // environment.API_URL + - // `/media/collections/posters/preview/` + - // this.list.posterPath - // ); - // } else { - // // * use the poster of the first entry in the collection if its no empty - // if (this.list.entries.length != 0) { - // return this.getEntryPosterPath(this.list.entries[0]); - // } + // // return `https://www.themoviedb.org/w1280/${this.list.backdropPath}`; + // // // * if the collection is empty + // // return 'assets/images/default/default-poster.png'; + // // } + // } - // return `https://www.themoviedb.org/w1280/${this.list.backdropPath}`; - // // * if the collection is empty - // return 'assets/images/default/default-poster.png'; - // } - } + // getEntryPosterPath(entry: Entry) { + // // * Is in library: use a local poster + // if (entry.medias) { + // const selectedPosters = entry.medias.filter( + // (m) => m.type == 'poster' && m.isSelected + // ); - getEntryPosterPath(entry: Entry) { - // * Is in library: use a local poster - if (entry.medias) { - const selectedPosters = entry.medias.filter( - (m) => m.type == 'poster' && m.isSelected - ); + // if ( + // selectedPosters.length && + // selectedPosters[0] && + // selectedPosters[0].path + // ) { + // const name = selectedPosters[0].path; + // return environment.API_URL + `/media/entries/posters/preview/${name}`; + // } + // } - if ( - selectedPosters.length && - selectedPosters[0] && - selectedPosters[0].path - ) { - const name = selectedPosters[0].path; - return environment.API_URL + `/media/entries/posters/preview/${name}`; - } - } + // // * No local poster available, Use TMDB poster + // if (entry.poster_path) + // return `https://image.tmdb.org/t/p/w300` + entry.poster_path; - // * No local poster available, Use TMDB poster - if (entry.poster_path) - return `https://image.tmdb.org/t/p/w300` + entry.poster_path; - - // * No poster found, use default poster image as a last stand - return 'assets/images/default/default-poster.png'; - } + // // * No poster found, use default poster image as a last stand + // return 'assets/images/default/default-poster.png'; + // } getCreatedDate(): string { - if (this.list.createdAt == null) return ''; + if (this.collection.createdAt == null) return ''; - return this.list.createdAt.toString(); + return this.collection.createdAt.toString(); } redirectTo(): void { - this.router.navigate([`/collections/${this.list.id}`]); + this.router.navigate([`/collections/${this.collection.id}`]); } deleteList() { - this.listService.deleteCollection(this.list.id); + this.listService.deleteCollection(this.collection.id); } } diff --git a/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.html b/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.html index cf929dd..f297302 100644 --- a/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.html +++ b/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.html @@ -46,7 +46,7 @@
    -
    diff --git a/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.ts b/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.ts index 8279069..5628c96 100644 --- a/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.ts +++ b/frontend/src/app/features/collections/user-collections/userCollections-page/userCollections-page.component.ts @@ -1,7 +1,7 @@ import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { UserCollection } from '../../../../shared/models/userCollection.model'; -import { UserCollectionService } from '../../../../core/services/userCollection.service'; +import { CollectionService } from '../../../../core/services/userCollection.service'; import { animate, state, @@ -9,6 +9,8 @@ import { transition, trigger, } from '@angular/animations'; +import { Entry } from '../../../../shared/models/entry.model'; +import { environment } from '../../../../../environments/environment.prod'; @Component({ selector: 'app-userCollections-page', @@ -32,7 +34,7 @@ export class UserCollectionsPageComponent implements OnInit { lockActions: boolean = false; - constructor(private collectionsService: UserCollectionService) {} + constructor(private collectionsService: CollectionService) {} ngOnInit() { this.getCollections(); @@ -43,9 +45,19 @@ export class UserCollectionsPageComponent implements OnInit { getCollections() { this.collectionsService.getCollections().subscribe({ - next: (l) => { + next: (result) => { // console.log(`Loaded ${l.length} lists.`); - this.collections = l; + this.collections = result.map((c) => { + c.mediasCount = c.medias.length; + c.entriesCount = c.entries.length; + + c.selectedPoster = this.getCollectionPosterPath(c); + + c.medias = []; + c.entries = []; + + return c; + }); this.collectionsToShow = this.collections; this.applyFilter(); }, @@ -101,6 +113,69 @@ export class UserCollectionsPageComponent implements OnInit { } doShowCreate() { - return this.searchControl.value && !this.collections.some(c => c.name.trim().toLowerCase() == this.searchControl.value?.trim().toLowerCase()); + return ( + this.searchControl.value && + !this.collections.some( + (c) => + c.name.trim().toLowerCase() == + this.searchControl.value?.trim().toLowerCase() + ) + ); + } + + getCollectionPosterPath(collection: UserCollection) { + if (collection.medias && collection.medias.length != 0) { + const selectedPosters = collection.medias.filter( + (m) => m.type == 'poster' && m.isSelected + ); + let selectedPoster; + if (selectedPosters.length != 0) { + selectedPoster = selectedPosters[0].path; + } else { + selectedPoster = collection.medias[0].path; + } + + return ( + environment.API_URL + + `/media/collections/posters/preview/${selectedPoster}` + ); + } else if (collection.entries && collection.entries.length != 0) { + // * use the poster of the first entry in the collection + // * if the collection is empty + return this.getEntryPosterPath(collection.entries[0]); + } else if (collection.posterPath) { + // * use first remote tmdb poster + // * if collection has none and has no entry + return `https://www.themoviedb.org/w420/${collection.posterPath}`; + } else { + // * use default poster + // * if collection has totaly no poster + return 'assets/images/default/default-poster.png'; + } + } + + getCollectionBakcgroundPath(collection: UserCollection) { + return `https://www.themoviedb.org/w1280/${collection.backdropPath}`; + } + + getEntryPosterPath(entry: Entry) { + // * Is in library: use a local poster + if (entry.medias) { + const selectedPosters = entry.medias.filter( + (m) => m.type == 'poster' && m.isSelected + ); + + if (selectedPosters.length != 0) { + const name = selectedPosters[0].path; + return environment.API_URL + `/media/entries/posters/preview/${name}`; + } + } + + // * No local poster available, Use TMDB poster + if (entry.poster_path) + return `https://image.tmdb.org/t/p/w300` + entry.poster_path; + + // * No poster found, use default poster image as a last stand + return 'assets/images/default/default-poster.png'; } } diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.css b/frontend/src/app/features/entry/entry-page/entry-page.component.css index d366943..1024839 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.css +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.css @@ -31,11 +31,9 @@ .content-wrapper { color: #212529; - background: linear-gradient( - to bottom, - rgba(255, 255, 255, 0.461) 10%, - #eff1f3 100% - ); + background: linear-gradient(to bottom, + rgba(255, 255, 255, 0.461) 10%, + #eff1f3 100%); backdrop-filter: blur(10px); padding: 20px; @@ -46,11 +44,9 @@ [data-bs-theme="dark"] .content-wrapper { color: #a7acb1; - background: linear-gradient( - to bottom, - rgba(33, 37, 41, 0.7) 50%, - #181c1f 100% - ); + background: linear-gradient(to bottom, + rgba(33, 37, 41, 0.7) 50%, + #181c1f 100%); background-color: rgba(33, 37, 41, 0.7); border: 1px solid #181c1f; @@ -181,3 +177,17 @@ background-color: transparent; border-radius: 0; } + + +/* ! collection */ +.card-img-overlay:hover h5 { + color: var(--shz-blue-default) !important; +} + +.card-img-overlay { + cursor: pointer; +} + +.card-img-overlay img { + height: 100%; +} \ No newline at end of file diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.html b/frontend/src/app/features/entry/entry-page/entry-page.component.html index d474494..9ea8067 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.html +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.html @@ -219,6 +219,12 @@

    Watch History

    +
    @@ -280,6 +286,33 @@
    +
    +
    +

    Belong to Collection(s)

    + +
    + +
    + +
    +
    +
    +
    +
    {{ collection.name }}
    +
    + {{ collection.name }} +
    +
    +
    +
    +
    +
    diff --git a/frontend/src/app/features/entry/entry-page/entry-page.component.ts b/frontend/src/app/features/entry/entry-page/entry-page.component.ts index f9f906e..7126c42 100644 --- a/frontend/src/app/features/entry/entry-page/entry-page.component.ts +++ b/frontend/src/app/features/entry/entry-page/entry-page.component.ts @@ -22,6 +22,7 @@ import { EntrySeen } from '../../../shared/models/entrySeen.model'; import { EpisodeSeenModalComponent } from '../../../shared/components/modals/episode-seen-modal/episode-seen-modal.component'; import { MediaModalComponent } from '../media-modal/media-modal.component'; import { environment } from '../../../../environments/environment.prod'; +import { UserCollection } from '../../../shared/models/userCollection.model'; @Component({ selector: 'app-entry-page', @@ -76,6 +77,14 @@ export class EntryPageComponent implements OnInit { this.entry = data['entry'] as Entry; this.entry.isInLibrary = true; + this.entry.collections = this.entry.collections.map((c) => { + c.mediasCount = c.medias.length; + c.selectedBackdrop = this.getCollectionBackdropPath(c); + + c.medias = []; + return c; + }); + if (this.entry.is_tvseries) { // ? sorting seasons this.entry.seasons = this.entry.seasons.sort((a, b) => { @@ -316,6 +325,50 @@ export class EntryPageComponent implements OnInit { } } + getCollectionBackdropPath(collection: UserCollection) { + console.log(`collection media:`, collection.medias); + if (collection.medias && collection.medias.length != 0) { + const backdrops = collection.medias.filter((m) => m.type == 'backdrop'); + if (backdrops.length != 0) { + const selectedBackdrops = backdrops.filter( + (m) => m.type == 'backdrop' && m.isSelected + ); + + console.log(selectedBackdrops); + let selectedBackdrop; + if (selectedBackdrops.length != 0) { + selectedBackdrop = selectedBackdrops[0].path; + } else { + selectedBackdrop = backdrops[0].path; + } + + return ( + environment.API_URL + + `/media/collections/backdrops/preview/${selectedBackdrop}` + ); + } + } + + // if (collection.entries && collection.entries.length != 0) { + // // * use the poster of the first entry in the collection + // // * if the collection is empty + // return this.getEntryBackdropPath(collection.entries[0]); + // } else + if (collection.backdropPath) { + // * use first remote tmdb poster + // * if collection has none and has no entry + return `https://image.tmdb.org/t/p/w1280/${collection.backdropPath}`; + } else { + // * use default poster + // * if collection has totaly no poster + return 'assets/images/default/default-backdrop.png'; + } + } + + getEntryBackdropPath(entry: Entry) { + return ''; + } + refrechEntry() { this.lockActions = true; this.entryService.refrechEntryById(this.entry.id).subscribe({ @@ -417,7 +470,7 @@ export class EntryPageComponent implements OnInit { addEpisodeSeen() { if (!this.entry) return; - this.seenHistory[0] + this.seenHistory[0]; const dialogRef = this.dialog.open(EpisodeSeenModalComponent, { width: '360px', diff --git a/frontend/src/app/features/media/media-page/media-page.component.html b/frontend/src/app/features/media/media-page/media-page.component.html index 4b6b66c..8ae22e8 100644 --- a/frontend/src/app/features/media/media-page/media-page.component.html +++ b/frontend/src/app/features/media/media-page/media-page.component.html @@ -38,7 +38,7 @@
    - Media Image + Media Image