Major rework of media handelling, and collections
This commit is contained in:
1 parent
b42e055691
commit
f7cb2bed53
37 files changed
+1120
-411
No files matched your search
+2
-2
@@ -81,8 +81,8 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "anyComponentStyle",
|
"type": "anyComponentStyle",
|
||||||
"maximumWarning": "2kb",
|
"maximumWarning": "5000kb",
|
||||||
"maximumError": "4kb"
|
"maximumError": "5mb"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"outputHashing": "all"
|
"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', });
|
// Entry.hasMany(Media, { foreignKey: 'entryId', as: 'medias', onDelete: 'CASCADE', });
|
||||||
// Media.belongsTo(Entry, { foreignKey: 'entryId', as: 'entry' });
|
// Media.belongsTo(Entry, { foreignKey: 'entryId', as: 'entry' });
|
||||||
|
|
||||||
// * ENTRY & MEDIA - ONE TO MANY
|
Media.belongsTo(Entry, {
|
||||||
Media.belongsTo(Entry, { foreignKey: 'mediaableId', as: 'entry', constraints: false, scope: { mediaable: 'entry' } });
|
foreignKey: 'mediaableId',
|
||||||
Media.belongsTo(Collection, { foreignKey: 'mediaableId', as: 'collection', constraints: false, scope: { mediaable: 'collection' } });
|
as: 'entry',
|
||||||
|
constraints: false,
|
||||||
|
where: {
|
||||||
|
mediaable: 'entry'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// * ENTRY & COLLECTION - ONE TO MANY
|
Media.belongsTo(Collection, {
|
||||||
Entry.hasMany(Media, { foreignKey: 'mediaableId', constraints: false, as: 'medias', scope: { mediaable: 'entry' } });
|
foreignKey: 'mediaableId',
|
||||||
Collection.hasMany(Media, { foreignKey: 'mediaableId', constraints: false, as: 'medias', scope: { mediaable: 'collection' } });
|
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 & SEASON - ONE TO MANY
|
||||||
Entry.hasMany(Season, { foreignKey: 'entry_id', as: 'seasons', onDelete: 'CASCADE', });
|
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 EntryId = require('../models/EntryId')
|
||||||
const EntryRating = require('../models/EntryRating')
|
const EntryRating = require('../models/EntryRating')
|
||||||
const EntrySeen = require('../models/EntrySeen');
|
const EntrySeen = require('../models/EntrySeen');
|
||||||
const UserCollection = require('../models/UserCollection');
|
const UserCollection = require('../models/Collection');
|
||||||
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
||||||
const Season = require('../models/Season');
|
const Season = require('../models/Season');
|
||||||
const Episode = require('../models/Episode');
|
const Episode = require('../models/Episode');
|
||||||
@@ -92,14 +92,14 @@ UserCollectionEntry.afterDestroy(async (instance, options) => {
|
|||||||
|
|
||||||
// ? updating collection poster
|
// ? updating collection poster
|
||||||
// ? remove the poster if the collection is empty now
|
// ? remove the poster if the collection is empty now
|
||||||
if (collectionsEntries.length == 0) {
|
// if (collectionsEntries.length == 0) {
|
||||||
updates.poster = null;
|
// updates.poster = null;
|
||||||
} else {
|
// } else {
|
||||||
// ? replace poster it belonged to the removed entry
|
// // ? replace poster it belonged to the removed entry
|
||||||
// if (userCollection.poster_path == entry.poster_path) {
|
// // if (userCollection.poster_path == entry.poster_path) {
|
||||||
// updates.poster_path = collectionsEntries[0].entry.poster_path;
|
// // updates.poster_path = collectionsEntries[0].entry.poster_path;
|
||||||
// }
|
// // }
|
||||||
}
|
// }
|
||||||
|
|
||||||
// ? updating order, only if the removed entry isn't placed at the end
|
// ? updating order, only if the removed entry isn't placed at the end
|
||||||
let order = instance.order;
|
let order = instance.order;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const EntrySeen = require('../models/EntrySeen');
|
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require('../models/Entry');
|
||||||
const Media = require('../models/Media');
|
const Media = require('../models/Media');
|
||||||
|
const Collection = require('../models/Collection');
|
||||||
|
|
||||||
const customMediaRouter = express.Router();
|
const customMediaRouter = express.Router();
|
||||||
|
|
||||||
@@ -11,12 +11,21 @@ customMediaRouter.get('/', async (req, res) => {
|
|||||||
|
|
||||||
const allCustomMedia = await Media.findAll({
|
const allCustomMedia = await Media.findAll({
|
||||||
where: {
|
where: {
|
||||||
isCustom: true
|
isCustom: true,
|
||||||
},
|
},
|
||||||
include: [
|
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);
|
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 { saveEntry, refrechEntry, SyncSeriesData } = require('../services/models-services/entryService');
|
||||||
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService');
|
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService');
|
||||||
const { entryPicturesUpload } = require('../services/mutlerStorageLocations');
|
const { entryPicturesUpload } = require('../services/mutlerStorageLocations');
|
||||||
const { generatePreview } = require('../services/mediaService');
|
const { generatePreview, doGeneratePreview } = require('../services/mediaService');
|
||||||
|
|
||||||
const { Sequelize } = require('sequelize');
|
const { Sequelize } = require('sequelize');
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require('../models/Entry');
|
||||||
@@ -18,6 +18,8 @@ const Season = require('../models/Season');
|
|||||||
const Media = require('../models/Media');
|
const Media = require('../models/Media');
|
||||||
const Episode = require('../models/Episode');
|
const Episode = require('../models/Episode');
|
||||||
const UserCollection = require('../models/Collection');
|
const UserCollection = require('../models/Collection');
|
||||||
|
const { upsertOfficialCollection } = require('../services/models-services/collectionService');
|
||||||
|
const { logToFile } = require('../services/logService');
|
||||||
|
|
||||||
// ! /entries
|
// ! /entries
|
||||||
// * GET - ALL ENTRIES
|
// * GET - ALL ENTRIES
|
||||||
@@ -77,7 +79,12 @@ entryRouter.get('/:id', async (req, res) => {
|
|||||||
{ model: EntrySeen, as: 'entrySeen' },
|
{ model: EntrySeen, as: 'entrySeen' },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: 'seasons' },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: 'medias' },
|
||||||
{ model: UserCollection, as: 'collections' },
|
{
|
||||||
|
model: UserCollection, as: 'collections',
|
||||||
|
include: [
|
||||||
|
{ model: Media, as: 'medias' }
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: 'genres',
|
||||||
@@ -155,37 +162,7 @@ entryRouter.post('/', async (req, res) => {
|
|||||||
const entry = await saveEntry(entryData);
|
const entry = await saveEntry(entryData);
|
||||||
|
|
||||||
if (entryData.belongs_to_collection) {
|
if (entryData.belongs_to_collection) {
|
||||||
let collectionData = entryData.belongs_to_collection;
|
upsertOfficialCollection(entryData.belongs_to_collection.id);
|
||||||
|
|
||||||
const [oldCollection, createdCollection] = await UserCollection.findOrCreate({
|
|
||||||
where: { tmdbId: collectionData.id },
|
|
||||||
defaults: {
|
|
||||||
name: collectionData.name,
|
|
||||||
posterPath: collectionData.poster_path,
|
|
||||||
backdropPath: collectionData.backdrop_path,
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
let userCollection = oldCollection || createdCollection;
|
|
||||||
if (userCollection) {
|
|
||||||
collectionData = await fetchCollectionData(collectionData.id);
|
|
||||||
const partIds = collectionData.parts.map(part => part.id);
|
|
||||||
|
|
||||||
const entries = await Entry.findAll({
|
|
||||||
include: [{
|
|
||||||
model: EntryId,
|
|
||||||
as: 'entryId',
|
|
||||||
where: {
|
|
||||||
tmdb_id: {
|
|
||||||
[Sequelize.Op.in]: partIds
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}]
|
|
||||||
});
|
|
||||||
|
|
||||||
await userCollection.setEntries(entries);
|
|
||||||
await userCollection.update({ description: collectionData.overview })
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(201).json(entry);
|
res.status(201).json(entry);
|
||||||
@@ -285,7 +262,7 @@ entryRouter.put('/:id', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// * GET - REQUEST ENTRY REFRECH
|
// * GET - REQUEST ENTRY REFRECH
|
||||||
entryRouter.get('/:id/refrech', async (req, res, next) => {
|
entryRouter.get('/:id/refresh', async (req, res, next) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -382,15 +359,25 @@ entryRouter.post('/:id/media', upload, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ? generating low resolution preview
|
// ? generating low resolution preview
|
||||||
const fileNameWithoutExt = file.filename.split('.')[0];
|
// const fileNameWithoutExt = file.filename.split('.')[0];
|
||||||
const originalPath = file.path;
|
// const originalPath = file.path;
|
||||||
|
|
||||||
let previewWidth = 342; // ? poster preview width
|
// let previewWidth = 342; // ? poster preview width
|
||||||
if (fileType == 'backdrop') previewWidth = 780;
|
// if (fileType == 'backdrop') previewWidth = 780;
|
||||||
if (fileType == 'logo') previewWidth = 300;
|
// if (fileType == 'logo') previewWidth = 300;
|
||||||
|
|
||||||
const previewPath = path.join(file.destination, `${fileNameWithoutExt}_preview.jpg`);
|
// const previewPath = path.join(file.destination, `${fileNameWithoutExt}_preview.jpg`);
|
||||||
generatePreview(originalPath, previewPath, previewWidth);
|
// generatePreview(originalPath, previewPath, previewWidth);
|
||||||
|
doGeneratePreview('entries', fileType + 's', file.filename).then((result) => {
|
||||||
|
const stream = fs.createReadStream(filePath);
|
||||||
|
stream.pipe(res);
|
||||||
|
|
||||||
|
const msg = `Media Route | Generated Entry Preview`
|
||||||
|
logToFile(msg);
|
||||||
|
}).catch((err) => {
|
||||||
|
const msg = `Media Route | Error Generating Entry Preview`
|
||||||
|
logToFile(msg);
|
||||||
|
});
|
||||||
|
|
||||||
return res.status(200).json(createdMedia);
|
return res.status(200).json(createdMedia);
|
||||||
}
|
}
|
||||||
@@ -417,7 +404,7 @@ entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => {
|
|||||||
{ isSelected: false },
|
{ isSelected: false },
|
||||||
{
|
{
|
||||||
where: {
|
where: {
|
||||||
entryId: entryId,
|
mediaableId: entryId,
|
||||||
type: media.type
|
type: media.type
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ const path = require('path');
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
|
|
||||||
const { getSettings } = require('../services/settingsService');
|
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();
|
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
|
// ? and generate a preview file, but still return 202 http code since the file
|
||||||
// ? is still generating
|
// ? is still generating
|
||||||
if (err && size == 'preview') {
|
if (err && size == 'preview') {
|
||||||
const originalPath = path.join(mediaPath, fileName);
|
// const originalPath = path.join(mediaPath, fileName);
|
||||||
const previewFileName = fileName.split('.')[0] + '_preview.jpg'
|
// const previewFileName = fileName.split('.')[0] + '_preview.jpg'
|
||||||
const previewPath = path.join(mediaPath, previewFileName);
|
// const previewPath = path.join(mediaPath, previewFileName);
|
||||||
|
|
||||||
let previewWidth = 342;
|
// let previewWidth = 342;
|
||||||
if (type == 'backdrops') previewWidth = 780;
|
// if (type == 'backdrops') previewWidth = 780;
|
||||||
if (type == 'logos') previewWidth = 300;
|
// if (type == 'logos') previewWidth = 300;
|
||||||
|
|
||||||
generatePreview(originalPath, previewPath, previewWidth).then((result) => {
|
doGeneratePreview(category, type, fileName).then((result) => {
|
||||||
console.log(`generated a preview: `, previewFileName);
|
|
||||||
const stream = fs.createReadStream(filePath);
|
const stream = fs.createReadStream(filePath);
|
||||||
stream.pipe(res);
|
stream.pipe(res);
|
||||||
|
logToFile(`Media Route | Generated Preview`);
|
||||||
}).catch((err) => {
|
}).catch((err) => {
|
||||||
|
logToFile(`Media Route | Error Generating Preview`);
|
||||||
});;
|
logToFile(err);
|
||||||
|
});
|
||||||
// const stream = fs.createReadStream(filePath);
|
// const stream = fs.createReadStream(filePath);
|
||||||
// stream.pipe(res);
|
// stream.pipe(res);
|
||||||
// return res.status(202).send('Preview is still generating. Please try again later.');
|
// return res.status(202).send('Preview is still generating. Please try again later.');
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const userCollectionRoutes = require('./user-collection.routes');
|
const collectionRouter = require('./user-collection.routes');
|
||||||
const entryIdsRouter = require('./entry-ids.routes');
|
const entryIdsRouter = require('./entry-ids.routes');
|
||||||
const entrySeenRouter = require('./entry-seen.routes');
|
const entrySeenRouter = require('./entry-seen.routes');
|
||||||
const entryRouter = require('./entry.routes');
|
const entryRouter = require('./entry.routes');
|
||||||
@@ -16,7 +16,7 @@ const episodeRouter = require('./episode.routes');
|
|||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
router.use('/media', mediaRouter);
|
router.use('/media', mediaRouter);
|
||||||
router.use('/entries', entryRouter);
|
router.use('/entries', entryRouter);
|
||||||
router.use('/user-collections', userCollectionRoutes);
|
router.use('/collections', collectionRouter);
|
||||||
router.use('/entry-seen', entrySeenRouter);
|
router.use('/entry-seen', entrySeenRouter);
|
||||||
router.use('/entry-ids', entryIdsRouter);
|
router.use('/entry-ids', entryIdsRouter);
|
||||||
router.use('/entry-ratings', entryRatingsRouter);
|
router.use('/entry-ratings', entryRatingsRouter);
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
const express = require('express');
|
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 UserCollectionEntry = require('../models/UserCollectionEntry');
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require('../models/Entry');
|
||||||
const EntryId = require('../models/EntryId');
|
const EntryId = require('../models/EntryId');
|
||||||
@@ -8,58 +13,61 @@ const Season = require('../models/Season');
|
|||||||
const Genre = require('../models/Genre');
|
const Genre = require('../models/Genre');
|
||||||
const Media = require('../models/Media');
|
const Media = require('../models/Media');
|
||||||
|
|
||||||
const { Sequelize } = require('sequelize');
|
const { getCollectionParts, upsertOfficialCollection } = require('../services/models-services/collectionService');
|
||||||
const router = express.Router();
|
const { collectionPicturesUpload } = require('../services/mutlerStorageLocations');
|
||||||
const multer = require('multer');
|
const { logToFile } = require('../services/logService');
|
||||||
const { v4: uuidv4 } = require('uuid');
|
|
||||||
const path = require('path');
|
|
||||||
const { getMediaFolder, generatePreview } = require('../services/mediaService');
|
|
||||||
|
|
||||||
// ! /user-collections
|
// ! /collections
|
||||||
// * GET - ALL UserCollections
|
// * GET - ALL COLLECTIONS
|
||||||
router.get('/', async (req, res) => {
|
collectionRouter.get('/', async (req, res) => {
|
||||||
let userCollections; // Declare outside to broaden scope, albeit unnecessary in your given context
|
let collections; // Declare outside to broaden scope, albeit unnecessary in your given context
|
||||||
try {
|
try {
|
||||||
userCollections = await UserCollection.findAll({
|
collections = await Collection.findAll({
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Entry, as: 'entries',
|
model: Entry, as: 'entries',
|
||||||
include: { model: Media, as: 'medias' }
|
include: { model: Media, as: 'medias' }
|
||||||
},
|
},
|
||||||
|
{ model: Media, as: 'medias' }
|
||||||
],
|
],
|
||||||
order: [['name', 'ASC']]
|
order: [['name', 'ASC']]
|
||||||
});
|
});
|
||||||
res.status(200).json(userCollections);
|
res.status(200).json(collections);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching UserCollections:", error); // More detailed error logging
|
console.error("Error fetching UserCollections:", error); // More detailed error logging
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * GET - userCollection BY ID
|
// * GET - COLLECTION BY ID
|
||||||
router.get('/:id', async (req, res) => {
|
collectionRouter.get('/:id', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const userCollection = await UserCollection.findByPk(req.params.id, {
|
const collectionId = req.params.id;
|
||||||
include: [{
|
|
||||||
model: Entry,
|
const collection = await Collection.findByPk(collectionId, {
|
||||||
as: 'entries',
|
include: [
|
||||||
include: [
|
{
|
||||||
{ model: EntryId, as: 'entryId' },
|
model: Entry,
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
as: 'entries',
|
||||||
{ model: Season, as: 'seasons' },
|
include: [
|
||||||
{ model: Media, as: 'medias' },
|
{ model: EntryId, as: 'entryId' },
|
||||||
{ model: Genre, as: 'genres' },
|
{ model: EntryRating, as: 'entryRating' },
|
||||||
],
|
{ model: Season, as: 'seasons' },
|
||||||
through: {
|
{ model: Media, as: 'medias' },
|
||||||
model: UserCollectionEntry,
|
{ model: Genre, as: 'genres' },
|
||||||
attributes: ['order'], // attributes (to include) from the join model
|
],
|
||||||
|
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
|
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
||||||
});
|
});
|
||||||
|
|
||||||
if (userCollection) {
|
if (collection) {
|
||||||
const collectionData = userCollection.get({ plain: true });
|
const collectionData = collection.get({ plain: true });
|
||||||
for (let i = 0; i < collectionData.entries.length; i++) {
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
||||||
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
||||||
collectionData.entries[i].genres = genres
|
collectionData.entries[i].genres = genres
|
||||||
@@ -75,70 +83,173 @@ router.get('/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * POST - CREATE UserCollection
|
// * POST - CREATE COLLECTION
|
||||||
router.post('/', async (req, res) => {
|
collectionRouter.post('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { name, description, userRating, posterPath } = req.body;
|
const { name, description, userRating, posterPath } = req.body;
|
||||||
const isUserCollection = true;
|
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);
|
res.status(201).json(newUserCollection);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const storage = multer.diskStorage({
|
// * PUT - UPDATE COLLECTION
|
||||||
destination: function (req, file, cb) {
|
const upload = collectionPicturesUpload.fields([
|
||||||
cb(null, path.join(getMediaFolder(), 'images', 'collections', 'posters'))
|
{ name: 'poster', maxCount: 1 },
|
||||||
},
|
{ name: 'backdrop', maxCount: 1 }
|
||||||
filename: function (req, file, cb) {
|
]);
|
||||||
const uniqueFilename = uuidv4();
|
collectionRouter.put('/:id', upload, async (req, res) => {
|
||||||
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) => {
|
|
||||||
try {
|
try {
|
||||||
const userCollectionId = req.params.id;
|
const collectionId = req.params.id;
|
||||||
const { name, description, userRating, is_poster_link } = req.body;
|
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 = {
|
const updateData = {
|
||||||
name,
|
name,
|
||||||
description,
|
description,
|
||||||
userRating: parseInt(userRating, 10),
|
userRating: parseInt(userRating, 10),
|
||||||
isLocal: false,
|
isLocal: false,
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (posterPath) {
|
if (posterPath) {
|
||||||
updateData.posterPath = posterPath;
|
// ? generating preview
|
||||||
updateData.isLocal = true;
|
doGeneratePreview("collections", 'posters', posterPath).then((result) => {
|
||||||
|
const msg = `Collection Service | Generated Collection Preview`;
|
||||||
|
logToFile(msg);
|
||||||
|
}).catch((err) => {
|
||||||
|
const msg = `Collection Service | Error Generating Collection Preview`;
|
||||||
|
logToFile(msg);
|
||||||
|
logToFile(err);
|
||||||
|
});
|
||||||
|
|
||||||
// ? generating preview
|
await Media.create({
|
||||||
const fileNameWithoutExt = req.file.filename.split('.')[0];
|
mediaable: 'collection',
|
||||||
const originalPath = req.file.path;
|
mediaableId: collectionId,
|
||||||
|
type: 'poster',
|
||||||
let previewWidth = 342; // ? poster preview width
|
path: posterPath,
|
||||||
const previewPath = path.join(req.file.destination, `${fileNameWithoutExt}_preview.jpg`);
|
isLocal: true,
|
||||||
generatePreview(originalPath, previewPath, previewWidth);
|
isSelected: true,
|
||||||
|
isCustom: true
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const updated = await UserCollection.update(updateData, {
|
if (backdropPath) {
|
||||||
where: { id: userCollectionId }
|
// ? generating preview
|
||||||
|
doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => {
|
||||||
|
const msg = `Collection Routes | Generated Collection Preview`;
|
||||||
|
logToFile(msg);
|
||||||
|
}).catch((err) => {
|
||||||
|
const msg = `Collection Routes | Error Generating Collection Preview`;
|
||||||
|
logToFile(msg);
|
||||||
|
logToFile(err);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ? inserting data
|
||||||
|
await Media.create({
|
||||||
|
mediaable: 'collection',
|
||||||
|
mediaableId: collectionId,
|
||||||
|
type: 'backdrop',
|
||||||
|
path: backdropPath,
|
||||||
|
isLocal: true,
|
||||||
|
isSelected: true,
|
||||||
|
isCustom: true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const oldCollection = await Collection.findByPk(collectionId, {
|
||||||
|
include: [{
|
||||||
|
model: Entry,
|
||||||
|
as: 'entries',
|
||||||
|
include: [
|
||||||
|
{ model: EntryId, as: 'entryId' },
|
||||||
|
{ model: EntryRating, as: 'entryRating' },
|
||||||
|
{ model: Season, as: 'seasons' },
|
||||||
|
{ model: Media, as: 'medias' },
|
||||||
|
{ model: Genre, as: 'genres' },
|
||||||
|
],
|
||||||
|
through: {
|
||||||
|
model: UserCollectionEntry,
|
||||||
|
attributes: ['order'], // attributes (to include) from the join model
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ model: Media, as: 'medias' },
|
||||||
|
],
|
||||||
|
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!updated[0]) {
|
if (!oldCollection)
|
||||||
return res.status(404).json({ message: 'UserCollection not found' });
|
res.status(404).json({ message: 'Collection not found' });
|
||||||
}
|
|
||||||
|
|
||||||
if (updated) {
|
await oldCollection.update(updateData);
|
||||||
const updatedUserCollection = await UserCollection.findByPk(userCollectionId, {
|
|
||||||
include: [{
|
res.status(200).json(oldCollection);
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`UserCollection update (put) error: `, error)
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// * PUT - REFRESH COLLECTION
|
||||||
|
collectionRouter.put('/:id/refresh', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const collectionId = req.params.id;
|
||||||
|
const oldCollection = await Collection.findByPk(collectionId);
|
||||||
|
|
||||||
|
const collection = await upsertOfficialCollection(oldCollection.tmdbId);
|
||||||
|
|
||||||
|
// const collection = await Collection.findByPk(collectionId, {
|
||||||
|
// include: [{
|
||||||
|
// model: Entry,
|
||||||
|
// as: 'entries',
|
||||||
|
// include: [
|
||||||
|
// { model: EntryId, as: 'entryId' },
|
||||||
|
// { model: EntryRating, as: 'entryRating' },
|
||||||
|
// { model: Season, as: 'seasons' },
|
||||||
|
// { model: Media, as: 'medias' },
|
||||||
|
// { model: Genre, as: 'genres' },
|
||||||
|
// ],
|
||||||
|
// through: {
|
||||||
|
// model: UserCollectionEntry,
|
||||||
|
// attributes: ['order'], // attributes (to include) from the join model
|
||||||
|
// },
|
||||||
|
// }],
|
||||||
|
// order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
||||||
|
// });
|
||||||
|
|
||||||
|
if (collection) {
|
||||||
|
const collectionData = collection.get({ plain: true });
|
||||||
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
||||||
|
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
||||||
|
collectionData.entries[i].genres = genres
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json(collectionData);
|
||||||
|
} else {
|
||||||
|
res.status(404).json({ message: 'Collection not found' });
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.log(`UserCollection update (put) error: `, error)
|
||||||
|
res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// * PUT - GET COLLECTION PARTS
|
||||||
|
collectionRouter.put('/:id/parts', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const collectionId = req.params.id;
|
||||||
|
|
||||||
|
await getCollectionParts(collectionId);
|
||||||
|
|
||||||
|
const collection = await Collection.findByPk(collectionId, {
|
||||||
|
include: [
|
||||||
|
{
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: 'entries',
|
as: 'entries',
|
||||||
include: [
|
include: [
|
||||||
@@ -152,13 +263,22 @@ router.put('/:id', upload.single('poster'), async (req, res) => {
|
|||||||
model: UserCollectionEntry,
|
model: UserCollectionEntry,
|
||||||
attributes: ['order'], // attributes (to include) from the join model
|
attributes: ['order'], // attributes (to include) from the join model
|
||||||
},
|
},
|
||||||
}],
|
},
|
||||||
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
{ model: Media, as: 'medias' },
|
||||||
});
|
],
|
||||||
|
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
||||||
|
});
|
||||||
|
|
||||||
res.status(200).json(updatedUserCollection);
|
if (collection) {
|
||||||
|
const collectionData = collection.get({ plain: true });
|
||||||
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
||||||
|
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
||||||
|
collectionData.entries[i].genres = genres
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(200).json(collectionData);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'UserCollection not found' });
|
res.status(404).json({ message: 'Collection not found' });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`UserCollection update (put) error: `, error)
|
console.log(`UserCollection update (put) error: `, error)
|
||||||
@@ -166,10 +286,10 @@ router.put('/:id', upload.single('poster'), async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * DELETE - A UserCollection
|
// * DELETE - DELETE COLLECTION
|
||||||
router.delete('/:id', async (req, res) => {
|
collectionRouter.delete('/:id', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const deleted = await UserCollection.destroy({ where: { id: req.params.id } });
|
const deleted = await Collection.destroy({ where: { id: req.params.id } });
|
||||||
if (deleted) {
|
if (deleted) {
|
||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
} else {
|
} else {
|
||||||
@@ -180,8 +300,8 @@ router.delete('/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * POST - ADD ENTRY TO A UserCollection
|
// * POST - ADD ENTRY TO A COLLECTION
|
||||||
router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
collectionRouter.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { userCollectionId, entryId } = req.params;
|
const { userCollectionId, entryId } = req.params;
|
||||||
|
|
||||||
@@ -191,7 +311,7 @@ router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ? set a default poster if none exists
|
// ? 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() === '') {
|
if (!userCollection.poster_path || userCollection.poster_path.trim() === '') {
|
||||||
const entry = await Entry.findByPk(entryId);
|
const entry = await Entry.findByPk(entryId);
|
||||||
userCollection.poster_path = entry.poster_path;
|
userCollection.poster_path = entry.poster_path;
|
||||||
@@ -205,8 +325,8 @@ router.post('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * PATCH - UPDATE ENTRY ORDER IN UserCollection
|
// * PATCH - UPDATE ENTRY ORDER IN COLLECTION
|
||||||
router.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
|
collectionRouter.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { userCollectionId, entryId } = req.params;
|
const { userCollectionId, entryId } = req.params;
|
||||||
const { newOrder } = req.body;
|
const { newOrder } = req.body;
|
||||||
@@ -233,8 +353,8 @@ router.patch('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * DELETE - REMOVE AN ENTRY FROM A UserCollection
|
// * DELETE - REMOVE AN ENTRY FROM A COLLECTION
|
||||||
router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
|
collectionRouter.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { userCollectionId, entryId } = req.params;
|
const { userCollectionId, entryId } = req.params;
|
||||||
const deleted = await UserCollectionEntry.findOne({
|
const deleted = await UserCollectionEntry.findOne({
|
||||||
@@ -258,13 +378,13 @@ router.delete('/:userCollectionId/entries/:entryId', async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// * POST - CREATE UserCollection WITH ENTRY
|
// * 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
|
const { listDetails, entryId, entryOrder } = req.body; // Destructure needed properties from the request body
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await sequelize.transaction(async (t) => {
|
const result = await sequelize.transaction(async (t) => {
|
||||||
// Step 1: Create the userCollection
|
// 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
|
// Step 2: Add an entry to the newly created userCollection
|
||||||
const newUserCollectionEntry = await UserCollectionEntry.create({
|
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();
|
const dataPath = await getMediaFolder();
|
||||||
|
|
||||||
// Handling different media types
|
// Handling different media types
|
||||||
const mediaTypes = {
|
const mediaTypeFolder = {
|
||||||
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
'entryposter': path.join(dataPath, 'images', 'entries', 'posters'),
|
||||||
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
'entrylogo': path.join(dataPath, 'images', 'entries', 'logos'),
|
||||||
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
|
'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 = [];
|
let missingFiles = [];
|
||||||
for (let i = 0; i < allMedia.length; i++) {
|
for (let i = 0; i < allMedia.length; i++) {
|
||||||
let type = `${allMedia[i].type}`.replace("_preview", "");
|
const folderType = `${allMedia[i].mediaable}${allMedia[i].type.replace("_preview", "")}`;
|
||||||
const filePath = path.join(mediaTypes[type], allMedia[i].path)
|
|
||||||
|
const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path)
|
||||||
if (!fs.existsSync(filePath)) {
|
if (!fs.existsSync(filePath)) {
|
||||||
missingFiles.push(allMedia[i]);
|
missingFiles.push(allMedia[i]);
|
||||||
}
|
}
|
||||||
@@ -33,40 +39,55 @@ async function deleteMissingFilesEntries(dry = false) {
|
|||||||
'backdrops': 0
|
'backdrops': 0
|
||||||
};
|
};
|
||||||
|
|
||||||
if (missingFiles.length == 0)
|
// if (missingFiles.length == 0)
|
||||||
return removed;
|
// return removed;
|
||||||
|
|
||||||
for (let i = 0; i < missingFiles.length; i++) {
|
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) missingFiles[i].destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
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}}`)
|
else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
||||||
|
|
||||||
return removed;
|
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) {
|
async function deleteOrphanFiles(dry = false) {
|
||||||
// Getting the userDataPath to store the images
|
// Getting the userDataPath to store the images
|
||||||
const dataPath = getMediaFolder();
|
const dataPath = getMediaFolder();
|
||||||
|
|
||||||
// ? Getting the path of all media files and putting them in an array
|
// ? Getting the path of all media files and putting them in an array
|
||||||
const allMedia = (await Media.findAll()).map(m =>
|
// const allMedia = (await Media.findAll()).map(m => {
|
||||||
path.join(dataPath, 'images', 'entries', m.type + 's', m.path)
|
// 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
|
// ? Loop trough the files of the images folder and check
|
||||||
// ? if a file doesnt exist in the allMedia array and mark it to delete
|
// ? 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 = [];
|
'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'),
|
||||||
const mediaTypes = {
|
'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops')
|
||||||
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
|
||||||
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
|
||||||
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// * counter
|
||||||
let removed = {
|
let removed = {
|
||||||
'posters': 0,
|
'posters': 0,
|
||||||
'logos': 0,
|
'logos': 0,
|
||||||
@@ -74,19 +95,31 @@ async function deleteOrphanFiles(dry = false) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Iterate over each media type directory and check for orphan files
|
// Iterate over each media type directory and check for orphan files
|
||||||
for (let type in mediaTypes) {
|
for (let folderType in mediaTypeFolder) {
|
||||||
const directory = mediaTypes[type];
|
const directory = mediaTypeFolder[folderType];
|
||||||
try {
|
try {
|
||||||
|
// ? getting all files inside that folder
|
||||||
const files = await fsPromises.readdir(directory).then();
|
const files = await fsPromises.readdir(directory).then();
|
||||||
|
// console.log(`${directory}, files count: ${files.length}`);
|
||||||
|
|
||||||
// Check each file in the directory
|
// Check each file in the directory
|
||||||
for (let file of files) {
|
for (let file of files) {
|
||||||
const filePath = path.join(directory, file);
|
// const filePath = path.join(directory, file);
|
||||||
// Check if the constructed file path exists in the allMedia array
|
// // Check if the constructed file path exists in the allMedia array
|
||||||
if (!allMedia.includes(filePath.replace("_preview", ""))) {
|
// // ? this step also takes into account preview files, by removing '_preview'
|
||||||
// If not, delete the file
|
// // ? 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);
|
if (!dry) await fsPromises.unlink(filePath);
|
||||||
removed[type + 's']++; // Increment the count of removed files
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const { v4: uuidv4 } = require('uuid');
|
|||||||
const { fetchEntryMedia } = require('./tmdbService');
|
const { fetchEntryMedia } = require('./tmdbService');
|
||||||
const { getSettings } = require('./settingsService');
|
const { getSettings } = require('./settingsService');
|
||||||
const sharp = require('sharp');
|
const sharp = require('sharp');
|
||||||
|
const { logToFile } = require('./logService');
|
||||||
|
|
||||||
async function downloadImage(url, filePath) {
|
async function downloadImage(url, filePath) {
|
||||||
const response = await axios({
|
const response = await axios({
|
||||||
@@ -66,6 +67,41 @@ async function getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos'
|
|||||||
return downloadedImages;
|
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)
|
// Utility to find the preferred media (English if available, otherwise the first one)
|
||||||
function findPreferredMedia(mediaArray, preferredLanguage = 'en') {
|
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];
|
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 uniqueFilename = uuidv4();
|
||||||
const extension = media.file_path.split('.').pop();
|
const extension = media.file_path.split('.').pop();
|
||||||
|
|
||||||
const originalUrl = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
const url = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
||||||
const originalFileName = `${uniqueFilename}.${extension}`;
|
const filename = `${uniqueFilename}.${extension}`;
|
||||||
const originalFilePath = path.join(mediaDir, originalFileName);
|
const downloadPath = path.join(mediaDir, filename);
|
||||||
|
|
||||||
// Schedule download of the original image
|
// Schedule download of the original image
|
||||||
downloadTasks.push(
|
downloadTasks.push(
|
||||||
downloadImage(originalUrl, originalFilePath)
|
downloadImage(url, downloadPath)
|
||||||
.then(() => downloadedImages.push({ type: mediaType, path: originalFileName }))
|
.then(() => {
|
||||||
.catch(err => console.error(`Error downloading ${mediaType}:`, err))
|
logToFile(`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`)
|
||||||
);
|
downloadedImages.push({ type: mediaType, path: filename })
|
||||||
|
})
|
||||||
const previewUrl = `https://image.tmdb.org/t/p/w300${media.file_path}`;
|
.catch(err => {
|
||||||
const previewFileName = `${uniqueFilename}_preview.${extension}`;
|
logToFile(`Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`)
|
||||||
const previewFilePath = path.join(mediaDir, previewFileName);
|
logToFile(err)
|
||||||
|
console.error(`Error downloading ${mediaType}:`, err)
|
||||||
// Schedule download of the preview image
|
})
|
||||||
downloadTasks.push(
|
|
||||||
downloadImage(previewUrl, previewFilePath)
|
|
||||||
.catch(err => console.error(`Error downloading preview ${mediaType}:`, err))
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -105,6 +138,28 @@ function generatePreview(originalPath, previewPath, previewWidth, previewQuality
|
|||||||
.toFile(previewPath);
|
.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() {
|
function getMediaFolder() {
|
||||||
return getSettings().userDataPath;
|
return getSettings().userDataPath;
|
||||||
}
|
}
|
||||||
@@ -117,11 +172,13 @@ function createMediaFolders() {
|
|||||||
const backdropDir = path.join(dataPath, 'images', 'entries', 'backdrops');
|
const backdropDir = path.join(dataPath, 'images', 'entries', 'backdrops');
|
||||||
const logoDir = path.join(dataPath, 'images', 'entries', 'logos');
|
const logoDir = path.join(dataPath, 'images', 'entries', 'logos');
|
||||||
const collectionsPostersDir = path.join(dataPath, 'images', 'collections', 'posters');
|
const collectionsPostersDir = path.join(dataPath, 'images', 'collections', 'posters');
|
||||||
|
const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops');
|
||||||
|
|
||||||
fs.mkdirSync(posterDir, { recursive: true });
|
fs.mkdirSync(posterDir, { recursive: true });
|
||||||
fs.mkdirSync(backdropDir, { recursive: true });
|
fs.mkdirSync(backdropDir, { recursive: true });
|
||||||
fs.mkdirSync(logoDir, { recursive: true });
|
fs.mkdirSync(logoDir, { recursive: true });
|
||||||
fs.mkdirSync(collectionsPostersDir, { recursive: true });
|
fs.mkdirSync(collectionsPostersDir, { recursive: true });
|
||||||
|
fs.mkdirSync(collectionsBackdropsDir, { recursive: true });
|
||||||
|
|
||||||
// console.log(`Created media folders.`);
|
// console.log(`Created media folders.`);
|
||||||
}
|
}
|
||||||
@@ -130,5 +187,7 @@ module.exports = {
|
|||||||
getEntryMedia,
|
getEntryMedia,
|
||||||
createMediaFolders,
|
createMediaFolders,
|
||||||
getMediaFolder,
|
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 Entry = require('../../models/Entry.js')
|
||||||
const EntryId = require('../../models/EntryId.js')
|
const EntryId = require('../../models/EntryId.js')
|
||||||
const EntryRating = require('../../models/EntryRating.js');
|
const EntryRating = require('../../models/EntryRating.js');
|
||||||
@@ -8,15 +19,6 @@ const Episode = require('../../models/Episode.js');
|
|||||||
const Media = require('../../models/Media.js');
|
const Media = require('../../models/Media.js');
|
||||||
const Genre = require('../../models/Genre.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) {
|
async function saveEntry(data) {
|
||||||
try {
|
try {
|
||||||
if (data == null) return;
|
if (data == null) return;
|
||||||
@@ -132,7 +134,7 @@ async function saveEntry(data) {
|
|||||||
|
|
||||||
// ? media
|
// ? media
|
||||||
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
|
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) {
|
for (const image of downloadedImages) {
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'entry',
|
mediaable: 'entry',
|
||||||
@@ -141,7 +143,9 @@ async function saveEntry(data) {
|
|||||||
path: image.path,
|
path: image.path,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true
|
||||||
})
|
});
|
||||||
|
|
||||||
|
doGeneratePreview('entries', image.type + 's', image.path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -348,27 +352,27 @@ async function refrechEntry(entryId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ? getting new data from TMDB
|
// ? getting new data from TMDB
|
||||||
const data = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
||||||
if (data == null) {
|
if (entryData == null) {
|
||||||
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ! the refrech logic
|
// ! the refrech logic
|
||||||
let newData = {
|
let newData = {
|
||||||
title: data.title || data.name,
|
title: entryData.title || entryData.name,
|
||||||
original_title: data.original_title || data.original_name,
|
original_title: entryData.original_title || entryData.original_name,
|
||||||
release_date: data.release_date || data.first_air_date,
|
release_date: entryData.release_date || entryData.first_air_date,
|
||||||
release_status: data.status,
|
release_status: entryData.status,
|
||||||
runtime: data.runtime || null,
|
runtime: entryData.runtime || null,
|
||||||
|
|
||||||
tagline: data.tagline || null,
|
tagline: entryData.tagline || null,
|
||||||
storyline: data.overview,
|
storyline: entryData.overview,
|
||||||
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
|
||||||
|
|
||||||
status: data.status,
|
status: entryData.status,
|
||||||
|
|
||||||
poster_path: data.poster_path,
|
poster_path: entryData.poster_path,
|
||||||
banner_path: data.backdrop_path,
|
banner_path: entryData.backdrop_path,
|
||||||
|
|
||||||
last_fetch: new Date()
|
last_fetch: new Date()
|
||||||
};
|
};
|
||||||
@@ -378,17 +382,17 @@ async function refrechEntry(entryId) {
|
|||||||
// * updating ids
|
// * updating ids
|
||||||
// TODO: get more ids
|
// TODO: get more ids
|
||||||
await oldEntry.entryId.update({
|
await oldEntry.entryId.update({
|
||||||
imdb_id: data.imdb_id,
|
imdb_id: entryData.imdb_id,
|
||||||
});
|
});
|
||||||
|
|
||||||
// * updating ratings
|
// * updating ratings
|
||||||
await oldEntry.entryRating.update({
|
await oldEntry.entryRating.update({
|
||||||
tmdb_rating: data.vote_average
|
tmdb_rating: entryData.vote_average
|
||||||
});
|
});
|
||||||
|
|
||||||
// * updating genres
|
// * updating genres
|
||||||
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
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 the entry already has this genre then skip
|
||||||
if (currentGenresIds.includes(genre.id)) return;
|
if (currentGenresIds.includes(genre.id)) return;
|
||||||
|
|
||||||
@@ -406,9 +410,9 @@ async function refrechEntry(entryId) {
|
|||||||
// ? and atleast 48 hours has passed
|
// ? and atleast 48 hours has passed
|
||||||
|
|
||||||
// * Update or insert seasons for the entry
|
// * 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
|
// 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)
|
// Fetch existing season if it exists (using tmdb_id)
|
||||||
let existingSeason = await Season.findOne({
|
let existingSeason = await Season.findOne({
|
||||||
@@ -498,32 +502,27 @@ async function refrechEntry(entryId) {
|
|||||||
|
|
||||||
// * Media
|
// * Media
|
||||||
// ? Only fetch if a Poster, Backdrop or a Logo is missing
|
// ? Only fetch if a Poster, Backdrop or a Logo is missing
|
||||||
|
// ? only get missing media types
|
||||||
|
|
||||||
|
// ? count media by type
|
||||||
|
let availableMedia = {
|
||||||
|
'posters': 0,
|
||||||
|
'logos': 0,
|
||||||
|
'backdrops': 0
|
||||||
|
};
|
||||||
|
for (let i = 0; i < oldEntry.medias.length; i++) {
|
||||||
|
availableMedia[oldEntry.medias[i].type + 's'] += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ? if the count of a media type == 0, the add the type to mediaToGet
|
||||||
|
let mediaToGet = [];
|
||||||
|
for (let key in availableMedia) {
|
||||||
|
if (availableMedia[key] == 0) mediaToGet.push(key);
|
||||||
|
}
|
||||||
|
|
||||||
let downloadedImages;
|
let downloadedImages;
|
||||||
if (oldEntry.medias.length < 3) {
|
if (mediaToGet.length != 0) {
|
||||||
// ? if no media is available, directly get all
|
downloadedImages = await getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
|
||||||
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries);
|
|
||||||
} else {
|
|
||||||
// ? only get missing media types
|
|
||||||
let availableMedia = {
|
|
||||||
'posters': 0,
|
|
||||||
'logos': 0,
|
|
||||||
'backdrops': 0
|
|
||||||
};
|
|
||||||
|
|
||||||
// ? count media by type
|
|
||||||
for (let i = 0; i < oldEntry.medias.length; i++) {
|
|
||||||
availableMedia[oldEntry.medias[i].type] += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ? if the count of a media type == 0, the add the type to mediaToGet
|
|
||||||
let mediaToGet = [];
|
|
||||||
for (let key in availableMedia) {
|
|
||||||
if (availableMedia[key] == 0) mediaToGet.push(availableMedia[key]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mediaToGet.length != 0) {
|
|
||||||
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries, mediaToGet);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (downloadedImages) {
|
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
|
// + end of: refrech logic
|
||||||
|
|
||||||
// ! returning the refreshed entry
|
// ! returning the refreshed entry
|
||||||
@@ -548,6 +553,7 @@ async function refrechEntry(entryId) {
|
|||||||
{ model: EntrySeen, as: 'entrySeen' },
|
{ model: EntrySeen, as: 'entrySeen' },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: 'seasons' },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: 'medias' },
|
||||||
|
{ model: Collection, as: 'collections' },
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: 'genres',
|
||||||
@@ -566,8 +572,8 @@ async function refrechEntry(entryId) {
|
|||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
const entryData = updatedEntry.get({ plain: true });
|
const plainEntry = updatedEntry.get({ plain: true });
|
||||||
entryData.genres = entryData.genres.map(genre => genre.name);
|
plainEntry.genres = plainEntry.genres.map(genre => genre.name);
|
||||||
|
|
||||||
return entryData;
|
return entryData;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,8 +12,7 @@ const entryPicturesUpload = multer({
|
|||||||
if (file.fieldname == 'backdrop') folder = 'backdrops';
|
if (file.fieldname == 'backdrop') folder = 'backdrops';
|
||||||
if (file.fieldname == 'logo') folder = 'logos';
|
if (file.fieldname == 'logo') folder = 'logos';
|
||||||
|
|
||||||
const settings = getSettings();
|
const dataPath = getSettings().userDataPath;
|
||||||
const dataPath = settings.userDataPath;
|
|
||||||
|
|
||||||
cb(null, path.join(dataPath, 'images', 'entries', folder));
|
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 = {
|
module.exports = {
|
||||||
entryPicturesUpload,
|
entryPicturesUpload,
|
||||||
|
collectionPicturesUpload,
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,7 @@ import { CommonModule } from '@angular/common';
|
|||||||
import { TmdbService } from './services/tmdb.service';
|
import { TmdbService } from './services/tmdb.service';
|
||||||
import { LibraryService } from './services/library.service';
|
import { LibraryService } from './services/library.service';
|
||||||
import { EntryService } from './services/entry.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 { ToggleService } from './services/toggle.service';
|
||||||
import { SidebarComponent } from './components/sidebar/sidebar.component';
|
import { SidebarComponent } from './components/sidebar/sidebar.component';
|
||||||
import { NavbarComponent } from './components/navbar/navbar.component';
|
import { NavbarComponent } from './components/navbar/navbar.component';
|
||||||
@@ -32,7 +32,7 @@ import { SharedModule } from '../shared/shared.module';
|
|||||||
LibraryService,
|
LibraryService,
|
||||||
EntryService,
|
EntryService,
|
||||||
EntrySeenService,
|
EntrySeenService,
|
||||||
UserCollectionService,
|
CollectionService,
|
||||||
ToggleService,
|
ToggleService,
|
||||||
EpisodeService,
|
EpisodeService,
|
||||||
EpisodeSeenService,
|
EpisodeSeenService,
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export class EntryService {
|
|||||||
// update entry
|
// update entry
|
||||||
refrechEntryById(entryId: number) {
|
refrechEntryById(entryId: number) {
|
||||||
return this.http.get<Entry>(
|
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({
|
@Injectable({
|
||||||
providedIn: 'root',
|
providedIn: 'root',
|
||||||
})
|
})
|
||||||
export class UserCollectionService {
|
export class CollectionService {
|
||||||
private backend_apiUrl = environment.API_URL;
|
private backend_apiUrl = environment.API_URL;
|
||||||
private apiAction = 'user-collections';
|
private apiAction = 'collections';
|
||||||
|
|
||||||
constructor(private http: HttpClient) {}
|
constructor(private http: HttpClient) {}
|
||||||
|
|
||||||
@@ -23,68 +23,84 @@ export class UserCollectionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// get a list by id
|
// get a list by id
|
||||||
getCollection(userCollectionId: string) {
|
getCollection(collectionId: string) {
|
||||||
return this.http.get<UserCollection>(
|
return this.http.get<UserCollection>(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}`
|
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a new list
|
// Create a new list
|
||||||
createCollection(userCollection: UserCollection): Observable<UserCollection> {
|
createCollection(collection: UserCollection): Observable<UserCollection> {
|
||||||
return this.http.post<UserCollection>(
|
return this.http.post<UserCollection>(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}`,
|
`${this.backend_apiUrl}/${this.apiAction}`,
|
||||||
userCollection
|
collection
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// * PUT - update a collection
|
// * PUT - update a collection
|
||||||
updateCollection(
|
updateCollection(
|
||||||
userCollectionId: number,
|
collectionId: number,
|
||||||
formData: FormData
|
formData: FormData
|
||||||
): Observable<UserCollection> {
|
): Observable<UserCollection> {
|
||||||
return this.http.put<UserCollection>(
|
return this.http.put<UserCollection>(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}`,
|
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}`,
|
||||||
formData
|
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
|
// Delete a list by ID
|
||||||
deleteCollection(userCollectionId: number): Observable<any> {
|
deleteCollection(collectionId: number): Observable<any> {
|
||||||
return this.http.delete(
|
return this.http.delete(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}`
|
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add an entry to a list
|
// Add an entry to a list
|
||||||
addEntryToCollection(
|
addEntryToCollection(
|
||||||
userCollectionId: number,
|
collectionId: number,
|
||||||
entryId: number
|
entryId: number
|
||||||
): Observable<UserCollectionEntry> {
|
): Observable<UserCollectionEntry> {
|
||||||
return this.http.post<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
|
// Update an entry's order in a list
|
||||||
updateEntryOrder(
|
updateEntryOrder(
|
||||||
userCollectionId: string,
|
collectionId: string,
|
||||||
entryId: number,
|
entryId: number,
|
||||||
newOrder: number
|
newOrder: number
|
||||||
): Observable<any> {
|
): Observable<any> {
|
||||||
return this.http.patch(
|
return this.http.patch(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`,
|
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}/entries/${entryId}`,
|
||||||
{ newOrder: newOrder }
|
{ newOrder: newOrder }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove an entry from a list
|
// Remove an entry from a list
|
||||||
removeEntryFromCollection(
|
removeEntryFromCollection(
|
||||||
userCollectionId: string,
|
collectionId: string,
|
||||||
entryId: number
|
entryId: number
|
||||||
): Observable<Entry> {
|
): Observable<Entry> {
|
||||||
return this.http.delete<Entry>(
|
return this.http.delete<Entry>(
|
||||||
`${this.backend_apiUrl}/${this.apiAction}/${userCollectionId}/entries/${entryId}`
|
`${this.backend_apiUrl}/${this.apiAction}/${collectionId}/entries/${entryId}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-2
@@ -4,7 +4,7 @@
|
|||||||
<button type="button" class="btn-close" (click)="onClose()" aria-label="Close"></button>
|
<button type="button" class="btn-close" (click)="onClose()" aria-label="Close"></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body p-4 pt-1">
|
<div class="card-body p-4 pt-1">
|
||||||
<form class="row g-3" [formGroup]="form">
|
<form class="row g-3" [formGroup]="form" >
|
||||||
<div class="col-md-12">
|
<div class="col-md-12">
|
||||||
<label class="form-label">Name</label>
|
<label class="form-label">Name</label>
|
||||||
<input type="text" class="form-control rounded-0" formControlName="name">
|
<input type="text" class="form-control rounded-0" formControlName="name">
|
||||||
@@ -32,7 +32,19 @@
|
|||||||
|
|
||||||
<div class="col-md-12">
|
<div class="col-md-12">
|
||||||
<label class="form-label">Poster</label>
|
<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>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+37
-10
@@ -35,6 +35,12 @@ import {
|
|||||||
export class CollectionEditModalComponent implements OnInit {
|
export class CollectionEditModalComponent implements OnInit {
|
||||||
form!: FormGroup;
|
form!: FormGroup;
|
||||||
|
|
||||||
|
posterFile: File | null = null;
|
||||||
|
backdropFile: File | null = null;
|
||||||
|
|
||||||
|
posterPreview: string | ArrayBuffer | null = '';
|
||||||
|
backdropPreview: string | ArrayBuffer | null = '';
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public dialogRef: MatDialogRef<CollectionEditModalComponent>,
|
public dialogRef: MatDialogRef<CollectionEditModalComponent>,
|
||||||
@Inject(MAT_DIALOG_DATA) public data: any,
|
@Inject(MAT_DIALOG_DATA) public data: any,
|
||||||
@@ -48,20 +54,43 @@ export class CollectionEditModalComponent implements OnInit {
|
|||||||
description: [this.data.description],
|
description: [this.data.description],
|
||||||
userRating: [this.data.userRating],
|
userRating: [this.data.userRating],
|
||||||
poster: [null],
|
poster: [null],
|
||||||
|
backdrop: [null],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onFileChange(event: any) {
|
onFileChange(event: Event, type: string) {
|
||||||
const file = event.target.files[0];
|
const file = (event.target as HTMLInputElement).files?.[0];
|
||||||
this.form.patchValue({ poster: file });
|
if (!file) return;
|
||||||
this.form.get('poster')?.updateValueAndValidity();
|
|
||||||
|
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 {
|
onConfirm(): void {
|
||||||
if (this.form.invalid) return this.form.markAllAsTouched();
|
if (this.form.invalid) return this.form.markAllAsTouched();
|
||||||
|
|
||||||
let formData = new FormData();
|
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('name', this.form.get('name')?.value.toString().trim());
|
||||||
formData.append('description', this.form.get('description')?.value || '');
|
formData.append('description', this.form.get('description')?.value || '');
|
||||||
formData.append(
|
formData.append(
|
||||||
@@ -70,12 +99,10 @@ export class CollectionEditModalComponent implements OnInit {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Check and append file if it exists
|
// Check and append file if it exists
|
||||||
const posterFile = this.form.get('poster')?.value;
|
// const posterFile = this.form.get('poster')?.value;
|
||||||
if (posterFile) {
|
// if (posterFile) {
|
||||||
formData.append('poster', posterFile);
|
// formData.append('poster', posterFile);
|
||||||
}
|
// }
|
||||||
|
|
||||||
formData.append('is_poster_link', 'false');
|
|
||||||
|
|
||||||
this.dialogRef.close({ formData: formData });
|
this.dialogRef.close({ formData: formData });
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
import { Component, Input } from '@angular/core';
|
import { Component, Input } from '@angular/core';
|
||||||
import { Entry } from '../../../../shared/models/entry.model';
|
import { Entry } from '../../../../shared/models/entry.model';
|
||||||
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
import { CollectionService } from '../../../../core/services/userCollection.service';
|
||||||
import {
|
import {
|
||||||
CdkDragDrop,
|
CdkDragDrop,
|
||||||
CdkDragEnd,
|
CdkDragEnd,
|
||||||
@@ -30,7 +30,7 @@ export class CollectionEntryTableComponent {
|
|||||||
@Input() entries: Entry[] = [];
|
@Input() entries: Entry[] = [];
|
||||||
@Input() collectionId: string = '';
|
@Input() collectionId: string = '';
|
||||||
|
|
||||||
constructor(private userCollectionService: UserCollectionService) {}
|
constructor(private userCollectionService: CollectionService) {}
|
||||||
|
|
||||||
refrechEventReceiver() {
|
refrechEventReceiver() {
|
||||||
console.log('event recieved');
|
console.log('event recieved');
|
||||||
|
|||||||
+2
-2
@@ -10,7 +10,7 @@ import { MatDialog } from '@angular/material/dialog';
|
|||||||
import { LibraryService } from '../../../../core/services/library.service';
|
import { LibraryService } from '../../../../core/services/library.service';
|
||||||
import { Entry } from '../../../../shared/models/entry.model';
|
import { Entry } from '../../../../shared/models/entry.model';
|
||||||
import { trigger, transition, style, animate } from '@angular/animations';
|
import { trigger, transition, style, animate } from '@angular/animations';
|
||||||
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
import { CollectionService } from '../../../../core/services/userCollection.service';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component';
|
||||||
import { environment } from '../../../../../environments/environment.prod';
|
import { environment } from '../../../../../environments/environment.prod';
|
||||||
@@ -37,7 +37,7 @@ export class CollectionTableLineComponent implements OnInit {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private libraryService: LibraryService,
|
private libraryService: LibraryService,
|
||||||
private userCollectionService: UserCollectionService,
|
private userCollectionService: CollectionService,
|
||||||
public dialog: MatDialog,
|
public dialog: MatDialog,
|
||||||
private router: Router
|
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 { MatDialog } from '@angular/material/dialog';
|
||||||
import { Entry } from '../../../../shared/models/entry.model';
|
import { Entry } from '../../../../shared/models/entry.model';
|
||||||
import { trigger, transition, style, animate } from '@angular/animations';
|
import { trigger, transition, style, animate } from '@angular/animations';
|
||||||
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
import { CollectionService } from '../../../../core/services/userCollection.service';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component';
|
import { ConfirmModalComponent } from '../../../../shared/components/modals/confirm-modal/confirm-modal.component';
|
||||||
import { environment } from '../../../../../environments/environment.prod';
|
import { environment } from '../../../../../environments/environment.prod';
|
||||||
@@ -27,7 +27,7 @@ export class UserCollectionGridCardComponent implements OnInit {
|
|||||||
@Output() refrechEvent = new EventEmitter();
|
@Output() refrechEvent = new EventEmitter();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private userCollectionService: UserCollectionService,
|
private userCollectionService: CollectionService,
|
||||||
public dialog: MatDialog,
|
public dialog: MatDialog,
|
||||||
private router: Router
|
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)="switchViewMode()">Switch View</a></li>
|
||||||
<li><a class="dropdown-item" (click)="deleteCollection()">Delete</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" (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>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+49
-7
@@ -1,6 +1,6 @@
|
|||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
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 { UserCollection } from '../../../../shared/models/userCollection.model';
|
||||||
import { DatePipe } from '@angular/common';
|
import { DatePipe } from '@angular/common';
|
||||||
import { CollectionEntry } from '../../../../shared/models/dtos/collection-entry.dto';
|
import { CollectionEntry } from '../../../../shared/models/dtos/collection-entry.dto';
|
||||||
@@ -25,7 +25,7 @@ export class UserCollectionInfoPageComponent implements OnInit {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private route: ActivatedRoute,
|
private route: ActivatedRoute,
|
||||||
private userCollectionService: UserCollectionService,
|
private userCollectionService: CollectionService,
|
||||||
private screenshotService: ScreenshotService,
|
private screenshotService: ScreenshotService,
|
||||||
private datePipe: DatePipe,
|
private datePipe: DatePipe,
|
||||||
public dialog: MatDialog,
|
public dialog: MatDialog,
|
||||||
@@ -36,8 +36,8 @@ export class UserCollectionInfoPageComponent implements OnInit {
|
|||||||
const id = this.route.snapshot.paramMap.get('id');
|
const id = this.route.snapshot.paramMap.get('id');
|
||||||
if (id == null) return; // todo redirect if no id is provided
|
if (id == null) return; // todo redirect if no id is provided
|
||||||
|
|
||||||
this.userCollectionService.getCollection(id.toString()).subscribe(
|
this.userCollectionService.getCollection(id.toString()).subscribe({
|
||||||
(data) => {
|
next: (data) => {
|
||||||
this.collection = data as unknown as UserCollection;
|
this.collection = data as unknown as UserCollection;
|
||||||
this.collection.entries = this.collection.entries as CollectionEntry[];
|
this.collection.entries = this.collection.entries as CollectionEntry[];
|
||||||
|
|
||||||
@@ -48,10 +48,10 @@ export class UserCollectionInfoPageComponent implements OnInit {
|
|||||||
// this.collection
|
// this.collection
|
||||||
// );
|
// );
|
||||||
},
|
},
|
||||||
(error) => {
|
error: (error) => {
|
||||||
console.error('Error occurred:', error);
|
console.error('Error occurred:', error);
|
||||||
}
|
},
|
||||||
);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getListId() {
|
getListId() {
|
||||||
@@ -111,6 +111,7 @@ export class UserCollectionInfoPageComponent implements OnInit {
|
|||||||
description: this.collection.description,
|
description: this.collection.description,
|
||||||
userRating: this.collection.userRating || 0,
|
userRating: this.collection.userRating || 0,
|
||||||
poster: this.collection.posterPath,
|
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() {
|
redirectToTMDB() {
|
||||||
window.open(
|
window.open(
|
||||||
`https://www.themoviedb.org/collection/${this.collection.tmdbId}`,
|
`https://www.themoviedb.org/collection/${this.collection.tmdbId}`,
|
||||||
|
|||||||
+3
-2
@@ -1,8 +1,9 @@
|
|||||||
<div class="card-coat">
|
<div class="card-coat">
|
||||||
<div class="d-flex flex-column align-items-center collection-card" @fadeInOut>
|
<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">
|
<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">Created: {{getCreatedDate() | dateFormat}}</p> -->
|
||||||
<!-- <p class="mb-0">Contains: {{list.userCollectionEntries.length}} title(s)</p> -->
|
<!-- <p class="mb-0">Contains: {{list.userCollectionEntries.length}} title(s)</p> -->
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+79
-73
@@ -1,6 +1,6 @@
|
|||||||
import { Component, Input } from '@angular/core';
|
import { Component, Input } from '@angular/core';
|
||||||
import { UserCollection } from '../../../../shared/models/userCollection.model';
|
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 { Router } from '@angular/router';
|
||||||
import { trigger, transition, style, animate } from '@angular/animations';
|
import { trigger, transition, style, animate } from '@angular/animations';
|
||||||
import { environment } from '../../../../../environments/environment.prod';
|
import { environment } from '../../../../../environments/environment.prod';
|
||||||
@@ -25,97 +25,103 @@ import { Entry } from '../../../../shared/models/entry.model';
|
|||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class UserCollectionsListItemComponent {
|
export class UserCollectionsListItemComponent {
|
||||||
@Input() list!: UserCollection;
|
@Input() collection!: UserCollection;
|
||||||
|
|
||||||
constructor(
|
constructor(private listService: CollectionService, private router: Router) {}
|
||||||
private listService: UserCollectionService,
|
|
||||||
private router: Router
|
|
||||||
) {}
|
|
||||||
|
|
||||||
getCollectionPosterPath() {
|
// getCollectionPosterPath() {
|
||||||
if (this.list.isLocal) {
|
// console.log(this.collection.medias);
|
||||||
if (this.list.posterPath == null)
|
// if (this.collection.medias.length != 0) {
|
||||||
return 'assets/images/default/default-poster.png';
|
// 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 (
|
||||||
return (
|
// environment.API_URL +
|
||||||
environment.API_URL +
|
// `/media/collections/posters/preview/${selectedPoster}`
|
||||||
`/media/collections/posters/preview/` +
|
// );
|
||||||
this.list.posterPath
|
// } else if (this.collection.entries.length != 0) {
|
||||||
);
|
// // * use the poster of the first entry in the collection
|
||||||
} else {
|
// // * if the collection is empty
|
||||||
// * use the poster of the first entry in the collection if its no empty
|
// return this.getEntryPosterPath(this.collection.entries[0]);
|
||||||
if (this.list.entries.length != 0) {
|
// } else if (this.collection.posterPath) {
|
||||||
return this.getEntryPosterPath(this.list.entries[0]);
|
// // * use first remote tmdb poster
|
||||||
}
|
// // * if collection has none and has no entry
|
||||||
|
// return `https://www.themoviedb.org/w1280/${this.collection.posterPath}`;
|
||||||
|
// } else {
|
||||||
|
// // * use default poster
|
||||||
|
// // * if collection has totaly no poster
|
||||||
|
// return 'assets/images/default/default-poster.png';
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
return `https://www.themoviedb.org/w1280/${this.list.posterPath}`;
|
// getCollectionBakcgroundPath() {
|
||||||
// * if the collection is empty
|
// return `https://www.themoviedb.org/w1280/${this.collection.backdropPath}`;
|
||||||
return 'assets/images/default/default-poster.png';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
getCollectionBakcgroundPath() {
|
// // if (this.list.isLocal) {
|
||||||
return `https://www.themoviedb.org/w1280/${this.list.backdropPath}`;
|
// // if (this.list.backdropPath == null)
|
||||||
|
// // return 'assets/images/default/default-poster.png';
|
||||||
|
|
||||||
// if (this.list.isLocal) {
|
// // // * use the collection custom poster
|
||||||
// if (this.list.backdropPath == null)
|
// // return (
|
||||||
// return 'assets/images/default/default-poster.png';
|
// // environment.API_URL +
|
||||||
|
// // `/media/collections/posters/preview/` +
|
||||||
|
// // this.list.posterPath
|
||||||
|
// // );
|
||||||
|
// // } else {
|
||||||
|
// // // * use the poster of the first entry in the collection if its no empty
|
||||||
|
// // if (this.list.entries.length != 0) {
|
||||||
|
// // return this.getEntryPosterPath(this.list.entries[0]);
|
||||||
|
// // }
|
||||||
|
|
||||||
// // * use the collection custom poster
|
// // return `https://www.themoviedb.org/w1280/${this.list.backdropPath}`;
|
||||||
// return (
|
// // // * if the collection is empty
|
||||||
// environment.API_URL +
|
// // return 'assets/images/default/default-poster.png';
|
||||||
// `/media/collections/posters/preview/` +
|
// // }
|
||||||
// this.list.posterPath
|
// }
|
||||||
// );
|
|
||||||
// } else {
|
|
||||||
// // * use the poster of the first entry in the collection if its no empty
|
|
||||||
// if (this.list.entries.length != 0) {
|
|
||||||
// return this.getEntryPosterPath(this.list.entries[0]);
|
|
||||||
// }
|
|
||||||
|
|
||||||
// return `https://www.themoviedb.org/w1280/${this.list.backdropPath}`;
|
// getEntryPosterPath(entry: Entry) {
|
||||||
// // * if the collection is empty
|
// // * Is in library: use a local poster
|
||||||
// return 'assets/images/default/default-poster.png';
|
// if (entry.medias) {
|
||||||
// }
|
// const selectedPosters = entry.medias.filter(
|
||||||
}
|
// (m) => m.type == 'poster' && m.isSelected
|
||||||
|
// );
|
||||||
|
|
||||||
getEntryPosterPath(entry: Entry) {
|
// if (
|
||||||
// * Is in library: use a local poster
|
// selectedPosters.length &&
|
||||||
if (entry.medias) {
|
// selectedPosters[0] &&
|
||||||
const selectedPosters = entry.medias.filter(
|
// selectedPosters[0].path
|
||||||
(m) => m.type == 'poster' && m.isSelected
|
// ) {
|
||||||
);
|
// const name = selectedPosters[0].path;
|
||||||
|
// return environment.API_URL + `/media/entries/posters/preview/${name}`;
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
if (
|
// // * No local poster available, Use TMDB poster
|
||||||
selectedPosters.length &&
|
// if (entry.poster_path)
|
||||||
selectedPosters[0] &&
|
// return `https://image.tmdb.org/t/p/w300` + entry.poster_path;
|
||||||
selectedPosters[0].path
|
|
||||||
) {
|
|
||||||
const name = selectedPosters[0].path;
|
|
||||||
return environment.API_URL + `/media/entries/posters/preview/${name}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// * No local poster available, Use TMDB poster
|
// // * No poster found, use default poster image as a last stand
|
||||||
if (entry.poster_path)
|
// return 'assets/images/default/default-poster.png';
|
||||||
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 {
|
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 {
|
redirectTo(): void {
|
||||||
this.router.navigate([`/collections/${this.list.id}`]);
|
this.router.navigate([`/collections/${this.collection.id}`]);
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteList() {
|
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="card-body p-0">
|
||||||
|
|
||||||
<div class="collections-container">
|
<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>
|
@animateDestroy></app-userCollections-list-item>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+80
-5
@@ -1,7 +1,7 @@
|
|||||||
import { Component, OnInit } from '@angular/core';
|
import { Component, OnInit } from '@angular/core';
|
||||||
import { FormControl } from '@angular/forms';
|
import { FormControl } from '@angular/forms';
|
||||||
import { UserCollection } from '../../../../shared/models/userCollection.model';
|
import { UserCollection } from '../../../../shared/models/userCollection.model';
|
||||||
import { UserCollectionService } from '../../../../core/services/userCollection.service';
|
import { CollectionService } from '../../../../core/services/userCollection.service';
|
||||||
import {
|
import {
|
||||||
animate,
|
animate,
|
||||||
state,
|
state,
|
||||||
@@ -9,6 +9,8 @@ import {
|
|||||||
transition,
|
transition,
|
||||||
trigger,
|
trigger,
|
||||||
} from '@angular/animations';
|
} from '@angular/animations';
|
||||||
|
import { Entry } from '../../../../shared/models/entry.model';
|
||||||
|
import { environment } from '../../../../../environments/environment.prod';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-userCollections-page',
|
selector: 'app-userCollections-page',
|
||||||
@@ -32,7 +34,7 @@ export class UserCollectionsPageComponent implements OnInit {
|
|||||||
|
|
||||||
lockActions: boolean = false;
|
lockActions: boolean = false;
|
||||||
|
|
||||||
constructor(private collectionsService: UserCollectionService) {}
|
constructor(private collectionsService: CollectionService) {}
|
||||||
|
|
||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.getCollections();
|
this.getCollections();
|
||||||
@@ -43,9 +45,19 @@ export class UserCollectionsPageComponent implements OnInit {
|
|||||||
|
|
||||||
getCollections() {
|
getCollections() {
|
||||||
this.collectionsService.getCollections().subscribe({
|
this.collectionsService.getCollections().subscribe({
|
||||||
next: (l) => {
|
next: (result) => {
|
||||||
// console.log(`Loaded ${l.length} lists.`);
|
// 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.collectionsToShow = this.collections;
|
||||||
this.applyFilter();
|
this.applyFilter();
|
||||||
},
|
},
|
||||||
@@ -101,6 +113,69 @@ export class UserCollectionsPageComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
doShowCreate() {
|
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 {
|
.content-wrapper {
|
||||||
color: #212529;
|
color: #212529;
|
||||||
background: linear-gradient(
|
background: linear-gradient(to bottom,
|
||||||
to bottom,
|
rgba(255, 255, 255, 0.461) 10%,
|
||||||
rgba(255, 255, 255, 0.461) 10%,
|
#eff1f3 100%);
|
||||||
#eff1f3 100%
|
|
||||||
);
|
|
||||||
|
|
||||||
backdrop-filter: blur(10px);
|
backdrop-filter: blur(10px);
|
||||||
padding: 20px;
|
padding: 20px;
|
||||||
@@ -46,11 +44,9 @@
|
|||||||
|
|
||||||
[data-bs-theme="dark"] .content-wrapper {
|
[data-bs-theme="dark"] .content-wrapper {
|
||||||
color: #a7acb1;
|
color: #a7acb1;
|
||||||
background: linear-gradient(
|
background: linear-gradient(to bottom,
|
||||||
to bottom,
|
rgba(33, 37, 41, 0.7) 50%,
|
||||||
rgba(33, 37, 41, 0.7) 50%,
|
#181c1f 100%);
|
||||||
#181c1f 100%
|
|
||||||
);
|
|
||||||
|
|
||||||
background-color: rgba(33, 37, 41, 0.7);
|
background-color: rgba(33, 37, 41, 0.7);
|
||||||
border: 1px solid #181c1f;
|
border: 1px solid #181c1f;
|
||||||
@@ -181,3 +177,17 @@
|
|||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
border-radius: 0;
|
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">
|
<div class="d-flex justify-content-between align-items-center mb-2">
|
||||||
<h3>Watch History</h3>
|
<h3>Watch History</h3>
|
||||||
<div class="dropdown">
|
<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"
|
<button class="btn btn-sm btn-filter dropdown-toggle dropdown-toggle-nocaret bg-transparent" type="button"
|
||||||
data-bs-toggle="dropdown" aria-expanded="false">
|
data-bs-toggle="dropdown" aria-expanded="false">
|
||||||
<i class="bi bi-three-dots"></i>
|
<i class="bi bi-three-dots"></i>
|
||||||
@@ -226,7 +232,7 @@
|
|||||||
<ul class="dropdown-menu" style="cursor: pointer;">
|
<ul class="dropdown-menu" style="cursor: pointer;">
|
||||||
<li (click)="addEpisodeSeen()"><a class="dropdown-item">Add a watch date</a></li>
|
<li (click)="addEpisodeSeen()"><a class="dropdown-item">Add a watch date</a></li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div> -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card-body p-3">
|
<div class="card-body p-3">
|
||||||
@@ -280,6 +286,33 @@
|
|||||||
</div>
|
</div>
|
||||||
</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>
|
</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 { EpisodeSeenModalComponent } from '../../../shared/components/modals/episode-seen-modal/episode-seen-modal.component';
|
||||||
import { MediaModalComponent } from '../media-modal/media-modal.component';
|
import { MediaModalComponent } from '../media-modal/media-modal.component';
|
||||||
import { environment } from '../../../../environments/environment.prod';
|
import { environment } from '../../../../environments/environment.prod';
|
||||||
|
import { UserCollection } from '../../../shared/models/userCollection.model';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-entry-page',
|
selector: 'app-entry-page',
|
||||||
@@ -76,6 +77,14 @@ export class EntryPageComponent implements OnInit {
|
|||||||
this.entry = data['entry'] as Entry;
|
this.entry = data['entry'] as Entry;
|
||||||
this.entry.isInLibrary = true;
|
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) {
|
if (this.entry.is_tvseries) {
|
||||||
// ? sorting seasons
|
// ? sorting seasons
|
||||||
this.entry.seasons = this.entry.seasons.sort((a, b) => {
|
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() {
|
refrechEntry() {
|
||||||
this.lockActions = true;
|
this.lockActions = true;
|
||||||
this.entryService.refrechEntryById(this.entry.id).subscribe({
|
this.entryService.refrechEntryById(this.entry.id).subscribe({
|
||||||
@@ -417,7 +470,7 @@ export class EntryPageComponent implements OnInit {
|
|||||||
addEpisodeSeen() {
|
addEpisodeSeen() {
|
||||||
if (!this.entry) return;
|
if (!this.entry) return;
|
||||||
|
|
||||||
this.seenHistory[0]
|
this.seenHistory[0];
|
||||||
|
|
||||||
const dialogRef = this.dialog.open(EpisodeSeenModalComponent, {
|
const dialogRef = this.dialog.open(EpisodeSeenModalComponent, {
|
||||||
width: '360px',
|
width: '360px',
|
||||||
|
|||||||
@@ -38,7 +38,7 @@
|
|||||||
<div class="row row-cols-4 row-cols-md-6 g-4">
|
<div class="row row-cols-4 row-cols-md-6 g-4">
|
||||||
<div class="col" *ngFor="let media of filterMedia('poster')">
|
<div class="col" *ngFor="let media of filterMedia('poster')">
|
||||||
<div class="card image-hover-container">
|
<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">
|
<div class="image-hover-overlay">
|
||||||
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
||||||
<span class="material-symbols-outlined">delete</span>
|
<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="row row-cols-2 row-cols-md-4 g-4">
|
||||||
<div class="col" *ngFor="let media of filterMedia('backdrop')">
|
<div class="col" *ngFor="let media of filterMedia('backdrop')">
|
||||||
<div class="card image-hover-container">
|
<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">
|
<div class="image-hover-overlay">
|
||||||
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
||||||
<span class="material-symbols-outlined">delete</span>
|
<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="row row-cols-1 row-cols-md-2 g-4">
|
||||||
<div class="col" *ngFor="let media of filterMedia('logo')">
|
<div class="col" *ngFor="let media of filterMedia('logo')">
|
||||||
<div class="card image-hover-container">
|
<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">
|
<div class="image-hover-overlay">
|
||||||
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
<button class="btn btn-icon btn-icon-delete" (click)="deleteMedia(media)">
|
||||||
<span class="material-symbols-outlined">delete</span>
|
<span class="material-symbols-outlined">delete</span>
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export class MediaPageComponent implements OnInit {
|
|||||||
ngOnInit() {
|
ngOnInit() {
|
||||||
this.customMediaService.fetchCustomMedia().subscribe({
|
this.customMediaService.fetchCustomMedia().subscribe({
|
||||||
next: (result) => {
|
next: (result) => {
|
||||||
|
console.log(result);
|
||||||
this.customMedia = result;
|
this.customMedia = result;
|
||||||
console.log(result);
|
console.log(result);
|
||||||
},
|
},
|
||||||
@@ -32,8 +33,11 @@ export class MediaPageComponent implements OnInit {
|
|||||||
return this.customMedia.filter((media) => media.type == type);
|
return this.customMedia.filter((media) => media.type == type);
|
||||||
}
|
}
|
||||||
|
|
||||||
getPath(type: string, fileName: string) {
|
getPath(type: string, media: Media) {
|
||||||
return `${environment.API_URL}/media/entries/${type}/preview/${fileName}`;
|
let category = 'entries';
|
||||||
|
if (media.mediaable == 'collection') category = 'collections';
|
||||||
|
|
||||||
|
return `${environment.API_URL}/media/${category}/${type}/preview/${media.path}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
setTab(tab: string) {
|
setTab(tab: string) {
|
||||||
@@ -71,7 +75,10 @@ export class MediaPageComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
expandMedia(media: any) {
|
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');
|
window.open(fullSizePath, '_blank');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -1,7 +1,7 @@
|
|||||||
import { Component, Inject, Input, OnInit, ViewChild } from '@angular/core';
|
import { Component, Inject, Input, OnInit, ViewChild } from '@angular/core';
|
||||||
import { FormControl } from '@angular/forms';
|
import { FormControl } from '@angular/forms';
|
||||||
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
|
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 { NotificationPopupComponent } from '../../notification-popup/notification-popup.component';
|
||||||
import { NotificationService } from '../../../services/notification.service';
|
import { NotificationService } from '../../../services/notification.service';
|
||||||
import { UserCollection } from '../../../models/userCollection.model';
|
import { UserCollection } from '../../../models/userCollection.model';
|
||||||
@@ -49,7 +49,7 @@ export class UserCollectionsModalComponent implements OnInit {
|
|||||||
constructor(
|
constructor(
|
||||||
public dialogRef: MatDialogRef<UserCollectionsModalComponent>,
|
public dialogRef: MatDialogRef<UserCollectionsModalComponent>,
|
||||||
@Inject(MAT_DIALOG_DATA) public data: any,
|
@Inject(MAT_DIALOG_DATA) public data: any,
|
||||||
private listService: UserCollectionService,
|
private listService: CollectionService,
|
||||||
private notificationService: NotificationService
|
private notificationService: NotificationService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { EntryRating } from './entryRating.model';
|
|||||||
import { EntrySeen } from './entrySeen.model';
|
import { EntrySeen } from './entrySeen.model';
|
||||||
import { Media } from './media.model';
|
import { Media } from './media.model';
|
||||||
import { Season } from './season.model';
|
import { Season } from './season.model';
|
||||||
|
import { UserCollection } from './userCollection.model';
|
||||||
|
|
||||||
export interface Entry {
|
export interface Entry {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -11,6 +12,7 @@ export interface Entry {
|
|||||||
entryRating: EntryRating;
|
entryRating: EntryRating;
|
||||||
entrySeen: EntrySeen[];
|
entrySeen: EntrySeen[];
|
||||||
seasons: Season[];
|
seasons: Season[];
|
||||||
|
collections: UserCollection[];
|
||||||
|
|
||||||
title: string;
|
title: string;
|
||||||
original_title: string;
|
original_title: string;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ export interface Media {
|
|||||||
id: number;
|
id: number;
|
||||||
|
|
||||||
entry_id: number;
|
entry_id: number;
|
||||||
|
mediaable: string;
|
||||||
|
mediaableId: number;
|
||||||
entry: Entry;
|
entry: Entry;
|
||||||
|
|
||||||
type: string;
|
type: string;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { CollectionEntry } from './dtos/collection-entry.dto';
|
import { CollectionEntry } from './dtos/collection-entry.dto';
|
||||||
|
import { Media } from './media.model';
|
||||||
import { UserCollectionEntry } from './userCollectionEntry.model';
|
import { UserCollectionEntry } from './userCollectionEntry.model';
|
||||||
|
|
||||||
export interface UserCollection {
|
export interface UserCollection {
|
||||||
@@ -12,6 +13,7 @@ export interface UserCollection {
|
|||||||
isUserCollection: boolean;
|
isUserCollection: boolean;
|
||||||
userRating: number;
|
userRating: number;
|
||||||
|
|
||||||
|
medias: Media[];
|
||||||
posterPath: string;
|
posterPath: string;
|
||||||
backdropPath: string;
|
backdropPath: string;
|
||||||
isLocal: boolean;
|
isLocal: boolean;
|
||||||
@@ -21,6 +23,12 @@ export interface UserCollection {
|
|||||||
changed: boolean;
|
changed: boolean;
|
||||||
isChecked: boolean;
|
isChecked: boolean;
|
||||||
|
|
||||||
|
// * Processed fields
|
||||||
|
mediasCount: number;
|
||||||
|
entriesCount: number;
|
||||||
|
selectedPoster: string;
|
||||||
|
selectedBackdrop: string;
|
||||||
|
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 2.0 KiB |
Reference in new issue
Block a user