Major rework of media handelling, and collections
This commit is contained in:
1 parent
b42e055691
commit
f7cb2bed53
37 files changed
+1086
-377
No files matched your search
+2
-2
@@ -81,8 +81,8 @@
|
||||
},
|
||||
{
|
||||
"type": "anyComponentStyle",
|
||||
"maximumWarning": "2kb",
|
||||
"maximumError": "4kb"
|
||||
"maximumWarning": "5000kb",
|
||||
"maximumError": "5mb"
|
||||
}
|
||||
],
|
||||
"outputHashing": "all"
|
||||
|
||||
+30
-6
@@ -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', });
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.');
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,39 +13,40 @@ 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: [{
|
||||
const collectionId = req.params.id;
|
||||
|
||||
const collection = await Collection.findByPk(collectionId, {
|
||||
include: [
|
||||
{
|
||||
model: Entry,
|
||||
as: 'entries',
|
||||
include: [
|
||||
@@ -54,12 +60,14 @@ router.get('/:id', async (req, res) => {
|
||||
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,69 +83,87 @@ 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
|
||||
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);
|
||||
}
|
||||
|
||||
const updated = await UserCollection.update(updateData, {
|
||||
where: { id: userCollectionId }
|
||||
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);
|
||||
});
|
||||
|
||||
if (!updated[0]) {
|
||||
return res.status(404).json({ message: 'UserCollection not found' });
|
||||
await Media.create({
|
||||
mediaable: 'collection',
|
||||
mediaableId: collectionId,
|
||||
type: 'poster',
|
||||
path: posterPath,
|
||||
isLocal: true,
|
||||
isSelected: true,
|
||||
isCustom: true
|
||||
})
|
||||
}
|
||||
|
||||
if (updated) {
|
||||
const updatedUserCollection = await UserCollection.findByPk(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',
|
||||
@@ -152,13 +178,61 @@ router.put('/:id', upload.single('poster'), async (req, res) => {
|
||||
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
|
||||
});
|
||||
|
||||
res.status(200).json(updatedUserCollection);
|
||||
if (!oldCollection)
|
||||
res.status(404).json({ message: 'Collection not found' });
|
||||
|
||||
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: 'UserCollection not found' });
|
||||
res.status(404).json({ message: 'Collection not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`UserCollection update (put) error: `, error)
|
||||
@@ -166,10 +240,56 @@ router.put('/:id', upload.single('poster'), async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// * DELETE - A UserCollection
|
||||
router.delete('/:id', async (req, res) => {
|
||||
// * PUT - GET COLLECTION PARTS
|
||||
collectionRouter.put('/:id/parts', async (req, res) => {
|
||||
try {
|
||||
const deleted = await UserCollection.destroy({ where: { id: req.params.id } });
|
||||
const collectionId = req.params.id;
|
||||
|
||||
await getCollectionParts(collectionId);
|
||||
|
||||
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 (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 });
|
||||
}
|
||||
});
|
||||
|
||||
// * DELETE - DELETE COLLECTION
|
||||
collectionRouter.delete('/:id', async (req, res) => {
|
||||
try {
|
||||
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;
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
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
|
||||
|
||||
// ? count media by type
|
||||
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;
|
||||
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(availableMedia[key]);
|
||||
if (availableMedia[key] == 0) mediaToGet.push(key);
|
||||
}
|
||||
|
||||
let downloadedImages;
|
||||
if (mediaToGet.length != 0) {
|
||||
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries, mediaToGet);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -65,7 +65,7 @@ export class EntryService {
|
||||
// update entry
|
||||
refrechEntryById(entryId: number) {
|
||||
return this.http.get<Entry>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${entryId}/refrech`
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${entryId}/refresh`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<UserCollection>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}`
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}`
|
||||
);
|
||||
}
|
||||
|
||||
// Create a new list
|
||||
createCollection(userCollection: UserCollection): Observable<UserCollection> {
|
||||
createCollection(collection: UserCollection): Observable<UserCollection> {
|
||||
return this.http.post<UserCollection>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}`,
|
||||
userCollection
|
||||
collection
|
||||
);
|
||||
}
|
||||
|
||||
// * PUT - update a collection
|
||||
updateCollection(
|
||||
userCollectionId: number,
|
||||
collectionId: number,
|
||||
formData: FormData
|
||||
): Observable<UserCollection> {
|
||||
return this.http.put<UserCollection>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}`,
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}`,
|
||||
formData
|
||||
);
|
||||
}
|
||||
|
||||
// * PUT - REFRESH COLLECTION
|
||||
refreshCollection(collectionId: number): Observable<UserCollection> {
|
||||
return this.http.put<UserCollection>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}/refresh`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
// * PUT - GET COLLECTION PARTS
|
||||
getCollectionParts(collectionId: number): Observable<UserCollection> {
|
||||
return this.http.put<UserCollection>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}/parts`,
|
||||
{}
|
||||
);
|
||||
}
|
||||
|
||||
// Delete a list by ID
|
||||
deleteCollection(userCollectionId: number): Observable<any> {
|
||||
deleteCollection(collectionId: number): Observable<any> {
|
||||
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<UserCollectionEntry> {
|
||||
return this.http.post<UserCollectionEntry>(
|
||||
`${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<any> {
|
||||
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<Entry> {
|
||||
return this.http.delete<Entry>(
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`
|
||||
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}/entries/${entryId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -32,7 +32,19 @@
|
||||
|
||||
<div class="col-md-12">
|
||||
<label class="form-label">Poster</label>
|
||||
<input type="file" class="form-control" id="image" (change)="onFileChange($event)">
|
||||
<input type="file" class="form-control" id="image" (change)="onFileChange($event, 'poster')" multiple>
|
||||
</div>
|
||||
|
||||
<div class="col-md-12">
|
||||
<label class="form-label">Backdrop</label>
|
||||
<input type="file" class="form-control" id="image" (change)="onFileChange($event, 'backdrop')">
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<img [src]="getCollectionPoster()" *ngIf="posterPreview == ''" style="max-height: 250px !important;"
|
||||
alt="Banner" class="img-fluid img-thumbnail banner-img" >
|
||||
<img [src]="posterPreview" *ngIf="posterPreview != ''" style="max-height: 250px !important;" alt="Banner"
|
||||
class="img-fluid img-thumbnail banner-img">
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
+37
-10
@@ -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<CollectionEditModalComponent>,
|
||||
@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 });
|
||||
}
|
||||
|
||||
+2
-2
@@ -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');
|
||||
|
||||
+2
-2
@@ -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
|
||||
) {}
|
||||
|
||||
+2
-2
@@ -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
|
||||
) {}
|
||||
|
||||
+15
-1
@@ -29,7 +29,21 @@
|
||||
<li><a class="dropdown-item" (click)="switchViewMode()">Switch View</a></li>
|
||||
<li><a class="dropdown-item" (click)="deleteCollection()">Delete</a></li>
|
||||
<li><a class="dropdown-item" (click)="shareScreenshot()">Share (as image)</a></li>
|
||||
<li><a class="dropdown-item" *ngIf="!this.collection.isUserCollection" (click)="redirectToTMDB()">View in TMDB</a></li>
|
||||
<li>
|
||||
<a class="dropdown-item" *ngIf="!collection.isUserCollection" (click)="refreshCollection()">Refresh
|
||||
Information
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" *ngIf="!collection.isUserCollection" (click)="getCollectionParts()">Get All
|
||||
Parts
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" *ngIf="!collection.isUserCollection" (click)="redirectToTMDB()">View in
|
||||
TMDB
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+49
-7
@@ -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}`,
|
||||
|
||||
+3
-2
@@ -1,8 +1,9 @@
|
||||
<div class="card-coat">
|
||||
<div class="d-flex flex-column align-items-center collection-card" @fadeInOut>
|
||||
<img id="poster" [src]="getCollectionPosterPath()" width="150" class="" alt="List poster" (click)="redirectTo()">
|
||||
<img id="poster" [src]="collection.selectedPoster" width="150" class="" alt="Collection poster"
|
||||
(click)="redirectTo()">
|
||||
<div class="list-item-1 mt-2 text-center">
|
||||
<h6 class="mb-0 list-title" (click)="redirectTo()">{{list.name}}</h6>
|
||||
<h6 class="mb-0 list-title" (click)="redirectTo()">{{collection.name}}</h6>
|
||||
<!-- <p class="mb-0">Created: {{getCreatedDate() | dateFormat}}</p> -->
|
||||
<!-- <p class="mb-0">Contains: {{list.userCollectionEntries.length}} title(s)</p> -->
|
||||
</div>
|
||||
|
||||
+77
-71
@@ -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 `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.list.backdropPath}`;
|
||||
|
||||
// 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
|
||||
// `/media/collections/posters/preview/${selectedPoster}`
|
||||
// );
|
||||
// } 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}`;
|
||||
// } 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';
|
||||
// }
|
||||
}
|
||||
// }
|
||||
|
||||
getEntryPosterPath(entry: Entry) {
|
||||
// * Is in library: use a local poster
|
||||
if (entry.medias) {
|
||||
const selectedPosters = entry.medias.filter(
|
||||
(m) => m.type == 'poster' && m.isSelected
|
||||
);
|
||||
// getCollectionBakcgroundPath() {
|
||||
// return `https://www.themoviedb.org/w1280/${this.collection.backdropPath}`;
|
||||
|
||||
if (
|
||||
selectedPosters.length &&
|
||||
selectedPosters[0] &&
|
||||
selectedPosters[0].path
|
||||
) {
|
||||
const name = selectedPosters[0].path;
|
||||
return environment.API_URL + `/media/entries/posters/preview/${name}`;
|
||||
}
|
||||
}
|
||||
// // if (this.list.isLocal) {
|
||||
// // if (this.list.backdropPath == null)
|
||||
// // return 'assets/images/default/default-poster.png';
|
||||
|
||||
// * No local poster available, Use TMDB poster
|
||||
if (entry.poster_path)
|
||||
return `https://image.tmdb.org/t/p/w300` + entry.poster_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]);
|
||||
// // }
|
||||
|
||||
// * No poster found, use default poster image as a last stand
|
||||
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
|
||||
// );
|
||||
|
||||
// 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 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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -46,7 +46,7 @@
|
||||
<div class="card-body p-0">
|
||||
|
||||
<div class="collections-container">
|
||||
<app-userCollections-list-item *ngFor="let list of collectionsToShow" [list]="list"
|
||||
<app-userCollections-list-item *ngFor="let collection of collectionsToShow" [collection]="collection"
|
||||
@animateDestroy></app-userCollections-list-item>
|
||||
</div>
|
||||
|
||||
|
||||
+80
-5
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -31,11 +31,9 @@
|
||||
|
||||
.content-wrapper {
|
||||
color: #212529;
|
||||
background: linear-gradient(
|
||||
to bottom,
|
||||
background: linear-gradient(to bottom,
|
||||
rgba(255, 255, 255, 0.461) 10%,
|
||||
#eff1f3 100%
|
||||
);
|
||||
#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,
|
||||
background: linear-gradient(to bottom,
|
||||
rgba(33, 37, 41, 0.7) 50%,
|
||||
#181c1f 100%
|
||||
);
|
||||
#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%;
|
||||
}
|
||||
@@ -219,6 +219,12 @@
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
<h3>Watch History</h3>
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-sm btn-filter bg-transparent" type="button" style="cursor: pointer;"
|
||||
(click)="addEpisodeSeen()">
|
||||
<i class="bi bi-check2"></i>
|
||||
</button>
|
||||
</div>
|
||||
<!-- <div class="dropdown">
|
||||
<button class="btn btn-sm btn-filter dropdown-toggle dropdown-toggle-nocaret bg-transparent" type="button"
|
||||
data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<i class="bi bi-three-dots"></i>
|
||||
@@ -226,7 +232,7 @@
|
||||
<ul class="dropdown-menu" style="cursor: pointer;">
|
||||
<li (click)="addEpisodeSeen()"><a class="dropdown-item">Add a watch date</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div> -->
|
||||
</div>
|
||||
|
||||
<div class="card-body p-3">
|
||||
@@ -280,6 +286,33 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row" *ngIf="this.entry.collections.length != 0">
|
||||
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||
<h3>Belong to Collection(s)</h3>
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-sm btn-filter bg-transparent" type="button" style="cursor: pointer;"
|
||||
(click)="showAddToListModal()">
|
||||
<i class="bi bi-collection"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-body p-3 pb-0">
|
||||
<!-- Iterate through each collection in the entry.collections array -->
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4" *ngFor="let collection of entry.collections">
|
||||
<div class="card h-100 mb-0 collection-card" [routerLink]="['/collections', collection.id]">
|
||||
<div class="card-img-overlay d-flex align-items-start justify-content-center"
|
||||
style="background-color: rgba(0, 0, 0, 0.5);">
|
||||
<h5 class="text-white">{{ collection.name }}</h5>
|
||||
</div>
|
||||
<img [src]="collection.selectedBackdrop" alt="{{ collection.name }}" class="card-img">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
<div class="row row-cols-4 row-cols-md-6 g-4">
|
||||
<div class="col" *ngFor="let media of filterMedia('poster')">
|
||||
<div class="card image-hover-container">
|
||||
<img [src]="getPath('posters' , media.path)" class="card-img-top" alt="Media Image">
|
||||
<img [src]="getPath('posters' , media)" class="card-img-top" alt="Media Image">
|
||||
<div class="image-hover-overlay">
|
||||
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
||||
<span class="material-symbols-outlined">delete</span>
|
||||
@@ -58,7 +58,7 @@
|
||||
<div class="row row-cols-2 row-cols-md-4 g-4">
|
||||
<div class="col" *ngFor="let media of filterMedia('backdrop')">
|
||||
<div class="card image-hover-container">
|
||||
<img [src]="getPath('backdrops', media.path)" class="card-img-top" alt="Media Image">
|
||||
<img [src]="getPath('backdrops', media)" class="card-img-top" alt="Media Image">
|
||||
<div class="image-hover-overlay">
|
||||
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
||||
<span class="material-symbols-outlined">delete</span>
|
||||
@@ -78,7 +78,7 @@
|
||||
<div class="row row-cols-1 row-cols-md-2 g-4">
|
||||
<div class="col" *ngFor="let media of filterMedia('logo')">
|
||||
<div class="card image-hover-container">
|
||||
<img [src]="getPath('logos', media.path)" class="card-img-top" alt="Media Image">
|
||||
<img [src]="getPath('logos', media)" class="card-img-top" alt="Media Image">
|
||||
<div class="image-hover-overlay">
|
||||
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
||||
<span class="material-symbols-outlined">delete</span>
|
||||
|
||||
@@ -21,6 +21,7 @@ export class MediaPageComponent implements OnInit {
|
||||
ngOnInit() {
|
||||
this.customMediaService.fetchCustomMedia().subscribe({
|
||||
next: (result) => {
|
||||
console.log(result);
|
||||
this.customMedia = result;
|
||||
console.log(result);
|
||||
},
|
||||
@@ -32,8 +33,11 @@ export class MediaPageComponent implements OnInit {
|
||||
return this.customMedia.filter((media) => media.type == type);
|
||||
}
|
||||
|
||||
getPath(type: string, fileName: string) {
|
||||
return `${environment.API_URL}/media/entries/${type}/preview/${fileName}`;
|
||||
getPath(type: string, media: Media) {
|
||||
let category = 'entries';
|
||||
if (media.mediaable == 'collection') category = 'collections';
|
||||
|
||||
return `${environment.API_URL}/media/${category}/${type}/preview/${media.path}`;
|
||||
}
|
||||
|
||||
setTab(tab: string) {
|
||||
@@ -71,7 +75,10 @@ export class MediaPageComponent implements OnInit {
|
||||
}
|
||||
|
||||
expandMedia(media: any) {
|
||||
const fullSizePath = `${environment.API_URL}/media/entries/${media.type}s/original/${media.path}`;
|
||||
let category = 'entries';
|
||||
if (media.mediaable == 'collection') category = 'collections';
|
||||
|
||||
const fullSizePath = `${environment.API_URL}/media/${category}/${media.type}s/original/${media.path}`;
|
||||
window.open(fullSizePath, '_blank');
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { Component, Inject, Input, OnInit, ViewChild } from '@angular/core';
|
||||
import { FormControl } from '@angular/forms';
|
||||
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
|
||||
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
||||
import { CollectionService } from '../../../../core/services/userCollection.service';
|
||||
import { NotificationPopupComponent } from '../../notification-popup/notification-popup.component';
|
||||
import { NotificationService } from '../../../services/notification.service';
|
||||
import { UserCollection } from '../../../models/userCollection.model';
|
||||
@@ -49,7 +49,7 @@ export class UserCollectionsModalComponent implements OnInit {
|
||||
constructor(
|
||||
public dialogRef: MatDialogRef<UserCollectionsModalComponent>,
|
||||
@Inject(MAT_DIALOG_DATA) public data: any,
|
||||
private listService: UserCollectionService,
|
||||
private listService: CollectionService,
|
||||
private notificationService: NotificationService
|
||||
) {}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { EntryRating } from './entryRating.model';
|
||||
import { EntrySeen } from './entrySeen.model';
|
||||
import { Media } from './media.model';
|
||||
import { Season } from './season.model';
|
||||
import { UserCollection } from './userCollection.model';
|
||||
|
||||
export interface Entry {
|
||||
id: number;
|
||||
@@ -11,6 +12,7 @@ export interface Entry {
|
||||
entryRating: EntryRating;
|
||||
entrySeen: EntrySeen[];
|
||||
seasons: Season[];
|
||||
collections: UserCollection[];
|
||||
|
||||
title: string;
|
||||
original_title: string;
|
||||
|
||||
@@ -4,6 +4,8 @@ export interface Media {
|
||||
id: number;
|
||||
|
||||
entry_id: number;
|
||||
mediaable: string;
|
||||
mediaableId: number;
|
||||
entry: Entry;
|
||||
|
||||
type: string;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CollectionEntry } from './dtos/collection-entry.dto';
|
||||
import { Media } from './media.model';
|
||||
import { UserCollectionEntry } from './userCollectionEntry.model';
|
||||
|
||||
export interface UserCollection {
|
||||
@@ -12,6 +13,7 @@ export interface UserCollection {
|
||||
isUserCollection: boolean;
|
||||
userRating: number;
|
||||
|
||||
medias: Media[];
|
||||
posterPath: string;
|
||||
backdropPath: string;
|
||||
isLocal: boolean;
|
||||
@@ -21,6 +23,12 @@ export interface UserCollection {
|
||||
changed: boolean;
|
||||
isChecked: boolean;
|
||||
|
||||
// * Processed fields
|
||||
mediasCount: number;
|
||||
entriesCount: number;
|
||||
selectedPoster: string;
|
||||
selectedBackdrop: string;
|
||||
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Reference in new issue
Block a user