Normalize to double quotes across all files with Prettier

This commit is contained in:
X4Lo committed 2026-06-21 22:28:08 +01:00
1 parent 73bff72cec
commit a5659cf4c8
190 files changed
+9523 -8859

No files matched your search

+59 -47
View File
@@ -19,7 +19,6 @@ const _mediaDownloaderService = mediaDownloaderService;
const _mediaOptimizerService = mediaOptimizerService;
class CollectionManager {
constructor() {
if (!CollectionManager.instance) {
CollectionManager.instance = this;
@@ -43,7 +42,8 @@ class CollectionManager {
}
// * 2 - insert/update collection
const [oldCollection, createdCollection] = await _collectionService.createOrUpdateCollection(collectionData);
const [oldCollection, createdCollection] =
await _collectionService.createOrUpdateCollection(collectionData);
// * 3 - link related entries to the collection
let collection = oldCollection || createdCollection;
@@ -51,57 +51,62 @@ class CollectionManager {
throw new NotFoundError("Collection not found");
}
const partIds = collectionData.parts.map(part => part.id);
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
}
}
}]
include: [
{
model: EntryId,
as: "entryId",
where: {
tmdb_id: {
[Sequelize.Op.in]: partIds,
},
},
},
],
});
await collection.setEntries(entries);
// * 4 - download collection media
// ? downloading
const downloadedImages = await _mediaDownloaderService.downloadCollectionMedia(collection);
const downloadedImages =
await _mediaDownloaderService.downloadCollectionMedia(collection);
// ? generating preview & inserting data
for (const image of downloadedImages) {
// ? generating preview
_mediaOptimizerService.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);
});
// ? generating preview
_mediaOptimizerService
.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',
mediaable: "collection",
mediaableId: collection.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
})
isSelected: true,
});
}
// * 5 - return the collection
return await _collectionService.getCollectionById(collection.id);
}
/**
* Fetches the corresponding collection for a given entry (movie) if it is missing.
* If the entry belongs to a collection, the collection is fetched and saved.
@@ -118,15 +123,16 @@ class CollectionManager {
}
const oldEntry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' }
]
})
include: [{ model: EntryId, as: "entryId" }],
});
if (!oldEntry) {
throw new NotFoundError("Entry not found");
}
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
const entryData = await fetchEntryData(
oldEntry.entryId.tmdb_id,
oldEntry.is_tvseries,
);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
@@ -172,19 +178,21 @@ class CollectionManager {
// * 3 - fetch missing entries and save them and linked already
// * existing ones to the collection
const partIds = collectionData.parts.map(part => part.id);
const partIds = collectionData.parts.map((part) => part.id);
// ? get all the related entries that are already in the library
const entries = await Entry.findAll({
include: [{
model: EntryId,
as: 'entryId',
where: {
tmdb_id: {
[Sequelize.Op.in]: partIds
}
}
}]
include: [
{
model: EntryId,
as: "entryId",
where: {
tmdb_id: {
[Sequelize.Op.in]: partIds,
},
},
},
],
});
// ? link entries already existing in the library
@@ -194,8 +202,12 @@ class CollectionManager {
collectionData.parts.forEach(async (part) => {
if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) {
const isTvSeries = false;
const _entryManager = require('./entryManager.js');
const entry = await _entryManager.fetchAndSaveNewEntry(part.id, isTvSeries, false)
const _entryManager = require("./entryManager.js");
const entry = await _entryManager.fetchAndSaveNewEntry(
part.id,
isTvSeries,
false,
);
await collection.addEntries([entry.id]);
}
@@ -203,4 +215,4 @@ class CollectionManager {
}
}
module.exports = new CollectionManager();
module.exports = new CollectionManager();
+27 -25
View File
@@ -8,9 +8,7 @@ const Media = require("../models/Media");
const Season = require("../models/Season");
const UserCollectionEntry = require("../models/UserCollectionEntry");
class CollectionService {
constructor() {
if (!CollectionService.instance) {
CollectionService.instance = this;
@@ -22,12 +20,13 @@ class CollectionService {
const collections = await Collection.findAll({
include: [
{
model: Entry, as: 'entries',
include: { model: Media, as: 'medias' }
model: Entry,
as: "entries",
include: { model: Media, as: "medias" },
},
{ model: Media, as: 'medias' }
{ model: Media, as: "medias" },
],
order: [['name', 'ASC']]
order: [["name", "ASC"]],
});
return collections;
@@ -35,22 +34,26 @@ class CollectionService {
async getCollectionById(id) {
const collection = await Collection.findByPk(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
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
],
order: [
[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), "ASC"],
], // sort by 'order' in ascending order
});
return collection;
@@ -63,12 +66,11 @@ class CollectionService {
name: collectionData.name,
posterPath: collectionData.poster_path,
backdropPath: collectionData.backdrop_path,
description: collectionData.overview
description: collectionData.overview,
},
include: [{ model: Media, as: 'medias' }]
include: [{ model: Media, as: "medias" }],
});
}
}
module.exports = new CollectionService();
module.exports = new CollectionService();
+66 -32
View File
@@ -1,20 +1,20 @@
const fs = require('fs');
const path = require('path');
const fs = require("fs");
const path = require("path");
const defaultSettings = {
userDataPath: '',
tmdbApiUrl: '',
tmdbApiKey: '',
frontPort: '',
backPort: '',
portableMode: '',
userDataPath: "",
tmdbApiUrl: "",
tmdbApiKey: "",
frontPort: "",
backPort: "",
portableMode: "",
libraryViewMode: 'grid',
favoritViewMode: 'grid',
watchlistViewMode: 'grid',
CollectionsViewMode: 'grid',
CollectionItemsViewMode: 'grid',
episodesViewMode: 'grid'
libraryViewMode: "grid",
favoritViewMode: "grid",
watchlistViewMode: "grid",
CollectionsViewMode: "grid",
CollectionItemsViewMode: "grid",
episodesViewMode: "grid",
};
class ConfigService {
@@ -31,7 +31,7 @@ class ConfigService {
}
getSettingsFilePath() {
return path.join(this.getUserDataPath(), 'settings.json');
return path.join(this.getUserDataPath(), "settings.json");
}
getSettings() {
@@ -43,19 +43,22 @@ class ConfigService {
const parsedSettings = JSON.parse(settingsData);
return { ...defaultSettings, ...parsedSettings };
} catch (err) {
console.error('Error reading settings file:', err);
console.log('Creating default settings file...');
console.error("Error reading settings file:", err);
console.log("Creating default settings file...");
let newSettingsFile = { ...defaultSettings };
let defaultDataPath = path.join(this.getUserDataPath(), 'data')
let defaultDataPath = path.join(this.getUserDataPath(), "data");
newSettingsFile.userDataPath = defaultDataPath;
newSettingsFile.backPort = 4000;
fs.mkdirSync(defaultDataPath, { recursive: true });
fs.writeFileSync(settingsFilePath, JSON.stringify(newSettingsFile, null, 2));
console.log('Default settings file created.');
fs.writeFileSync(
settingsFilePath,
JSON.stringify(newSettingsFile, null, 2),
);
console.log("Default settings file created.");
return defaultSettings;
}
@@ -65,9 +68,16 @@ class ConfigService {
const settingsFilePath = this.getSettingsFilePath();
const oldSettings = this.getSettings();
let updatedSettings = { ...defaultSettings, ...oldSettings, ...newSettings };
let updatedSettings = {
...defaultSettings,
...oldSettings,
...newSettings,
};
fs.mkdirSync(updatedSettings.userDataPath, { recursive: true }); // making sure the newly set data path is created before saving the new config
fs.writeFileSync(settingsFilePath, JSON.stringify(updatedSettings, null, 2));
fs.writeFileSync(
settingsFilePath,
JSON.stringify(updatedSettings, null, 2),
);
}
getMediaFolder() {
@@ -77,14 +87,39 @@ class ConfigService {
const settings = this.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');
const seasonsPostersDir = path.join(dataPath, 'images', 'seasons', 'posters');
const episodesStillsDir = path.join(dataPath, 'images', 'episodes', 'stills');
const peopleProfilesDir = path.join(dataPath, 'images', 'peoples', 'profiles');
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",
);
const seasonsPostersDir = path.join(
dataPath,
"images",
"seasons",
"posters",
);
const episodesStillsDir = path.join(
dataPath,
"images",
"episodes",
"stills",
);
const peopleProfilesDir = path.join(
dataPath,
"images",
"peoples",
"profiles",
);
fs.mkdirSync(posterDir, { recursive: true });
fs.mkdirSync(backdropDir, { recursive: true });
@@ -103,10 +138,9 @@ class ConfigService {
getTmdbApiKey() {
return this.settings.tmdbApiKey;
}
}
// const instance = new ConfigService();
// Object.freeze(instance);
module.exports = new ConfigService();
module.exports = new ConfigService();
+12 -14
View File
@@ -1,6 +1,6 @@
const moment = require("../utils/moment");
const { Op } = require("sequelize")
const { Op } = require("sequelize");
const Episode = require("../models/Episode");
const Season = require("../models/Season");
const Entry = require("../models/Entry");
@@ -10,7 +10,6 @@ const Media = require("../models/Media");
const BadRequestError = require("../errors/BadRequestError");
class EpisodeService {
constructor() {
if (!EpisodeService.instance) {
EpisodeService.instance = this;
@@ -27,37 +26,37 @@ class EpisodeService {
throw new BadRequestError("end Date not provided");
}
const formatedStartDate = moment(startDate).format('YYYY-MM-DD');
const formatedEndDate = moment(endDate).format('YYYY-MM-DD');
const formatedStartDate = moment(startDate).format("YYYY-MM-DD");
const formatedEndDate = moment(endDate).format("YYYY-MM-DD");
// fetch episodes that aired within the current month, only from entries with showInCalendar enabled
const episodes = await Episode.findAll({
where: {
air_date: {
[Op.between]: [formatedStartDate, formatedEndDate]
[Op.between]: [formatedStartDate, formatedEndDate],
},
},
include: [
{
model: Season,
as: 'season',
as: "season",
include: {
model: Entry,
as: 'entry',
as: "entry",
where: { showInCalendar: true },
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryId, as: "entryId" },
{
model: Media,
as: 'medias',
as: "medias",
},
],
}
}
]
},
},
],
});
const modifiedEpisodes = episodes.map(episode => {
const modifiedEpisodes = episodes.map((episode) => {
const episodeJSON = episode.toJSON();
if (episodeJSON.season && episodeJSON.season.entry) {
episodeJSON.entry = episodeJSON.season.entry;
@@ -68,7 +67,6 @@ class EpisodeService {
return modifiedEpisodes;
}
}
module.exports = new EpisodeService();
+85 -64
View File
@@ -15,15 +15,13 @@ async function bulkImportMovies(movies) {
const waitTime = 10000;
let entries = [];
let overAllFetches = 0
let overAllFetches = 0;
let currenFetch = 0;
// ? gettings all entries from db
const entriesFromDb = await Entry.findAll({
include: [
{ model: EntryId, as: 'entryId' }
]
})
include: [{ model: EntryId, as: "entryId" }],
});
// ? creating a dict from the entries
const entriesDict = entriesFromDb.reduce((dict, entry) => {
@@ -32,20 +30,30 @@ async function bulkImportMovies(movies) {
}, {});
for (const movie of movies) {
if (entriesDict[movie.tmdbId]) {
console.log(`Entry already exists: ${entriesDict[movie.tmdbId].title} (${movie.tmdbId})`)
console.log(
`Entry already exists: ${entriesDict[movie.tmdbId].title} (${movie.tmdbId})`,
);
// ? adding date seen
await EntrySeen.destroy({ where: { entry_id: entriesDict[movie.tmdbId].id } });
await EntrySeen.create({ entry_id: entriesDict[movie.tmdbId].id, date_seen: movie.dateSeen, seen_with: "" });
await EntrySeen.destroy({
where: { entry_id: entriesDict[movie.tmdbId].id },
});
await EntrySeen.create({
entry_id: entriesDict[movie.tmdbId].id,
date_seen: movie.dateSeen,
seen_with: "",
});
// ? adding entry user rating
if (movie.userRating != 0) {
await EntryRating.update({ user_rating: movie.userRating }, {
where: {
entry_id: entriesDict[movie.tmdbId].id
}
});
await EntryRating.update(
{ user_rating: movie.userRating },
{
where: {
entry_id: entriesDict[movie.tmdbId].id,
},
},
);
}
} else {
const data = await fetchEntryData(movie.tmdbId, false);
@@ -55,20 +63,27 @@ async function bulkImportMovies(movies) {
const entry = await saveEntry(data);
// ? adding date seen
await EntrySeen.create({ entry_id: entry.id, date_seen: movie.dateSeen, seen_with: "" });
await EntrySeen.create({
entry_id: entry.id,
date_seen: movie.dateSeen,
seen_with: "",
});
// ? adding entry user rating
if (movie.userRating != 0) {
await EntryRating.update({ user_rating: movie.userRating }, {
where: {
entry_id: entry.id
}
});
await EntryRating.update(
{ user_rating: movie.userRating },
{
where: {
entry_id: entry.id,
},
},
);
}
entries.push(entry)
entries.push(entry);
// ? wait 100ms between each tmdb fetch
await new Promise(resolve => setTimeout(resolve, fetchInterval));
await new Promise((resolve) => setTimeout(resolve, fetchInterval));
console.log(`${currenFetch} imported id: ${movie.tmdbId}`);
currenFetch++;
overAllFetches++;
@@ -76,31 +91,28 @@ async function bulkImportMovies(movies) {
// ? stop 10 seconds after 35 tmdb fetch
if (currenFetch == maxFetches) {
console.log(`Now waiting ${waitTime / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
await new Promise((resolve) => setTimeout(resolve, waitTime));
currentFetch = 0;
}
}
};
}
return entries;
}
async function bulkImportTmdb(movies) {
const maxFetches = 35; // ! max fetch per 10 seconds
const fetchInterval = 500;
const waitTime = 10000;
let entries = [];
let overAllFetches = 0
let overAllFetches = 0;
let currentFetch = 0;
// ? gettings all entries from db
const entriesFromDb = await Entry.findAll({
include: [
{ model: EntryId, as: 'entryId' }
]
})
include: [{ model: EntryId, as: "entryId" }],
});
// ? creating a dict from the entries
const entriesDict = entriesFromDb.reduce((dict, entry) => {
@@ -112,7 +124,9 @@ async function bulkImportTmdb(movies) {
for (const movie of movies) {
if (entriesDict[movie]) {
console.log(`Entry already exists: ${entriesDict[movie].title} (${movie})`)
console.log(
`Entry already exists: ${entriesDict[movie].title} (${movie})`,
);
created.push(movie);
} else {
if (created.includes(movie)) continue; // * skip doubles
@@ -122,20 +136,21 @@ async function bulkImportTmdb(movies) {
console.log(`${currentFetch} data null for id: ${movie.id}`);
}
// ? saving the entry
const entry = await saveEntry(data);
entries.push(entry)
created.push(movie)
entries.push(entry);
created.push(movie);
currentFetch += data.seasons.length;
// TODO implement option like rating, dateseen...
// ? wait 100ms between each tmdb fetch
await new Promise(resolve => setTimeout(resolve, fetchInterval));
console.log(`${overAllFetches} (${currentFetch + 1}/${maxFetches}) imported ${entry.title}`);
await new Promise((resolve) => setTimeout(resolve, fetchInterval));
console.log(
`${overAllFetches} (${currentFetch + 1}/${maxFetches}) imported ${entry.title}`,
);
if (data.seasons.length)
console.log(`With ${data.seasons.length} season(s).`)
console.log(`With ${data.seasons.length} season(s).`);
currentFetch++;
overAllFetches++;
@@ -143,42 +158,40 @@ async function bulkImportTmdb(movies) {
// ? stop 10 seconds after 35 tmdb fetch
if (currentFetch >= maxFetches) {
console.log(`Now waiting ${waitTime / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
await new Promise((resolve) => setTimeout(resolve, waitTime));
currentFetch = 0;
}
}
};
}
return entries;
}
async function bulkImportEpisodes(episodesSeen) {
try {
// ! DANGER clearing old episode seen
await EpisodeSeen.destroy({
where: {
entry_id: {
[Op.ne]: 3
}
}
})
[Op.ne]: 3,
},
},
});
// ? gettings all entries from db
const entriesFromDb = await Entry.findAll({
where: {
is_tvseries: 1
is_tvseries: 1,
},
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryId, as: "entryId" },
{
model: Season, as: 'seasons', include:
[
{ model: Episode, as: 'episodes' }
]
}
]
})
model: Season,
as: "seasons",
include: [{ model: Episode, as: "episodes" }],
},
],
});
// ? creating two dictionnaries names & ids
const idsDict = entriesFromDb.reduce((dict, entry) => {
@@ -198,14 +211,16 @@ async function bulkImportEpisodes(episodesSeen) {
for (let i = 0; i < episodesSeen.length; i++) {
let theEntry;
if (episodesSeen[i].type == 'id') {
if (episodesSeen[i].type == "id") {
theEntry = idsDict[episodesSeen[i].id];
} else if (episodesSeen[i].type == 'title') {
} else if (episodesSeen[i].type == "title") {
theEntry = titlesDict[episodesSeen[i].title.toLowerCase()];
}
if (!theEntry) {
console.log(`No entry found for line ${i + 1} (${episodesSeen[i].id || episodesSeen[i].title})`);
console.log(
`No entry found for line ${i + 1} (${episodesSeen[i].id || episodesSeen[i].title})`,
);
continue;
}
@@ -221,18 +236,22 @@ async function bulkImportEpisodes(episodesSeen) {
episodes++;
let date_seen = episodesSeen[i].date_seen;
if (new Date(episodesSeen[i].date_seen) < new Date(episode.air_date)) {
date_seen = episode.air_date.toISOString().split('T')[0];
console.log(`Date seen changed for ${theEntry.title} S${episodesSeen[i].season}E${episodesSeen[i].episode} from ${episodesSeen[i].date_seen} to ${date_seen}`);
if (
new Date(episodesSeen[i].date_seen) < new Date(episode.air_date)
) {
date_seen = episode.air_date.toISOString().split("T")[0];
console.log(
`Date seen changed for ${theEntry.title} S${episodesSeen[i].season}E${episodesSeen[i].episode} from ${episodesSeen[i].date_seen} to ${date_seen}`,
);
}
let id = `${theEntry.id}${(episodesSeen[i].season + 0)}${episode.id}${date_seen.replace(/-/g, '')}`;
let id = `${theEntry.id}${episodesSeen[i].season + 0}${episode.id}${date_seen.replace(/-/g, "")}`;
if (!added[id]) {
await EpisodeSeen.create({
entry_id: theEntry.id,
episode_id: episode.id,
date_seen: date_seen,
seen_with: episodesSeen[i].seen_with
seen_with: episodesSeen[i].seen_with,
});
added[id] = true;
rows++;
@@ -243,11 +262,13 @@ async function bulkImportEpisodes(episodesSeen) {
}
}
console.log(`rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`)
console.log(
`rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`,
);
console.log(added);
return rows;
} catch (error) {
console.log(error)
console.log(error);
}
}
@@ -255,4 +276,4 @@ module.exports = {
bulkImportMovies,
bulkImportTmdb,
bulkImportEpisodes,
};
};
+8 -8
View File
@@ -1,14 +1,14 @@
// logService.js
const fs = require('fs');
const util = require('util');
const moment = require('../utils/moment');
const fs = require("fs");
const util = require("util");
const moment = require("../utils/moment");
// Convert fs.writeFile to a promise-based function
const writeFile = util.promisify(fs.writeFile);
// Ensure the log file exists and is accessible
const logFilePath = 'showy.log';
fs.open(logFilePath, 'a', (err, fd) => {
const logFilePath = "showy.log";
fs.open(logFilePath, "a", (err, fd) => {
if (err) {
console.error("Failed to open log file:", err);
} else {
@@ -21,10 +21,10 @@ fs.open(logFilePath, 'a', (err, fd) => {
// Asynchronous function to append a message to the log file
async function logToFile(message) {
try {
const time = moment().format('YYYY-MM-DD HH:mm:ss')
const time = moment().format("YYYY-MM-DD HH:mm:ss");
const formatedMsg = `[${time}] ${message}`;
console.log(formatedMsg);
await writeFile(logFilePath, formatedMsg + '\n', { flag: 'a' });
await writeFile(logFilePath, formatedMsg + "\n", { flag: "a" });
} catch (err) {
console.error("Failed to write to log file:", err);
}
@@ -32,4 +32,4 @@ async function logToFile(message) {
module.exports = {
logToFile,
};
};
+98 -42
View File
@@ -1,10 +1,10 @@
const path = require('path');
const fs = require('fs');
const { default: axios } = require('axios');
const { v4: uuidv4 } = require('uuid');
const path = require("path");
const fs = require("fs");
const { default: axios } = require("axios");
const { v4: uuidv4 } = require("uuid");
const { logToFile } = require("./logService");
const configService = require('./configService');
const configService = require("./configService");
const _configService = configService;
@@ -27,24 +27,52 @@ class MediaDownloaderService {
const dataPath = _configService.getSettings().userDataPath;
const hasPoster = collection.medias && collection.medias.filter((m) => m.type == 'poster').length != 0;
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')
this.scheduleDownloads({ file_path: collection.posterPath }, 'poster', postersDir, downloadTasks, downloadedImages);
const postersDir = path.join(
dataPath,
"images",
"collections",
"posters",
);
this.scheduleDownloads(
{ file_path: collection.posterPath },
"poster",
postersDir,
downloadTasks,
downloadedImages,
);
}
const hasBackdrop = collection.medias && collection.medias.filter((m) => m.type == 'backdrop').length != 0;
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')
this.scheduleDownloads({ file_path: collection.backdropPath }, 'backdrop', backdropsDir, downloadTasks, downloadedImages);
const backdropsDir = path.join(
dataPath,
"images",
"collections",
"backdrops",
);
this.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);
});
await Promise.all(downloadTasks)
.then(() => {
console.log("Downloaded images:", downloadedImages);
})
.catch((err) => {
console.error("Error downloading entry images:", err);
});
return downloadedImages;
}
@@ -61,32 +89,56 @@ class MediaDownloaderService {
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;
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);
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);
});
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)
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];
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
scheduleDownloads(media, mediaType, mediaDir, downloadTasks, downloadedImages) {
scheduleDownloads(
media,
mediaType,
mediaDir,
downloadTasks,
downloadedImages,
) {
const uniqueFilename = uuidv4();
const extension = media.file_path.split('.').pop();
const extension = media.file_path.split(".").pop();
const url = `https://image.tmdb.org/t/p/original${media.file_path}`;
const filename = `${uniqueFilename}.${extension}`;
@@ -96,42 +148,46 @@ class MediaDownloaderService {
downloadTasks.push(
this.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)
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);
}),
);
}
async downloadImage(url, filePath) {
const response = await axios({
url: url,
method: 'GET',
responseType: 'stream'
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);
writer.on("finish", resolve);
writer.on("error", reject);
});
}
async downloadFile(url) {
const response = await axios({
url: url,
method: 'GET',
responseType: 'stream'
method: "GET",
responseType: "stream",
});
return response;
}
}
module.exports = new MediaDownloaderService();
module.exports = new MediaDownloaderService();
+97 -57
View File
@@ -1,5 +1,5 @@
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const Entry = require("../models/Entry");
@@ -11,9 +11,9 @@ const tmdbService = require("./tmdbService");
const mediaService = require("./mediaService");
const mediaDownloaderService = require("./mediaDownloaderService");
const mediaOptimizerService = require("./mediaOptimizerService");
const Season = require('../models/Season');
const storageService = require('./storageService');
const Media = require('../models/Media');
const Season = require("../models/Season");
const storageService = require("./storageService");
const Media = require("../models/Media");
const _configService = configService;
const _mediaService = mediaService;
@@ -23,7 +23,6 @@ const _mediaDownloaderService = mediaDownloaderService;
const _storageService = storageService;
class MediaManager {
constructor() {
if (!MediaManager.instance) {
MediaManager.instance = this;
@@ -32,7 +31,6 @@ class MediaManager {
}
async saveMedia(entryId, files) {
if (!files) {
throw new BadRequestError("No media uploaded");
}
@@ -42,7 +40,9 @@ class MediaManager {
throw new NotFoundError("Entry not found");
}
const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]);
const fileType = ["poster", "backdrop", "logo"].find(
(type) => req.files[type],
);
if (!fileType) {
throw new BadRequestError("Invalid media type");
@@ -51,31 +51,38 @@ class MediaManager {
// * 1 - save the media into database
const file = req.files[fileType][0];
const createdMedia = await _mediaService.createMedia({
mediaable: 'entry',
mediaable: "entry",
mediaableId: id,
type: fileType,
path: file.filename,
isLocal: true,
isSelected: false,
isCustom: true
isCustom: true,
});
// * 2 - generating low resolution preview
_mediaOptimizerService.generatePreviewFiles('entries', fileType + 's', file.filename).then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
_mediaOptimizerService
.generatePreviewFiles("entries", fileType + "s", file.filename)
.then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
const msg = `Media Route | Generated Entry Preview`
logToFile(msg);
}).catch((err) => {
const msg = `Media Route | Error Generating Entry Preview`
logToFile(msg);
});
const msg = `Media Route | Generated Entry Preview`;
logToFile(msg);
})
.catch((err) => {
const msg = `Media Route | Error Generating Entry Preview`;
logToFile(msg);
});
return createdMedia;
}
async getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos', 'backdrops']) {
async getEntryMedia(
tmdb_id,
is_tvserie,
includes = ["posters", "logos", "backdrops"],
) {
// Fetching entry media
const mediaData = await _tmdbService.fetchEntryMedia(tmdb_id, is_tvserie);
if (!mediaData) {
@@ -93,28 +100,44 @@ class MediaManager {
// 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') }
{
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 = _mediaDownloaderService.findPreferredMedia(mediaData[type]);
const selectedMedia = _mediaDownloaderService.findPreferredMedia(
mediaData[type],
);
if (selectedMedia) {
_mediaDownloaderService.scheduleDownloads(selectedMedia, type.slice(0, -1), dir, downloadTasks, downloadedImages);
_mediaDownloaderService.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);
});
await Promise.all(downloadTasks)
.then(() => {
console.log("Downloaded images:", downloadedImages);
})
.catch((err) => {
console.error("Error downloading entry images:", err);
});
return downloadedImages;
}
@@ -125,23 +148,32 @@ class MediaManager {
const file = await _mediaDownloaderService.downloadFile(url);
const uniqueFilename = uuidv4();
const extension = season.poster_path.split('.').pop();
const extension = season.poster_path.split(".").pop();
const filename = `${uniqueFilename}.${extension}`;
const dataPath = _configService.getSettings().userDataPath;
const fullFilePath = path.join(dataPath, 'images', 'seasons', 'posters', filename)
const fullFilePath = path.join(
dataPath,
"images",
"seasons",
"posters",
filename,
);
_storageService.storeFile(file, fullFilePath).then(async () => {
await Media.create({
mediaable: 'season',
mediaableId: season.id,
type: 'poster',
path: filename,
isLocal: true,
isSelected: true
});
console.log(`File created for season: ${filename}`);
}).catch();
_storageService
.storeFile(file, fullFilePath)
.then(async () => {
await Media.create({
mediaable: "season",
mediaableId: season.id,
type: "poster",
path: filename,
isLocal: true,
isSelected: true,
});
console.log(`File created for season: ${filename}`);
})
.catch();
}
async getEpisodenMedia(episode) {
@@ -150,25 +182,33 @@ class MediaManager {
const file = await _mediaDownloaderService.downloadFile(url);
const uniqueFilename = uuidv4();
const extension = episode.still_path.split('.').pop();
const extension = episode.still_path.split(".").pop();
const filename = `${uniqueFilename}.${extension}`;
const dataPath = _configService.getSettings().userDataPath;
const fullFilePath = path.join(dataPath, 'images', 'episodes', 'stills', filename)
const fullFilePath = path.join(
dataPath,
"images",
"episodes",
"stills",
filename,
);
_storageService.storeFile(file, fullFilePath).then(async () => {
await Media.create({
mediaable: 'episode',
mediaableId: episode.id,
type: 'still',
path: filename,
isLocal: true,
isSelected: true
});
console.log(`File created for episode: ${filename}`);
}).catch();
_storageService
.storeFile(file, fullFilePath)
.then(async () => {
await Media.create({
mediaable: "episode",
mediaableId: episode.id,
type: "still",
path: filename,
isLocal: true,
isSelected: true,
});
console.log(`File created for episode: ${filename}`);
})
.catch();
}
}
module.exports = new MediaManager();
+34 -16
View File
@@ -1,12 +1,11 @@
const path = require('path');
const sharp = require('sharp');
const path = require("path");
const sharp = require("sharp");
const configService = require('./configService');
const configService = require("./configService");
const _configService = configService;
class MediaOptimizerService {
constructor() {
if (!MediaOptimizerService.instance) {
MediaOptimizerService.instance = this;
@@ -15,29 +14,44 @@ class MediaOptimizerService {
}
// todo rename this function to prepareAndGeneratePreview
doGeneratePreview(fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80) {
doGeneratePreview(
fileCategory,
fileType,
originalFileName,
previewWidth = 0,
previewQuality = 80,
) {
const dataPath = _configService.getSettings().userDataPath;
const mediaPath = path.join(dataPath, 'images', fileCategory, fileType);
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 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 == "backdrops") previewWidth = 780;
if (fileType == "logos") previewWidth = 300;
}
if (fileType == 'logos') {
return this.generatePreview(originalPath, previewPath.replace('.jpg', '.png'), previewWidth);
if (fileType == "logos") {
return this.generatePreview(
originalPath,
previewPath.replace(".jpg", ".png"),
previewWidth,
);
// return sharp(originalPath)
// .resize({ width: previewWidth })
// .toFile(previewPath.replace('.jpg', '.png'));
} else {
return this.generatePreview(originalPath, previewPath, previewWidth, previewQuality);
return this.generatePreview(
originalPath,
previewPath,
previewWidth,
previewQuality,
);
// return sharp(originalPath)
// .resize({ width: previewWidth })
// .jpeg({ quality: previewQuality })
@@ -45,13 +59,17 @@ class MediaOptimizerService {
}
}
generatePreview(originalPath, previewPath, previewWidth, previewQuality = 80) {
generatePreview(
originalPath,
previewPath,
previewWidth,
previewQuality = 80,
) {
return sharp(originalPath)
.resize({ width: previewWidth })
.jpeg({ quality: previewQuality })
.toFile(previewPath);
}
}
module.exports = new MediaOptimizerService();
module.exports = new MediaOptimizerService();
+1 -3
View File
@@ -1,7 +1,6 @@
const Media = require("../models/Media");
class MediaService {
constructor() {
if (!MediaService.instance) {
MediaService.instance = this;
@@ -14,7 +13,6 @@ class MediaService {
return media;
}
}
module.exports = new MediaService();
module.exports = new MediaService();
+167 -140
View File
@@ -1,23 +1,23 @@
const moment = require('../../utils/moment.js');
const moment = require("../../utils/moment.js");
const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js');
const { getEntryMedia, doGeneratePreview } = require('../mediaService.js');
const { logToFile } = require('../logService.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 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');
const Season = require('../../models/Season.js');
const EntryGenre = require('../../models/EntryGenre.js');
const EntrySeen = require('../../models/EntrySeen.js');
const Episode = require('../../models/Episode.js');
const Media = require('../../models/Media.js');
const Genre = require('../../models/Genre.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");
const Season = require("../../models/Season.js");
const EntryGenre = require("../../models/EntryGenre.js");
const EntrySeen = require("../../models/EntrySeen.js");
const Episode = require("../../models/Episode.js");
const Media = require("../../models/Media.js");
const Genre = require("../../models/Genre.js");
async function saveEntry(data) {
try {
@@ -35,7 +35,10 @@ async function saveEntry(data) {
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
is_tvseries: is_tvseries,
watchlist: true,
@@ -46,7 +49,7 @@ async function saveEntry(data) {
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date()
last_fetch: new Date(),
});
const savedEntry = await movie.save();
@@ -62,8 +65,8 @@ async function saveEntry(data) {
data.genres.forEach(async (genre) => {
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
entry_id: savedEntry.id,
});
});
// ? ratings
@@ -95,7 +98,7 @@ async function saveEntry(data) {
poster_path: seasonData.poster_path,
banner_path: null,
})
});
// * episodes
let episodes = [];
@@ -122,43 +125,41 @@ async function saveEntry(data) {
// TODO fetch cast
savedSeason.setDataValue('episodes', episodes);
seasons.push(savedSeason)
savedSeason.setDataValue("episodes", episodes);
seasons.push(savedSeason);
}
savedEntry.setDataValue('seasons', seasons);
savedEntry.setDataValue("seasons", seasons);
}
// + end of: seasons & episodes for tv series
// ? cast
// ? media
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
// console.log(`entry service, downloaded images: `, downloadedImages)
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaable: "entry",
mediaableId: savedEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
isSelected: true,
});
doGeneratePreview('entries', image.type + 's', image.path);
doGeneratePreview("entries", image.type + "s", image.path);
}
const currentGenresNames = await data.genres.map((genre) => genre.name);
const currentGenresNames = await data.genres.map(genre => genre.name);
savedEntry.setDataValue('entryId', ids);
savedEntry.setDataValue('entryRating', ratings);
savedEntry.setDataValue('genres', currentGenresNames);
savedEntry.setDataValue("entryId", ids);
savedEntry.setDataValue("entryRating", ratings);
savedEntry.setDataValue("genres", currentGenresNames);
return savedEntry;
} catch (error) {
console.log(`Error saving entry (in entry serive): `, error);
return null
return null;
}
}
@@ -171,7 +172,10 @@ async function updateEntry(oldEntry, data) {
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
status: data.status,
@@ -190,11 +194,11 @@ async function updateEntry(oldEntry, data) {
// update ratings
const ratings = await oldEntry.entryRating.update({
tmdb_rating: data.vote_average
tmdb_rating: data.vote_average,
});
// update genres
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
let currentGenresNames = [];
data.genres.forEach(async (genre) => {
// add genres names to an array so it can be returned with the entry object
@@ -206,12 +210,14 @@ async function updateEntry(oldEntry, data) {
// otherwise assign the genre to the entry
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
entry_id: savedEntry.id,
});
});
// fetch entry-seens
const entrySeens = await EntrySeen.findAll({ where: { entry_id: oldEntry.id } });
const entrySeens = await EntrySeen.findAll({
where: { entry_id: oldEntry.id },
});
// TODO: refrech seasons
if (oldEntry.is_tvseries) {
@@ -224,8 +230,8 @@ async function updateEntry(oldEntry, data) {
// Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({
where: {
tmdb_id: season.id
}
tmdb_id: season.id,
},
});
// If the season exists, update it; otherwise, create a new season
@@ -269,7 +275,7 @@ async function updateEntry(oldEntry, data) {
let existingEpisode = await Episode.findOne({
where: {
tmdb_id: episode.id,
}
},
});
// If the episode exists, update it; otherwise, create a new episode
@@ -309,19 +315,18 @@ async function updateEntry(oldEntry, data) {
}
// Update the episodes of the current season
existingSeason.setDataValue('episodes', updatedEpisodes);
existingSeason.setDataValue("episodes", updatedEpisodes);
updatedSeasons.push(existingSeason);
}
// Update the seasons of the movie
savedEntry.setDataValue('seasons', updatedSeasons);
savedEntry.setDataValue("seasons", updatedSeasons);
}
savedEntry.setDataValue('entryId', ids);
savedEntry.setDataValue('entryRating', ratings);
savedEntry.setDataValue('genres', currentGenresNames);
savedEntry.setDataValue('entrySeen', entrySeens);
savedEntry.setDataValue("entryId", ids);
savedEntry.setDataValue("entryRating", ratings);
savedEntry.setDataValue("genres", currentGenresNames);
savedEntry.setDataValue("entrySeen", entrySeens);
return savedEntry;
}
@@ -332,25 +337,24 @@ async function refrechEntry(entryId) {
// ! note: the includes are required for the update
const oldEntry = await Entry.findByPk(entryId, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
{ model: EntrySeen, as: "entrySeen" },
{ model: Season, as: "seasons" },
{ model: Media, as: "medias" },
{
model: Collection, as: 'collections',
include: [
{ model: Media, as: 'medias' }
]
model: Collection,
as: "collections",
include: [{ model: Media, as: "medias" }],
},
{
model: Genre,
as: 'genres',
}
as: "genres",
},
],
order: [
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
]
[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"], // Order the entry-seen list
],
});
if (!oldEntry) {
@@ -358,7 +362,10 @@ async function refrechEntry(entryId) {
}
// ? getting new data from TMDB
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
const entryData = await fetchEntryData(
oldEntry.entryId.tmdb_id,
oldEntry.is_tvseries,
);
if (entryData == null) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
@@ -373,14 +380,17 @@ async function refrechEntry(entryId) {
tagline: entryData.tagline || null,
storyline: entryData.overview,
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
country:
entryData.production_countries.length > 0
? entryData.production_countries[0].name
: null,
status: entryData.status,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date()
last_fetch: new Date(),
};
const savedEntry = await oldEntry.update(newData);
@@ -393,11 +403,11 @@ async function refrechEntry(entryId) {
// * updating ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
tmdb_rating: entryData.vote_average,
});
// * updating genres
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
entryData.genres.forEach(async (genre) => {
// if the entry already has this genre then skip
if (currentGenresIds.includes(genre.id)) return;
@@ -405,26 +415,28 @@ async function refrechEntry(entryId) {
// otherwise assign the genre to the entry
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
entry_id: savedEntry.id,
});
});
// * For TV-Series (Seasons & Episodes)
if (oldEntry.is_tvseries) {
// ? Only refrech if the series's status is not 'Ended'
// ? and atleast 48 hours has passed
// ? and atleast 48 hours has passed
// * Update or insert seasons for the entry
for (const season of entryData.seasons) {
// fetch new season data from tmdb
let seasonData = await fetchSeasonData(entryData.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({
where: {
tmdb_id: season.id
}
tmdb_id: season.id,
},
});
// If the season exists, update it; otherwise, create a new season
@@ -464,7 +476,7 @@ async function refrechEntry(entryId) {
let existingEpisode = await Episode.findOne({
where: {
tmdb_id: episode.id,
}
},
});
// If the episode exists, update it; otherwise, create a new episode
@@ -512,12 +524,12 @@ async function refrechEntry(entryId) {
// ? count media by type
let availableMedia = {
'posters': 0,
'logos': 0,
'backdrops': 0
posters: 0,
logos: 0,
backdrops: 0,
};
for (let i = 0; i < oldEntry.medias.length; i++) {
availableMedia[oldEntry.medias[i].type + 's'] += 1;
availableMedia[oldEntry.medias[i].type + "s"] += 1;
}
// ? if the count of a media type == 0, the add the type to mediaToGet
@@ -528,26 +540,32 @@ async function refrechEntry(entryId) {
let downloadedImages;
if (mediaToGet.length != 0) {
downloadedImages = await getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
downloadedImages = await getEntryMedia(
entryData.id,
oldEntry.is_tvseries,
mediaToGet,
);
}
if (downloadedImages) {
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaable: "entry",
mediaableId: oldEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
isSelected: true,
});
}
}
// ? fetch collection
if (entryData.belongs_to_collection) {
const collectionService = require('../collectionService.js');
await collectionService.createOrUpdateCollection(entryData.belongs_to_collection.id);
const collectionService = require("../collectionService.js");
await collectionService.createOrUpdateCollection(
entryData.belongs_to_collection.id,
);
}
// + end of: refrech logic
@@ -573,53 +591,49 @@ async function refrechEntry(entryId) {
const updatedEntry = await Entry.findByPk(entryId, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
{ model: EntrySeen, as: "entrySeen" },
{ model: Season, as: "seasons" },
{ model: Media, as: "medias" },
{
model: Collection, as: 'collections',
include: [
{ model: Media, as: 'medias' }
]
model: Collection,
as: "collections",
include: [{ model: Media, as: "medias" }],
},
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre ID
as: "genres",
attributes: ["name"], // Only fetch the genre ID
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
attributes: [], // Do not fetch any attributes from the join table
},
},
],
order: [
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
]
[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"], // Order the entry-seen list
],
});
const plainEntry = updatedEntry.get({ plain: true });
plainEntry.genres = plainEntry.genres.map(genre => genre.name);
plainEntry.genres = plainEntry.genres.map((genre) => genre.name);
return plainEntry;
}
/** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today
*/
*/
async function SyncSeriesData() {
const today = moment().format('YYYY-MM-DD');
const today = moment().format("YYYY-MM-DD");
const entries = await Entry.findAll({
where: {
is_tvseries: true,
autoSync: true,
last_fetch: {
[Op.ne]: today
[Op.ne]: today,
},
status: {
[Op.notIn]: [
'Ended',
'Canceled'
]
[Op.notIn]: ["Ended", "Canceled"],
},
},
});
@@ -627,7 +641,7 @@ async function SyncSeriesData() {
logToFile(`Started syncing ${entries.length} Tv-Series`);
const results = await Promise.all(
entries.map(entry => SyncSerieData(entry.id))
entries.map((entry) => SyncSerieData(entry.id)),
);
logToFile(`Syncing Tv-Series Finished`);
@@ -637,30 +651,31 @@ async function SyncSeriesData() {
async function SyncSerieData(entryId) {
const oldEntry = await Entry.findByPk(entryId, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
{ model: EntrySeen, as: "entrySeen" },
{ model: Season, as: "seasons" },
{ model: Media, as: "medias" },
{
model: Genre,
as: 'genres',
attributes: ['id'],
as: "genres",
attributes: ["id"],
through: {
attributes: []
}
}
]
attributes: [],
},
},
],
});
logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`)
logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`);
if (!oldEntry)
throw NotFoundError('Entry Not Found');
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!oldEntry) throw NotFoundError("Entry Not Found");
const entryData = await fetchEntryData(
oldEntry.entryId.tmdb_id,
oldEntry.is_tvseries,
);
if (!entryData)
throw new ValidationError(`Couldn't Fetch Entry Data`);
if (!entryData) throw new ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data
let newData = {
@@ -671,14 +686,17 @@ async function SyncSerieData(entryId) {
tagline: entryData.tagline || null,
storyline: entryData.overview,
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
country:
entryData.production_countries.length > 0
? entryData.production_countries[0].name
: null,
status: entryData.status,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date()
last_fetch: new Date(),
};
await oldEntry.update(newData);
@@ -691,30 +709,39 @@ async function SyncSerieData(entryId) {
// ! 3 - Ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
tmdb_rating: entryData.vote_average,
});
// ! 4 - Genres
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
entryData.genres.forEach(async (genre) => {
// ? only assing the genre if its not already asigned
if (!currentGenresIds.includes(genre.id)) {
await EntryGenre.create({
genre_id: genre.id,
entry_id: oldEntry.id
})
entry_id: oldEntry.id,
});
}
});
// ! 5 - Seasons
// ? only update the last seasons available + season 0 (specials)
if (oldEntry.is_tvseries) {
const latestAvailableSeason = await Math.max(...oldEntry.seasons.map(s => s.season_number));
const latestAvailableSeason = await Math.max(
...oldEntry.seasons.map((s) => s.season_number),
);
for (const season of entryData.seasons) {
if (season.season_number != 0 && season.season_number != latestAvailableSeason) continue;
if (
season.season_number != 0 &&
season.season_number != latestAvailableSeason
)
continue;
// ? fetch new season data from tmdb
let seasonData = await fetchSeasonData(oldEntry.entryId.tmdb_id, season.season_number);
let seasonData = await fetchSeasonData(
oldEntry.entryId.tmdb_id,
season.season_number,
);
// * find or create the season
const [oldSeason, createdSeason] = await Season.findOrCreate({
@@ -731,7 +758,7 @@ async function SyncSerieData(entryId) {
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
}
},
});
// ? if the season already exist then just update it with new data
@@ -769,7 +796,7 @@ async function SyncSerieData(entryId) {
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
}
},
});
// ? if the episode already exist then just update it with new data
@@ -802,4 +829,4 @@ module.exports = {
refrechEntry,
SyncSeriesData,
SyncSerieData,
}
};
@@ -1,43 +1,29 @@
const Entry = require('../../models/Entry.js')
const EntryId = require('../../models/EntryId.js')
const EntryRating = require('../../models/EntryRating.js');
const Season = require('../../models/Season.js');
const EntryGenre = require('../../models/EntryGenre.js');
const EntrySeen = require('../../models/EntrySeen.js');
const Entry = require("../../models/Entry.js");
const EntryId = require("../../models/EntryId.js");
const EntryRating = require("../../models/EntryRating.js");
const Season = require("../../models/Season.js");
const EntryGenre = require("../../models/EntryGenre.js");
const EntrySeen = require("../../models/EntrySeen.js");
async function saveSeason(entryId) {
// fetch data from tmdb
// save season to db
}
async function updateSeason(seasonId) {
// fetch season form db
// fetch data from tmdb
// update fields
// save
}
async function getSeason() {}
async function getSeason() {
}
async function deleteSeason() {
}
async function deleteSeason() {}
module.exports = {
saveSeason,
updateSeason,
getSeason,
deleteSeason,
}
};
+45 -48
View File
@@ -1,67 +1,64 @@
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const configService = require('./configService');
const multer = require("multer");
const { v4: uuidv4 } = require("uuid");
const path = require("path");
const configService = require("./configService");
// ? users
const entryPicturesUpload = multer({
storage:
multer.diskStorage({
destination: function (req, file, cb) {
let folder = 'posters';
if (file.fieldname == 'backdrop') folder = 'backdrops';
if (file.fieldname == 'logo') folder = 'logos';
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 = configService.getSettings().userDataPath;
const dataPath = configService.getSettings().userDataPath;
cb(null, path.join(dataPath, 'images', 'entries', folder));
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split('.').pop();
cb(null, `${uniqueFilename}.${extension}`);
}
})
cb(null, path.join(dataPath, "images", "entries", folder));
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split(".").pop();
cb(null, `${uniqueFilename}.${extension}`);
},
}),
});
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';
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 = configService.getSettings().userDataPath;
const dataPath = configService.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}`);
}
})
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}`);
},
}),
});
const peoplePicturesUpload = multer({
storage:
multer.diskStorage({
destination: function (req, file, cb) {
let folder = 'profiles';
const dataPath = configService.getSettings().userDataPath;
cb(null, path.join(dataPath, 'images', 'people', folder));
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split('.').pop();
cb(null, `${uniqueFilename}.${extension}`);
}
})
storage: multer.diskStorage({
destination: function (req, file, cb) {
let folder = "profiles";
const dataPath = configService.getSettings().userDataPath;
cb(null, path.join(dataPath, "images", "people", folder));
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split(".").pop();
cb(null, `${uniqueFilename}.${extension}`);
},
}),
});
module.exports = {
entryPicturesUpload,
collectionPicturesUpload,
peoplePicturesUpload,
}
};
+20 -19
View File
@@ -8,7 +8,6 @@ const Network = require("../models/Network");
const Season = require("../models/Season");
class NetworkService {
constructor() {
if (!NetworkService.instance) {
NetworkService.instance = this;
@@ -20,11 +19,12 @@ class NetworkService {
const networks = await Network.findAll({
include: [
{
model: Entry, as: 'entries',
include: { model: Media, as: 'medias' }
}
model: Entry,
as: "entries",
include: { model: Media, as: "medias" },
},
],
order: [['name', 'ASC']]
order: [["name", "ASC"]],
});
return networks;
@@ -32,17 +32,19 @@ class NetworkService {
async getNetworkById(id) {
const network = await Network.findByPk(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' },
]
}]
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" },
],
},
],
});
return network;
@@ -61,10 +63,9 @@ class NetworkService {
logoPath: networkData.logoPath,
posterPath: networkData.posterPath,
backdropPath: networkData.backdropPath,
}
},
});
}
}
module.exports = new NetworkService();
module.exports = new NetworkService();
+20 -16
View File
@@ -15,7 +15,6 @@ const _mediaDownloaderService = mediaDownloaderService;
const _mediaOptimizerService = mediaOptimizerService;
class PeopleManager {
constructor() {
if (!PeopleManager.instance) {
PeopleManager.instance = this;
@@ -36,7 +35,9 @@ class PeopleManager {
// * 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}`);
throw new InternalServerError(
`Couldn't fetch data from TMDB for person with ID: ${id}`,
);
}
// * 4 - update person with fetched data
@@ -50,25 +51,29 @@ class PeopleManager {
// * 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);
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);
});
// ? 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',
mediaable: "people",
mediaableId: person.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
isSelected: true,
});
}
}
@@ -76,7 +81,6 @@ class PeopleManager {
// * 6 - return the person
return await _peopleService.getPersonById(id);
}
}
module.exports = new PeopleManager();
module.exports = new PeopleManager();
+26 -24
View File
@@ -22,8 +22,8 @@ class PeopleService {
async getAllPeople(includeCrew = false, { page, limit, search } = {}) {
let where = {
where: {
cast_type: 'cast'
}
cast_type: "cast",
},
};
if (includeCrew) {
@@ -45,11 +45,11 @@ class PeopleService {
include: {
model: Entry,
as: "entry",
include: { model: Media, as: "medias" }
include: { model: Media, as: "medias" },
},
...where
...where,
},
{ model: Media, as: 'medias' }
{ model: Media, as: "medias" },
],
};
@@ -83,11 +83,11 @@ class PeopleService {
include: {
model: Entry,
as: "entry",
include: { model: Media, as: "medias" }
include: { model: Media, as: "medias" },
},
},
{ model: Media, as: 'medias' }
]
{ model: Media, as: "medias" },
],
});
if (!person) {
@@ -107,11 +107,11 @@ class PeopleService {
include: {
model: Entry,
as: "entry",
include: { model: Media, as: "medias" }
}
include: { model: Media, as: "medias" },
},
},
{ model: Media, as: 'medias' }
]
{ model: Media, as: "medias" },
],
});
return person;
@@ -120,13 +120,11 @@ class PeopleService {
async searchPeople(query) {
const people = await People.findAll({
where: {
name: { [Op.like]: `%${query}%` }
name: { [Op.like]: `%${query}%` },
},
order: [["popularity", "DESC"]],
limit: 20,
include: [
{ model: Media, as: 'medias' }
]
include: [{ model: Media, as: "medias" }],
});
return people;
}
@@ -134,7 +132,7 @@ class PeopleService {
async createPerson(personData) {
try {
const existingPerson = await People.findOne({
where: { tmdb_id: personData.tmdb_id }
where: { tmdb_id: personData.tmdb_id },
});
if (existingPerson) {
@@ -165,14 +163,16 @@ class PeopleService {
},
include: [
{
model: Credit, as: 'roles',
model: Credit,
as: "roles",
include: {
model: Entry, as: 'entry',
include: [{ model: Media, as: 'medias' }]
}
model: Entry,
as: "entry",
include: [{ model: Media, as: "medias" }],
},
},
{ model: Media, as: 'medias' }
]
{ model: Media, as: "medias" },
],
});
}
@@ -235,7 +235,9 @@ class PeopleService {
// Fetch person data from TMDB
const personData = await fetchPersonData(tmdbId);
if (!personData) {
throw new NotFoundError(`Person with TMDB ID ${tmdbId} not found in TMDB`);
throw new NotFoundError(
`Person with TMDB ID ${tmdbId} not found in TMDB`,
);
}
// Create new person in database
+4 -6
View File
@@ -1,5 +1,5 @@
const path = require('path');
const fs = require('fs');
const path = require("path");
const fs = require("fs");
const configService = require("./configService");
const tmdbService = require("./tmdbService");
@@ -14,7 +14,6 @@ const _mediaOptimizerService = mediaOptimizerService;
const _mediaDownloaderService = mediaDownloaderService;
class StorageService {
constructor() {
if (!StorageService.instance) {
StorageService.instance = this;
@@ -27,11 +26,10 @@ class StorageService {
file.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
writer.on("finish", resolve);
writer.on("error", reject);
});
}
}
module.exports = new StorageService();
+69 -75
View File
@@ -1,6 +1,6 @@
const axios = require('axios');
const { logToFile } = require('./logService');
const configService = require('./configService');
const axios = require("axios");
const { logToFile } = require("./logService");
const configService = require("./configService");
const TMDB_APIURL = configService.getTmdbApiUrl();
const TMDB_APIKEY = configService.getTmdbApiKey();
@@ -8,44 +8,41 @@ const TMDB_APIKEY = configService.getTmdbApiKey();
async function fetchEntryData(tmdb_id, is_tvserie) {
try {
let type = is_tvserie ? "tv" : "movie";
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`
logToFile(`Fetching Entry Data From: ${url}`)
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Entry Data From: ${url}`);
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`)
return console.log('Error fetching the data.')
};
data = response.data;
})
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log('Error fetching the entry data.', error)
console.log("Error fetching the entry data.", error);
return null;
}
}
async function fetchSeasonData(tmdbTvId, seasonNumber) {
// fetching the informations
try {
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`
logToFile(`Fetching Season Data From: ${url}`)
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Season Data From: ${url}`);
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`)
return console.log('Error fetching the data.')
};
data = response.data;
})
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log('Error fetching the data.')
console.log("Error fetching the data.");
return null;
}
}
@@ -53,42 +50,44 @@ async function fetchSeasonData(tmdbTvId, seasonNumber) {
async function fetchEntryMedia(tmdb_id, is_tvserie) {
try {
let type = is_tvserie ? "tv" : "movie";
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`
logToFile(`Fetching Entry Media Data From: ${url}`)
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`;
logToFile(`Fetching Entry Media Data From: ${url}`);
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`)
return console.log('Error fetching the data.')
};
data = response.data;
})
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log('Error fetching the entry media.', error)
console.log("Error fetching the entry media.", error);
return null;
}
}
async function fetchCollectionData(collectionId) {
try {
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`
logToFile(`Fetching Collection Data From: ${url}`)
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Collection Data From: ${url}`);
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) return console.log('Error fetching collection data from tmdb:', response);
data = response.data;
})
await axios.get(url).then((response) => {
if (response.status != 200)
return console.log(
"Error fetching collection data from tmdb:",
response,
);
data = response.data;
});
return data;
} catch (error) {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`)
return console.log('Error fetching the data.')
};
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
return null;
}
}
@@ -105,24 +104,23 @@ async function fetchEntryCredits(tmdb_id, is_tvserie) {
let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`;
if (is_tvserie) {
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`;
}
logToFile(`Fetching Entry Credits From: ${url}`);
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Credits From: ${url}`);
return console.log('Error fetching the credits data.');
};
data = response.data;
});
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Credits From: ${url}`);
return console.log("Error fetching the credits data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log('Error fetching the entry credits.', error);
console.log("Error fetching the entry credits.", error);
return null;
}
}
@@ -138,18 +136,17 @@ async function fetchPersonDetails(tmdb_id) {
logToFile(`Fetching Person Details From: ${url}`);
let data;
await axios.get(url)
.then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Person Details From: ${url}`);
return console.log('Error fetching the person data.');
};
data = response.data;
});
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Person Details From: ${url}`);
return console.log("Error fetching the person data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log('Error fetching the person details.', error);
console.log("Error fetching the person details.", error);
return null;
}
}
@@ -197,7 +194,7 @@ async function fetchUpcoming(page = 1) {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log('Error fetching upcoming movies.', error);
console.log("Error fetching upcoming movies.", error);
return null;
}
}
@@ -209,7 +206,7 @@ async function searchMulti(query, page = 1) {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log('Error searching TMDB.', error);
console.log("Error searching TMDB.", error);
return null;
}
}
@@ -221,7 +218,7 @@ async function searchPeople(query, page = 1) {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log('Error searching TMDB people.', error);
console.log("Error searching TMDB people.", error);
return null;
}
}
@@ -233,7 +230,7 @@ async function fetchPopularPeople(page = 1) {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log('Error fetching popular people.', error);
console.log("Error fetching popular people.", error);
return null;
}
}
@@ -245,7 +242,7 @@ async function fetchPersonCombinedCredits(tmdb_id) {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log('Error fetching person combined credits.', error);
console.log("Error fetching person combined credits.", error);
return null;
}
}
@@ -265,7 +262,4 @@ module.exports = {
searchMulti,
searchPeople,
fetchPopularPeople,
}
};