87 lines
2.6 KiB
JavaScript
87 lines
2.6 KiB
JavaScript
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();
|