Backend: People & Media

- Added people manager
- Auto update non fully fetched people
- People media downloader
- Updated media controller to serve peoples profiles
- Config people media folders auto creation
This commit is contained in:
X4Lo committed 2025-07-12 02:54:18 +01:00
1 parent 367c9899a0
commit 9d8f2899d4
6 files changed
+120 -10

No files matched your search

+2 -2
View File
@@ -46,11 +46,11 @@ class MediaController {
getMedia(req, res, next) { getMedia(req, res, next) {
const { category, type, size, fileName } = req.params; const { category, type, size, fileName } = req.params;
if (!['entries', 'collections', 'franchises', 'seasons', 'episodes'].includes(category)) { if (!['entries', 'collections', 'franchises', 'seasons', 'episodes', 'peoples'].includes(category)) {
return res.status(404).send('Category Not Found'); return res.status(404).send('Category Not Found');
} }
if (!['backdrops', 'posters', 'logos', 'stills', 'others'].includes(type)) { if (!['backdrops', 'posters', 'logos', 'stills', 'profiles', 'others'].includes(type)) {
return res.status(404).send('Type Not Found'); return res.status(404).send('Type Not Found');
} }
+3 -2
View File
@@ -1,7 +1,8 @@
const peopleService = require("../services/peopleService"); const peopleService = require("../services/peopleService");
const { logToFile } = require("../services/logService"); const peopleManager = require("../services/peopleManager");
const _peopleService = peopleService; const _peopleService = peopleService;
const _peopleManager = peopleManager;
class PeopleController { class PeopleController {
constructor() { constructor() {
@@ -24,7 +25,7 @@ class PeopleController {
async getPersonById(req, res) { async getPersonById(req, res) {
const { id } = req.params; const { id } = req.params;
const person = await _peopleService.getPersonById(id); const person = await _peopleManager.getUpdatedPerson(id);
res.status(200).json(person); res.status(200).json(person);
} }
+1 -1
View File
@@ -84,7 +84,7 @@ class ConfigService {
const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops'); const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops');
const seasonsPostersDir = path.join(dataPath, 'images', 'seasons', 'posters'); const seasonsPostersDir = path.join(dataPath, 'images', 'seasons', 'posters');
const episodesStillsDir = path.join(dataPath, 'images', 'episodes', 'stills'); const episodesStillsDir = path.join(dataPath, 'images', 'episodes', 'stills');
const peopleProfilesDir = path.join(dataPath, 'images', 'people', 'profiles'); const peopleProfilesDir = path.join(dataPath, 'images', 'peoples', 'profiles');
fs.mkdirSync(posterDir, { recursive: true }); fs.mkdirSync(posterDir, { recursive: true });
fs.mkdirSync(backdropDir, { recursive: true }); fs.mkdirSync(backdropDir, { recursive: true });
+29 -2
View File
@@ -49,6 +49,35 @@ class MediaDownloaderService {
return downloadedImages; return downloadedImages;
} }
async downloadPersonMedia(person) {
if (!person) return null;
// Local variables for this function invocation
let downloadTasks = [];
let downloadedImages = [];
_configService.createMediaFolders(); // Ensuring directories exist
const dataPath = _configService.getSettings().userDataPath;
// Check if person already has a profile image
const hasProfile = person.medias && person.medias.filter((m) => m.type === 'profile').length !== 0;
if (person.profile_path && !hasProfile) {
const profilesDir = path.join(dataPath, 'images', 'peoples', 'profiles');
this.scheduleDownloads({ file_path: person.profile_path }, 'profile', profilesDir, 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)
findPreferredMedia(mediaArray, preferredLanguage = 'en') { 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];
@@ -94,7 +123,6 @@ class MediaDownloaderService {
}); });
} }
async downloadFile(url) { async downloadFile(url) {
const response = await axios({ const response = await axios({
url: url, url: url,
@@ -104,7 +132,6 @@ class MediaDownloaderService {
return response; return response;
} }
} }
module.exports = new MediaDownloaderService(); module.exports = new MediaDownloaderService();
+82
View File
@@ -0,0 +1,82 @@
const Media = require("../models/Media");
const InternalServerError = require("../errors/InternalServerError");
const NotFoundError = require("../errors/NotFoundError");
const { fetchPersonDetails } = require("./tmdbService");
const { logToFile } = require("./logService");
const peopleService = require("./peopleService.js");
const mediaDownloaderService = require("./mediaDownloaderService");
const mediaOptimizerService = require("./mediaOptimizerService.js");
const _peopleService = peopleService;
const _mediaDownloaderService = mediaDownloaderService;
const _mediaOptimizerService = mediaOptimizerService;
class PeopleManager {
constructor() {
if (!PeopleManager.instance) {
PeopleManager.instance = this;
}
return PeopleManager.instance;
}
async getUpdatedPerson(id) {
// * 1 - get person by id
let person = await _peopleService.getPersonById(id);
if (!person) {
throw new NotFoundError("Person not found");
}
// * 2 - check if person is not fully fetched
if (!person.fully_fetched) {
// * 3 - fetch person data from TMDB
const personData = await fetchPersonDetails(person.tmdb_id);
if (!personData) {
throw new InternalServerError(`Couldn't fetch data from TMDB for person with ID: ${id}`);
}
// * 4 - update person with fetched data
person = await _peopleService.updatePerson(id, personData);
}
person.fully_fetched = true;
person.last_fetch = new Date();
person.save();
// * 5 - download person media
// TODO: peopleManage: update the person media each year
if (!person.medias || person.medias.length === 0) {
const downloadedImages = await _mediaDownloaderService.downloadPersonMedia(person);
for (const image of downloadedImages) {
// ? generating preview
_mediaOptimizerService.doGeneratePreview('peoples', image.type + 's', image.path).then((result) => {
const msg = `People Service | Generated Person Preview`;
logToFile(msg);
}).catch((err) => {
const msg = `People Service | Error Generating Person Preview`;
logToFile(msg);
logToFile(err);
});
// ? inserting data
await Media.create({
mediaable: 'people',
mediaableId: person.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
});
}
}
// * 6 - return the person
return await _peopleService.getPersonById(id);
}
}
module.exports = new PeopleManager();
+3 -3
View File
@@ -124,12 +124,12 @@ async function fetchEntryCredits(tmdb_id, is_tvserie) {
/** /**
* Fetches detailed information about a person * Fetches detailed information about a person
* @param {number} person_id - The TMDB ID of the person * @param {number} tmdb_id - The TMDB ID of the person
* @returns {Promise<Object|null>} - The person data or null if there's an error * @returns {Promise<Object|null>} - The person data or null if there's an error
*/ */
async function fetchPersonDetails(person_id) { async function fetchPersonDetails(tmdb_id) {
try { try {
let url = `${TMDB_APIURL}person/${person_id}?api_key=${TMDB_APIKEY}&language=en-US&append_to_response=external_ids`; let url = `${TMDB_APIURL}person/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US&append_to_response=external_ids`;
logToFile(`Fetching Person Details From: ${url}`); logToFile(`Fetching Person Details From: ${url}`);
let data; let data;