134 lines
4.5 KiB
JavaScript
134 lines
4.5 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');
|
|
|
|
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;
|
|
}
|
|
|
|
// 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 originalUrl = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
|
const originalFileName = `${uniqueFilename}.${extension}`;
|
|
const originalFilePath = path.join(mediaDir, originalFileName);
|
|
|
|
// 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))
|
|
);
|
|
}
|
|
|
|
function generatePreview(originalPath, previewPath, previewWidth, previewQuality = 80) {
|
|
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');
|
|
|
|
fs.mkdirSync(posterDir, { recursive: true });
|
|
fs.mkdirSync(backdropDir, { recursive: true });
|
|
fs.mkdirSync(logoDir, { recursive: true });
|
|
fs.mkdirSync(collectionsPostersDir, { recursive: true });
|
|
|
|
// console.log(`Created media folders.`);
|
|
}
|
|
|
|
module.exports = {
|
|
getEntryMedia,
|
|
createMediaFolders,
|
|
getMediaFolder,
|
|
generatePreview
|
|
}; |