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
@@ -13,15 +13,21 @@ async function deleteMissingFilesEntries(dry = false) {
|
||||
const dataPath = await getMediaFolder();
|
||||
|
||||
// Handling different media types
|
||||
const mediaTypes = {
|
||||
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
||||
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
||||
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
|
||||
const mediaTypeFolder = {
|
||||
'entryposter': path.join(dataPath, 'images', 'entries', 'posters'),
|
||||
'entrylogo': path.join(dataPath, 'images', 'entries', 'logos'),
|
||||
'entrybackdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
|
||||
|
||||
'collectionposter': path.join(dataPath, 'images', 'collections', 'posters'),
|
||||
'collectionlogo': path.join(dataPath, 'images', 'collections', 'logos'),
|
||||
'collectionbackdrop': path.join(dataPath, 'images', 'collections', 'backdrops')
|
||||
};
|
||||
|
||||
let missingFiles = [];
|
||||
for (let i = 0; i < allMedia.length; i++) {
|
||||
let type = `${allMedia[i].type}`.replace("_preview", "");
|
||||
const filePath = path.join(mediaTypes[type], allMedia[i].path)
|
||||
const folderType = `${allMedia[i].mediaable}${allMedia[i].type.replace("_preview", "")}`;
|
||||
|
||||
const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path)
|
||||
if (!fs.existsSync(filePath)) {
|
||||
missingFiles.push(allMedia[i]);
|
||||
}
|
||||
@@ -33,40 +39,55 @@ async function deleteMissingFilesEntries(dry = false) {
|
||||
'backdrops': 0
|
||||
};
|
||||
|
||||
if (missingFiles.length == 0)
|
||||
return removed;
|
||||
// if (missingFiles.length == 0)
|
||||
// return removed;
|
||||
|
||||
for (let i = 0; i < missingFiles.length; i++) {
|
||||
removed[missingFiles[i].type] += 1;
|
||||
removed[missingFiles[i].type + 's'] += 1;
|
||||
if (!dry) missingFiles[i].destroy();
|
||||
}
|
||||
|
||||
|
||||
if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
||||
else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete orphan files from media folder data,
|
||||
* orphan files are files that exist in the `folder data`
|
||||
* but do not have an instance in the database
|
||||
* @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false`
|
||||
*/
|
||||
async function deleteOrphanFiles(dry = false) {
|
||||
// Getting the userDataPath to store the images
|
||||
const dataPath = getMediaFolder();
|
||||
|
||||
// ? Getting the path of all media files and putting them in an array
|
||||
const allMedia = (await Media.findAll()).map(m =>
|
||||
path.join(dataPath, 'images', 'entries', m.type + 's', m.path)
|
||||
);
|
||||
// const allMedia = (await Media.findAll()).map(m => {
|
||||
// if (m.mediaable == 'entry')
|
||||
// return path.join(dataPath, 'images', 'entries', m.type + 's', m.path)
|
||||
// else if (m.mediaable == 'collection')
|
||||
// return path.join(dataPath, 'images', 'collections', m.type + 's', m.path)
|
||||
// });
|
||||
|
||||
// ? Getting the name (without extention) of all media in database
|
||||
const allMedia = (await Media.findAll()).map(m => {
|
||||
return m.path.split('.')[0]
|
||||
});
|
||||
|
||||
|
||||
// ? Loop trough the files of the images folder and check
|
||||
// ? if a file doesnt exist in the allMedia array and mark it to delete
|
||||
const mediaTypeFolder = {
|
||||
'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
||||
'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
||||
'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
|
||||
|
||||
let orphanFiles = [];
|
||||
const mediaTypes = {
|
||||
'poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
||||
'logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
||||
'backdrop': path.join(dataPath, 'images', 'entries', 'backdrops')
|
||||
'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'),
|
||||
'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops')
|
||||
};
|
||||
|
||||
// * counter
|
||||
let removed = {
|
||||
'posters': 0,
|
||||
'logos': 0,
|
||||
@@ -74,19 +95,31 @@ async function deleteOrphanFiles(dry = false) {
|
||||
};
|
||||
|
||||
// Iterate over each media type directory and check for orphan files
|
||||
for (let type in mediaTypes) {
|
||||
const directory = mediaTypes[type];
|
||||
for (let folderType in mediaTypeFolder) {
|
||||
const directory = mediaTypeFolder[folderType];
|
||||
try {
|
||||
// ? getting all files inside that folder
|
||||
const files = await fsPromises.readdir(directory).then();
|
||||
// console.log(`${directory}, files count: ${files.length}`);
|
||||
|
||||
// Check each file in the directory
|
||||
for (let file of files) {
|
||||
const filePath = path.join(directory, file);
|
||||
// Check if the constructed file path exists in the allMedia array
|
||||
if (!allMedia.includes(filePath.replace("_preview", ""))) {
|
||||
// If not, delete the file
|
||||
// const filePath = path.join(directory, file);
|
||||
// // Check if the constructed file path exists in the allMedia array
|
||||
// // ? this step also takes into account preview files, by removing '_preview'
|
||||
// // ? and verifying if the file path is in database
|
||||
// const hasJpgFormat = allMedia.includes(filePath.replace("_preview.jpg", ".jpg"));
|
||||
// const hasPngFormat = allMedia.includes(filePath.replace("_preview.jpg", ".png"));
|
||||
// const hasGifFormat = allMedia.includes(filePath.replace("_preview.jpg", ".gif"));
|
||||
|
||||
// preparing the file name
|
||||
const fileName = file.split('.')[0].replace("_preview", "");
|
||||
const isInDatabase = allMedia.includes(fileName);
|
||||
|
||||
// if the file isn't in database even on other extentions then delete it
|
||||
if (!isInDatabase) {
|
||||
removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files
|
||||
if (!dry) await fsPromises.unlink(filePath);
|
||||
removed[type + 's']++; // Increment the count of removed files
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
@@ -6,6 +6,7 @@ const { v4: uuidv4 } = require('uuid');
|
||||
const { fetchEntryMedia } = require('./tmdbService');
|
||||
const { getSettings } = require('./settingsService');
|
||||
const sharp = require('sharp');
|
||||
const { logToFile } = require('./logService');
|
||||
|
||||
async function downloadImage(url, filePath) {
|
||||
const response = await axios({
|
||||
@@ -66,6 +67,41 @@ async function getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos'
|
||||
return downloadedImages;
|
||||
}
|
||||
|
||||
async function downloadCollectionMedia(collection) {
|
||||
if (!collection) return null;
|
||||
|
||||
// Local variables for this function invocation
|
||||
let downloadTasks = [];
|
||||
let downloadedImages = [];
|
||||
|
||||
createMediaFolders(); // Ensuring directories exist
|
||||
|
||||
// Getting the userDataPath to store the images
|
||||
const settings = getSettings();
|
||||
const dataPath = settings.userDataPath;
|
||||
|
||||
const hasPoster = collection.medias && collection.medias.filter((m) => m.type == 'poster').length != 0;
|
||||
if (collection.posterPath && !hasPoster) {
|
||||
const postersDir = path.join(dataPath, 'images', 'collections', 'posters')
|
||||
scheduleDownloads({ file_path: collection.posterPath }, 'poster', postersDir, downloadTasks, downloadedImages);
|
||||
}
|
||||
|
||||
const hasBackdrop = collection.medias && collection.medias.filter((m) => m.type == 'backdrop').length != 0;
|
||||
if (collection.backdropPath && !hasBackdrop) {
|
||||
const backdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops')
|
||||
scheduleDownloads({ file_path: collection.backdropPath }, 'backdrop', backdropsDir, downloadTasks, downloadedImages);
|
||||
}
|
||||
|
||||
// Wait for all downloads to complete
|
||||
await Promise.all(downloadTasks).then(() => {
|
||||
console.log('Downloaded images:', downloadedImages);
|
||||
}).catch(err => {
|
||||
console.error('Error downloading entry images:', err);
|
||||
});
|
||||
|
||||
return downloadedImages;
|
||||
}
|
||||
|
||||
// Utility to find the preferred media (English if available, otherwise the first one)
|
||||
function findPreferredMedia(mediaArray, preferredLanguage = 'en') {
|
||||
return mediaArray.find(media => media.iso_639_1 === preferredLanguage && !media.file_path.includes('.svg')) || mediaArray.find(media => !media.file_path.includes('.svg')) || mediaArray[0];
|
||||
@@ -76,25 +112,22 @@ function scheduleDownloads(media, mediaType, mediaDir, downloadTasks, downloaded
|
||||
const uniqueFilename = uuidv4();
|
||||
const extension = media.file_path.split('.').pop();
|
||||
|
||||
const originalUrl = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
||||
const originalFileName = `${uniqueFilename}.${extension}`;
|
||||
const originalFilePath = path.join(mediaDir, originalFileName);
|
||||
const url = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
||||
const filename = `${uniqueFilename}.${extension}`;
|
||||
const downloadPath = path.join(mediaDir, filename);
|
||||
|
||||
// Schedule download of the original image
|
||||
downloadTasks.push(
|
||||
downloadImage(originalUrl, originalFilePath)
|
||||
.then(() => downloadedImages.push({ type: mediaType, path: originalFileName }))
|
||||
.catch(err => console.error(`Error downloading ${mediaType}:`, err))
|
||||
);
|
||||
|
||||
const previewUrl = `https://image.tmdb.org/t/p/w300${media.file_path}`;
|
||||
const previewFileName = `${uniqueFilename}_preview.${extension}`;
|
||||
const previewFilePath = path.join(mediaDir, previewFileName);
|
||||
|
||||
// Schedule download of the preview image
|
||||
downloadTasks.push(
|
||||
downloadImage(previewUrl, previewFilePath)
|
||||
.catch(err => console.error(`Error downloading preview ${mediaType}:`, err))
|
||||
downloadImage(url, downloadPath)
|
||||
.then(() => {
|
||||
logToFile(`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`)
|
||||
downloadedImages.push({ type: mediaType, path: filename })
|
||||
})
|
||||
.catch(err => {
|
||||
logToFile(`Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`)
|
||||
logToFile(err)
|
||||
console.error(`Error downloading ${mediaType}:`, err)
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
@@ -105,6 +138,28 @@ function generatePreview(originalPath, previewPath, previewWidth, previewQuality
|
||||
.toFile(previewPath);
|
||||
}
|
||||
|
||||
function doGeneratePreview(fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80) {
|
||||
const dataPath = getSettings().userDataPath;
|
||||
const mediaPath = path.join(dataPath, 'images', fileCategory, fileType);
|
||||
|
||||
const originalPath = path.join(mediaPath, originalFileName);
|
||||
|
||||
const fileNameWithoutExt = originalFileName.split('.')[0];
|
||||
const previewFileName = fileNameWithoutExt + '_preview.jpg'
|
||||
const previewPath = path.join(mediaPath, previewFileName);
|
||||
|
||||
if (previewWidth == 0) {
|
||||
previewWidth = 342; // ? poster
|
||||
if (fileType == 'backdrops') previewWidth = 780;
|
||||
if (fileType == 'logos') previewWidth = 300;
|
||||
}
|
||||
|
||||
return sharp(originalPath)
|
||||
.resize({ width: previewWidth })
|
||||
.jpeg({ quality: previewQuality })
|
||||
.toFile(previewPath);
|
||||
}
|
||||
|
||||
function getMediaFolder() {
|
||||
return getSettings().userDataPath;
|
||||
}
|
||||
@@ -117,11 +172,13 @@ function createMediaFolders() {
|
||||
const backdropDir = path.join(dataPath, 'images', 'entries', 'backdrops');
|
||||
const logoDir = path.join(dataPath, 'images', 'entries', 'logos');
|
||||
const collectionsPostersDir = path.join(dataPath, 'images', 'collections', 'posters');
|
||||
const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops');
|
||||
|
||||
fs.mkdirSync(posterDir, { recursive: true });
|
||||
fs.mkdirSync(backdropDir, { recursive: true });
|
||||
fs.mkdirSync(logoDir, { recursive: true });
|
||||
fs.mkdirSync(collectionsPostersDir, { recursive: true });
|
||||
fs.mkdirSync(collectionsBackdropsDir, { recursive: true });
|
||||
|
||||
// console.log(`Created media folders.`);
|
||||
}
|
||||
@@ -130,5 +187,7 @@ module.exports = {
|
||||
getEntryMedia,
|
||||
createMediaFolders,
|
||||
getMediaFolder,
|
||||
generatePreview
|
||||
generatePreview,
|
||||
doGeneratePreview,
|
||||
downloadCollectionMedia
|
||||
};
|
||||
@@ -0,0 +1,142 @@
|
||||
const { Sequelize } = require("sequelize");
|
||||
const Entry = require("../../models/Entry");
|
||||
const EntryId = require("../../models/EntryId");
|
||||
const UserCollection = require("../../models/Collection");
|
||||
const { fetchCollectionData, fetchEntryData } = require("../tmdbService");
|
||||
const { downloadCollectionMedia, doGeneratePreview } = require("../mediaService");
|
||||
const Media = require("../../models/Media");
|
||||
const Collection = require("../../models/Collection");
|
||||
const { saveEntry } = require("./entryService");
|
||||
const { logToFile } = require("../logService");
|
||||
const EntryRating = require("../../models/EntryRating");
|
||||
const Season = require("../../models/Season");
|
||||
const Genre = require("../../models/Genre");
|
||||
const UserCollectionEntry = require("../../models/UserCollectionEntry");
|
||||
|
||||
/**
|
||||
* Creates or updates an official collection,
|
||||
* it also create an association to all related library entries
|
||||
* @collection_tmdbId tmdb id of the collection
|
||||
*/
|
||||
async function upsertOfficialCollection(collection_tmdbId) {
|
||||
let collectionData = await fetchCollectionData(collection_tmdbId);
|
||||
|
||||
// * 1 - collection info
|
||||
const [oldCollection, createdCollection] = await UserCollection.findOrCreate({
|
||||
where: { tmdbId: collectionData.id },
|
||||
defaults: {
|
||||
name: collectionData.name,
|
||||
posterPath: collectionData.poster_path,
|
||||
backdropPath: collectionData.backdrop_path,
|
||||
description: collectionData.overview
|
||||
},
|
||||
include: [{ model: Media, as: 'medias' }]
|
||||
});
|
||||
|
||||
// * 2 - collection entries
|
||||
let collection = oldCollection || createdCollection;
|
||||
if (collection) {
|
||||
const partIds = collectionData.parts.map(part => part.id);
|
||||
|
||||
const entries = await Entry.findAll({
|
||||
include: [{
|
||||
model: EntryId,
|
||||
as: 'entryId',
|
||||
where: {
|
||||
tmdb_id: {
|
||||
[Sequelize.Op.in]: partIds
|
||||
}
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
await collection.setEntries(entries);
|
||||
|
||||
// * 3 - collection media
|
||||
// ? downloading
|
||||
const downloadedImages = await downloadCollectionMedia(collection);
|
||||
|
||||
// ? generating preview & inserting data
|
||||
for (const image of downloadedImages) {
|
||||
// ? generating preview
|
||||
doGeneratePreview('collections', image.type + 's', image.path).then((result) => {
|
||||
const msg = `Collection Service | Generated Collection Preview`;
|
||||
console.log(msg);
|
||||
logToFile(msg);
|
||||
}).catch((err) => {
|
||||
const msg = `Collection Service | Error Generating Collection Preview`;
|
||||
console.log(msg);
|
||||
console.log(err);
|
||||
logToFile(msg);
|
||||
logToFile(err);
|
||||
});
|
||||
|
||||
// ? inserting data
|
||||
await Media.create({
|
||||
mediaable: 'collection',
|
||||
mediaableId: collection.id,
|
||||
type: image.type,
|
||||
path: image.path,
|
||||
isLocal: true,
|
||||
isSelected: true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return await Collection.findByPk(collection.id, {
|
||||
include: [{
|
||||
model: Entry,
|
||||
as: 'entries',
|
||||
include: [
|
||||
{ model: EntryId, as: 'entryId' },
|
||||
{ model: EntryRating, as: 'entryRating' },
|
||||
{ model: Season, as: 'seasons' },
|
||||
{ model: Media, as: 'medias' },
|
||||
{ model: Genre, as: 'genres' },
|
||||
],
|
||||
through: {
|
||||
model: UserCollectionEntry,
|
||||
attributes: ['order'], // attributes (to include) from the join model
|
||||
},
|
||||
}],
|
||||
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
|
||||
});;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the other parts of the collection to the library
|
||||
* @collectionId id of the collection
|
||||
*/
|
||||
async function getCollectionParts(collectionId) {
|
||||
const collection = await Collection.findByPk(collectionId);
|
||||
const collectionData = await fetchCollectionData(collection.tmdbId);
|
||||
|
||||
const partIds = collectionData.parts.map(part => part.id);
|
||||
|
||||
const entries = await Entry.findAll({
|
||||
include: [{
|
||||
model: EntryId,
|
||||
as: 'entryId',
|
||||
where: {
|
||||
tmdb_id: {
|
||||
[Sequelize.Op.in]: partIds
|
||||
}
|
||||
}
|
||||
}]
|
||||
});
|
||||
|
||||
collectionData.parts.forEach(async (part) => {
|
||||
if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) {
|
||||
const isTvSeries = false;
|
||||
const entryData = await fetchEntryData(part.id, isTvSeries);
|
||||
const entry = await saveEntry(entryData);
|
||||
|
||||
await collection.addEntries([entry.id]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
upsertOfficialCollection,
|
||||
getCollectionParts,
|
||||
}
|
||||
@@ -1,3 +1,14 @@
|
||||
const moment = require('../../utils/moment.js');
|
||||
|
||||
const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js');
|
||||
const { getEntryMedia, doGeneratePreview } = require('../mediaService.js');
|
||||
const { logToFile } = require('../logService.js');
|
||||
|
||||
const NotFoundError = require('../../errors/NotFoundError.js');
|
||||
const InternalServerError = require('../../errors/InternalServerError.js');
|
||||
|
||||
const { ValidationError, Op } = require('sequelize');
|
||||
const Collection = require('../../models/Collection.js');
|
||||
const Entry = require('../../models/Entry.js')
|
||||
const EntryId = require('../../models/EntryId.js')
|
||||
const EntryRating = require('../../models/EntryRating.js');
|
||||
@@ -8,15 +19,6 @@ const Episode = require('../../models/Episode.js');
|
||||
const Media = require('../../models/Media.js');
|
||||
const Genre = require('../../models/Genre.js');
|
||||
|
||||
const NotFoundError = require('../../errors/NotFoundError.js');
|
||||
const InternalServerError = require('../../errors/InternalServerError.js');
|
||||
|
||||
const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js');
|
||||
const { getEntryMedia } = require('../mediaService.js');
|
||||
const { logToFile } = require('../logService.js');
|
||||
const { ValidationError, Op } = require('sequelize');
|
||||
const moment = require('../../utils/moment.js');
|
||||
|
||||
async function saveEntry(data) {
|
||||
try {
|
||||
if (data == null) return;
|
||||
@@ -132,7 +134,7 @@ async function saveEntry(data) {
|
||||
|
||||
// ? media
|
||||
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
|
||||
console.log(`entry service, downloaded images: `, downloadedImages)
|
||||
// console.log(`entry service, downloaded images: `, downloadedImages)
|
||||
for (const image of downloadedImages) {
|
||||
await Media.create({
|
||||
mediaable: 'entry',
|
||||
@@ -141,7 +143,9 @@ async function saveEntry(data) {
|
||||
path: image.path,
|
||||
isLocal: true,
|
||||
isSelected: true
|
||||
})
|
||||
});
|
||||
|
||||
doGeneratePreview('entries', image.type + 's', image.path);
|
||||
}
|
||||
|
||||
|
||||
@@ -348,27 +352,27 @@ async function refrechEntry(entryId) {
|
||||
}
|
||||
|
||||
// ? getting new data from TMDB
|
||||
const data = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
||||
if (data == null) {
|
||||
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
||||
if (entryData == null) {
|
||||
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
||||
}
|
||||
|
||||
// ! the refrech logic
|
||||
let newData = {
|
||||
title: data.title || data.name,
|
||||
original_title: data.original_title || data.original_name,
|
||||
release_date: data.release_date || data.first_air_date,
|
||||
release_status: data.status,
|
||||
runtime: data.runtime || null,
|
||||
title: entryData.title || entryData.name,
|
||||
original_title: entryData.original_title || entryData.original_name,
|
||||
release_date: entryData.release_date || entryData.first_air_date,
|
||||
release_status: entryData.status,
|
||||
runtime: entryData.runtime || null,
|
||||
|
||||
tagline: data.tagline || null,
|
||||
storyline: data.overview,
|
||||
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
||||
tagline: entryData.tagline || null,
|
||||
storyline: entryData.overview,
|
||||
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
|
||||
|
||||
status: data.status,
|
||||
status: entryData.status,
|
||||
|
||||
poster_path: data.poster_path,
|
||||
banner_path: data.backdrop_path,
|
||||
poster_path: entryData.poster_path,
|
||||
banner_path: entryData.backdrop_path,
|
||||
|
||||
last_fetch: new Date()
|
||||
};
|
||||
@@ -378,17 +382,17 @@ async function refrechEntry(entryId) {
|
||||
// * updating ids
|
||||
// TODO: get more ids
|
||||
await oldEntry.entryId.update({
|
||||
imdb_id: data.imdb_id,
|
||||
imdb_id: entryData.imdb_id,
|
||||
});
|
||||
|
||||
// * updating ratings
|
||||
await oldEntry.entryRating.update({
|
||||
tmdb_rating: data.vote_average
|
||||
tmdb_rating: entryData.vote_average
|
||||
});
|
||||
|
||||
// * updating genres
|
||||
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
||||
data.genres.forEach(async (genre) => {
|
||||
entryData.genres.forEach(async (genre) => {
|
||||
// if the entry already has this genre then skip
|
||||
if (currentGenresIds.includes(genre.id)) return;
|
||||
|
||||
@@ -406,9 +410,9 @@ async function refrechEntry(entryId) {
|
||||
// ? and atleast 48 hours has passed
|
||||
|
||||
// * Update or insert seasons for the entry
|
||||
for (const season of data.seasons) {
|
||||
for (const season of entryData.seasons) {
|
||||
// fetch new season data from tmdb
|
||||
let seasonData = await fetchSeasonData(data.id, season.season_number);
|
||||
let seasonData = await fetchSeasonData(entryData.id, season.season_number);
|
||||
|
||||
// Fetch existing season if it exists (using tmdb_id)
|
||||
let existingSeason = await Season.findOne({
|
||||
@@ -498,32 +502,27 @@ async function refrechEntry(entryId) {
|
||||
|
||||
// * Media
|
||||
// ? Only fetch if a Poster, Backdrop or a Logo is missing
|
||||
// ? only get missing media types
|
||||
|
||||
// ? count media by type
|
||||
let availableMedia = {
|
||||
'posters': 0,
|
||||
'logos': 0,
|
||||
'backdrops': 0
|
||||
};
|
||||
for (let i = 0; i < oldEntry.medias.length; i++) {
|
||||
availableMedia[oldEntry.medias[i].type + 's'] += 1;
|
||||
}
|
||||
|
||||
// ? if the count of a media type == 0, the add the type to mediaToGet
|
||||
let mediaToGet = [];
|
||||
for (let key in availableMedia) {
|
||||
if (availableMedia[key] == 0) mediaToGet.push(key);
|
||||
}
|
||||
|
||||
let downloadedImages;
|
||||
if (oldEntry.medias.length < 3) {
|
||||
// ? if no media is available, directly get all
|
||||
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries);
|
||||
} else {
|
||||
// ? only get missing media types
|
||||
let availableMedia = {
|
||||
'posters': 0,
|
||||
'logos': 0,
|
||||
'backdrops': 0
|
||||
};
|
||||
|
||||
// ? count media by type
|
||||
for (let i = 0; i < oldEntry.medias.length; i++) {
|
||||
availableMedia[oldEntry.medias[i].type] += 1;
|
||||
}
|
||||
|
||||
// ? if the count of a media type == 0, the add the type to mediaToGet
|
||||
let mediaToGet = [];
|
||||
for (let key in availableMedia) {
|
||||
if (availableMedia[key] == 0) mediaToGet.push(availableMedia[key]);
|
||||
}
|
||||
|
||||
if (mediaToGet.length != 0) {
|
||||
downloadedImages = await getEntryMedia(data.id, oldEntry.is_tvseries, mediaToGet);
|
||||
}
|
||||
if (mediaToGet.length != 0) {
|
||||
downloadedImages = await getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
|
||||
}
|
||||
|
||||
if (downloadedImages) {
|
||||
@@ -539,6 +538,12 @@ async function refrechEntry(entryId) {
|
||||
}
|
||||
}
|
||||
|
||||
// ? fetch collection
|
||||
if (entryData.belongs_to_collection) {
|
||||
const collectionService = require('./collectionService.js');
|
||||
await collectionService.upsertOfficialCollection(entryData.belongs_to_collection.id);
|
||||
}
|
||||
|
||||
// + end of: refrech logic
|
||||
|
||||
// ! returning the refreshed entry
|
||||
@@ -548,6 +553,7 @@ async function refrechEntry(entryId) {
|
||||
{ model: EntrySeen, as: 'entrySeen' },
|
||||
{ model: Season, as: 'seasons' },
|
||||
{ model: Media, as: 'medias' },
|
||||
{ model: Collection, as: 'collections' },
|
||||
{
|
||||
model: Genre,
|
||||
as: 'genres',
|
||||
@@ -566,8 +572,8 @@ async function refrechEntry(entryId) {
|
||||
]
|
||||
});
|
||||
|
||||
const entryData = updatedEntry.get({ plain: true });
|
||||
entryData.genres = entryData.genres.map(genre => genre.name);
|
||||
const plainEntry = updatedEntry.get({ plain: true });
|
||||
plainEntry.genres = plainEntry.genres.map(genre => genre.name);
|
||||
|
||||
return entryData;
|
||||
}
|
||||
|
||||
@@ -12,8 +12,7 @@ const entryPicturesUpload = multer({
|
||||
if (file.fieldname == 'backdrop') folder = 'backdrops';
|
||||
if (file.fieldname == 'logo') folder = 'logos';
|
||||
|
||||
const settings = getSettings();
|
||||
const dataPath = settings.userDataPath;
|
||||
const dataPath = getSettings().userDataPath;
|
||||
|
||||
cb(null, path.join(dataPath, 'images', 'entries', folder));
|
||||
},
|
||||
@@ -25,7 +24,27 @@ const entryPicturesUpload = multer({
|
||||
})
|
||||
});
|
||||
|
||||
const collectionPicturesUpload = multer({
|
||||
storage:
|
||||
multer.diskStorage({
|
||||
destination: function (req, file, cb) {
|
||||
let folder = 'posters';
|
||||
if (file.fieldname == 'backdrop') folder = 'backdrops';
|
||||
if (file.fieldname == 'logo') folder = 'logos';
|
||||
|
||||
const dataPath = getSettings().userDataPath;
|
||||
|
||||
cb(null, path.join(dataPath, 'images', 'collections', folder));
|
||||
},
|
||||
filename: function (req, file, cb) {
|
||||
const uniqueFilename = uuidv4();
|
||||
const extension = file.originalname.split('.').pop();
|
||||
cb(null, `${uniqueFilename}.${extension}`);
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
entryPicturesUpload,
|
||||
collectionPicturesUpload,
|
||||
}
|
||||
Reference in new issue
Block a user