199 lines
6.8 KiB
JavaScript
199 lines
6.8 KiB
JavaScript
const axios = require('axios');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
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({
|
|
url: url,
|
|
method: 'GET',
|
|
responseType: 'stream'
|
|
});
|
|
|
|
const writer = fs.createWriteStream(filePath);
|
|
response.data.pipe(writer);
|
|
|
|
return new Promise((resolve, reject) => {
|
|
writer.on('finish', resolve);
|
|
writer.on('error', reject);
|
|
});
|
|
}
|
|
|
|
async function getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos', 'backdrops']) {
|
|
// Fetching entry media
|
|
let mediaData = await fetchEntryMedia(tmdb_id, is_tvserie);
|
|
if (mediaData == null) 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;
|
|
|
|
// Handling different media types
|
|
const mediaTypes = [
|
|
{ type: 'posters', dir: path.join(dataPath, 'images', 'entries', 'posters') },
|
|
{ type: 'logos', dir: path.join(dataPath, 'images', 'entries', 'logos') },
|
|
{ type: 'backdrops', dir: path.join(dataPath, 'images', 'entries', 'backdrops') }
|
|
];
|
|
|
|
mediaTypes.forEach(({ type, dir }) => {
|
|
if (!includes.includes(type)) return; // ? the media type is not requested
|
|
|
|
if (mediaData[type] && mediaData[type].length) {
|
|
const selectedMedia = findPreferredMedia(mediaData[type]);
|
|
if (selectedMedia) {
|
|
scheduleDownloads(selectedMedia, type.slice(0, -1), dir, 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;
|
|
}
|
|
|
|
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];
|
|
}
|
|
|
|
// Adjusted scheduleDownloads to accept local arrays
|
|
function scheduleDownloads(media, mediaType, mediaDir, downloadTasks, downloadedImages) {
|
|
const uniqueFilename = uuidv4();
|
|
const extension = media.file_path.split('.').pop();
|
|
|
|
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(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)
|
|
})
|
|
);
|
|
}
|
|
|
|
function generatePreview(originalPath, previewPath, previewWidth, previewQuality = 80) {
|
|
return sharp(originalPath)
|
|
.resize({ width: previewWidth })
|
|
.jpeg({ quality: 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;
|
|
}
|
|
|
|
if (fileType == 'logos') {
|
|
return sharp(originalPath)
|
|
.resize({ width: previewWidth })
|
|
.toFile(previewPath.replace('.jpg', '.png'));
|
|
} else {
|
|
return sharp(originalPath)
|
|
.resize({ width: previewWidth })
|
|
.jpeg({ quality: previewQuality })
|
|
.toFile(previewPath);
|
|
}
|
|
}
|
|
|
|
function getMediaFolder() {
|
|
return getSettings().userDataPath;
|
|
}
|
|
|
|
function createMediaFolders() {
|
|
const settings = getSettings();
|
|
const dataPath = settings.userDataPath;
|
|
|
|
const posterDir = path.join(dataPath, 'images', 'entries', 'posters');
|
|
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.`);
|
|
}
|
|
|
|
module.exports = {
|
|
getEntryMedia,
|
|
createMediaFolders,
|
|
getMediaFolder,
|
|
generatePreview,
|
|
doGeneratePreview,
|
|
downloadCollectionMedia
|
|
}; |