Major Backend Single Responsibility Update part 1

This commit is contained in:
X4Lo committed 2025-01-25 04:29:42 +01:00
1 parent 65177c7553
commit cbdffb21e3
41 files changed
+1723 -888

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
const { Sequelize } = require("sequelize");
const Collection = require("../models/Collection");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const Media = require("../models/Media");
const BadRequestError = require("../errors/BadRequestError");
const InternalServerError = require("../errors/InternalServerError");
const NotFoundError = require("../errors/NotFoundError");
const { fetchEntryData, fetchCollectionData } = require("./tmdbService");
const { logToFile } = require("./logService");
const mediaDownloaderService = require("./mediaDownloaderService");
const collectionService = require("./collectionService");
const mediaOptimizerService = require("./mediaOptimizerService.js");
const _collectionService = collectionService;
const _mediaDownloaderService = mediaDownloaderService;
const _mediaOptimizerService = mediaOptimizerService;
class CollectionManager {
constructor() {
if (!CollectionManager.instance) {
CollectionManager.instance = this;
}
return CollectionManager.instance;
}
/**
* Fetches a collection from TMDB, saves it, links related entries, downloads media, and generates previews.
*
* @param {number} collectionTMDBId - The TMDB ID of the collection to fetch.
* @throws {InternalServerError} If the collection data couldn't be fetched from TMDB.
* @throws {NotFoundError} If the collection is not found after creation/update.
* @returns {Promise<Object>} The updated collection object.
*/
async fetchAndSaveCollection(collectionTMDBId) {
// * 1 - fetch collection data
const collectionData = await fetchCollectionData(collectionTMDBId);
if (!collectionData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// * 2 - insert/update collection
const [oldCollection, createdCollection] = await _collectionService.createOrUpdateCollection(collectionData);
// * 3 - link related entries to the collection
let collection = oldCollection || createdCollection;
if (!collection) {
throw new NotFoundError("Collection not found");
}
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
}
}
}]
});
await collection.setEntries(entries);
// * 4 - download collection media
// ? downloading
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);
});
// ? inserting data
await Media.create({
mediaable: 'collection',
mediaableId: collection.id,
type: image.type,
path: image.path,
isLocal: 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.
*
* @param {number} id - The ID of the entry to search for.
* @throws {BadRequestError} If the entry ID is not provided.
* @throws {NotFoundError} If the entry is not found.
* @throws {InternalServerError} If entry data couldn't be fetched from TMDB.
* @returns {Promise<Object|null>} The collection object or null if the entry does not belong to any collection.
*/
async fetchCollectionByEntryId(id) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
const oldEntry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' }
]
})
if (!oldEntry) {
throw new NotFoundError("Entry not found");
}
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// ? entry doesn't belong to a collection
if (!entryData.belongs_to_collection) {
return null;
}
let collectionData = entryData.belongs_to_collection;
const collection = await this.fetchAndSaveCollection(collectionData.id);
return collection;
}
/**
* Fetches missing parts (entries) for an existing collection and updates its overview.
* Links new entries to the collection.
*
* @param {number} collectionId - The ID of the collection to update.
* @throws {BadRequestError} If the collection ID is not provided.
* @throws {NotFoundError} If the collection is not found.
* @throws {InternalServerError} If collection data couldn't be fetched from TMDB.
* @returns {Promise<void>} No return value.
*/
async getCollectionParts(collectionId) {
if (!collectionId) {
throw new BadRequestError("Collection id not provided");
}
// * 1 - check if collection with given id exists
const collection = await Collection.findByPk(collectionId);
if (!collection) {
throw new NotFoundError("Collection not found");
}
// * 2 - fetch collection data
const collectionData = await fetchCollectionData(collection.tmdbId);
if (!collectionData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// * 3 - fetch missing entries and save them and linked already
// * existing ones to the collection
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
}
}
}]
});
// ? link entries already existing in the library
await collection.setEntries(entries);
// ? fetch and save missing entries, then link them to the collection
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)
await collection.addEntries([entry.id]);
}
});
}
}
module.exports = new CollectionManager();
+57
View File
@@ -0,0 +1,57 @@
const { Sequelize } = require("sequelize");
const Collection = require("../models/Collection");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const EntryRating = require("../models/EntryRating");
const Genre = require("../models/Genre");
const Media = require("../models/Media");
const Season = require("../models/Season");
const UserCollectionEntry = require("../models/UserCollectionEntry");
class CollectionService {
constructor() {
if (!CollectionService.instance) {
CollectionService.instance = this;
}
return CollectionService.instance;
}
async getCollectionById(id) {
return 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
},
}],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});
}
async createOrUpdateCollection(collectionData) {
return await Collection.findOrCreate({
where: { tmdbId: collectionData.id },
defaults: {
name: collectionData.name,
posterPath: collectionData.poster_path,
backdropPath: collectionData.backdrop_path,
description: collectionData.overview
},
include: [{ model: Media, as: 'medias' }]
});
}
}
module.exports = new CollectionService();
+95
View File
@@ -0,0 +1,95 @@
const fs = require('fs');
const path = require('path');
const defaultSettings = {
userDataPath: '',
tmdbApiUrl: '',
tmdbApiKey: '',
frontPort: '',
backPort: '',
portableMode: '',
libraryViewMode: '',
favoritViewMode: '',
watchlistViewMode: '',
CollectionsViewMode: '',
CollectionItemsViewMode: '',
};
class ConfigService {
constructor() {
if (!ConfigService.instance) {
ConfigService.instance = this;
}
return ConfigService.instance;
}
getUserDataPath() {
return path.join(__dirname, '..', '..');
}
getSettingsFilePath() {
return path.join(this.getUserDataPath(), 'settings.json');
}
getSettings() {
const settingsFilePath = this.getSettingsFilePath();
try {
const settingsData = fs.readFileSync(settingsFilePath);
// console.log(`Loaded settings file.`);
return JSON.parse(settingsData);
} catch (err) {
console.error('Error reading settings file:', err);
console.log('Creating default settings file...');
let newSettingsFile = { ...defaultSettings };
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.');
return defaultSettings;
}
}
updateSettings(newSettings) {
const settingsFilePath = this.getSettingsFilePath();
const oldSettings = this.getSettings();
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));
}
getMediaFolder() {
return this.getSettings().userDataPath;
}
createMediaFolders() {
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');
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 });
}
}
// const instance = new ConfigService();
// Object.freeze(instance);
module.exports = new ConfigService();
+472
View File
@@ -0,0 +1,472 @@
const moment = require("../utils/moment.js");
const { Op } = require("sequelize");
const Entry = require("../models/Entry.js");
const Episode = require("../models/Episode.js");
const Season = require("../models/Season.js");
const EntryGenre = require("../models/EntryGenre.js");
const EntryId = require("../models/EntryId.js");
const EntryRating = require("../models/EntryRating.js");
const EntrySeen = require("../models/EntrySeen.js");
const Media = require("../models/Media.js");
const Genre = require("../models/Genre.js");
const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError.js");
const ValidationError = require("../errors/ValidationError.js");
const { fetchEntryData, fetchSeasonData } = require("./tmdbService.js");
const { logToFile } = require("./logService.js");
const collectionManager = require('./collectionManager.js');
const entryService = require("./entryService");
const mediaManager = require("./mediaManager.js");
const _collectionManager = collectionManager;
const _entryService = entryService;
const _mediaManager = mediaManager;
class EntryManager {
constructor() {
if (!EntryManager.instance) {
EntryManager.instance = this;
}
return EntryManager.instance;
}
// todo: change fetchEntryData to TMDBService.fetchEntryData()
async fetchAndSaveNewEntry(id, type, fetchCollection = true, plain = true) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
if (typeof type !== "boolean") {
throw new BadRequestError(`Invalid type: ${type}. Expected a boolean value.`);
}
// * 1 - fetch entry data
const entryData = await fetchEntryData(id, type);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// * 2 - insert the entry into db
const entry = await _entryService.createEntry(entryData, plain);
// * 3 - created the related collection
if (entryData.belongs_to_collection && fetchCollection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
}
return entry;
}
// todo: change fetchEntryData to TMDBService.fetchEntryData()
// todo: change fetchEntryData to TMDBService.fetchSeasonData()
async refrechEntryById(id, plain = true) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
// ? checking if the provied id is valid
// ! note: the includes are required for the update
const oldEntry = await _entryService.getEntryById(id, false);
if (!oldEntry) {
throw new NotFoundError("Entry not found");
}
// ? getting new data from TMDB
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (!entryData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// ! the refrech logic
let newData = {
title: entryData.title || entryData.name,
original_title: entryData.original_title || entryData.original_name,
release_date: entryData.release_date || entryData.first_air_date,
release_status: entryData.status,
runtime: entryData.runtime || null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
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()
};
const savedEntry = await _entryService.updateEntryById(id, newData, false);
// * updating ids
// TODO: get more ids
await oldEntry.entryId.update({
imdb_id: entryData.imdb_id,
});
// * updating ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
});
// * updating genres
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;
// otherwise assign the genre to the entry
await EntryGenre.create({
genre_id: genre.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
// * 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);
// Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({
where: {
tmdb_id: season.id
}
});
// If the season exists, update it; otherwise, create a new season
if (existingSeason) {
// Update existing season data
existingSeason.tmdb_id = seasonData.id;
existingSeason.name = seasonData.name;
existingSeason.overview = seasonData.overview;
existingSeason.episode_count = seasonData.episodes.length;
existingSeason.air_date = seasonData.air_date;
existingSeason.tmdb_rating = seasonData.vote_average;
existingSeason.poster_path = seasonData.poster_path;
existingSeason.banner_path = null;
// Save the updated season
await existingSeason.save();
} else {
// Create a new season
existingSeason = await Season.create({
tmdb_id: seasonData.id,
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
}
// * Update or insert episodes for the season
for (const episode of seasonData.episodes) {
// Fetch existing episode data if it exists
let existingEpisode = await Episode.findOne({
where: {
tmdb_id: episode.id,
}
});
// If the episode exists, update it; otherwise, create a new episode
if (existingEpisode) {
// Update existing episode data
existingEpisode.tmdb_id = episode.tmdb_id;
existingEpisode.name = episode.name;
existingEpisode.overview = episode.overview;
existingEpisode.episode_type = episode.episode_type;
existingEpisode.runtime = episode.runtime;
existingEpisode.air_date = episode.air_date;
existingEpisode.tmdb_rating = episode.vote_average;
existingEpisode.still_path = episode.still_path;
// Updated episode
await existingEpisode.save();
} else {
// Create a new episode
await Episode.create({
tmdb_id: episode.id,
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
}
}
}
}
// * Cast
// ? Only fetch if the cast count is 0 or less than max_cast
// TODO add cast refrech
// if (!oldEntry.casts || oldEntry.casts.length == 0 || oldEntry.casts.length < oldEntry.max_cast) {
// }
// * Media
// ? Only fetch if a Poster, Backdrop or a Logo is missing
// ? only get missing media types
// ? count media by type
let availableMedia = {
'posters': 0,
'logos': 0,
'backdrops': 0
};
for (let i = 0; i < oldEntry.medias.length; i++) {
availableMedia[oldEntry.medias[i].type + 's'] += 1;
}
// ? if the count of a media type == 0, the add the type to mediaToGet
let mediaToGet = [];
for (let key in availableMedia) {
if (availableMedia[key] == 0) mediaToGet.push(key);
}
let downloadedImages;
if (mediaToGet.length != 0) {
downloadedImages = await _mediaManager.getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
}
if (downloadedImages) {
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaableId: oldEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
});
}
}
// ? fetch collection
if (entryData.belongs_to_collection) {
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
}
// + end of: refrech logic
// ! returning the refreshed entry
const refreshedEntry = await _entryService.getEntryById(id, plain);
return refreshedEntry;
}
/** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today
*/
async SyncSeriesData() {
const today = moment().format('YYYY-MM-DD');
const entries = await Entry.findAll({
where: {
is_tvseries: true,
autoSync: true,
last_fetch: {
[Op.ne]: today
},
status: {
[Op.notIn]: [
'Ended',
'Canceled'
]
},
},
});
logToFile(`Started syncing ${entries.length} Tv-Series`);
const results = await Promise.all(
entries.map(entry => this.SyncSerieData(entry.id))
);
logToFile(`Syncing Tv-Series Finished`);
return results;
}
async 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: Genre,
as: 'genres',
attributes: ['id'],
through: {
attributes: []
}
}
]
});
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 (!entryData)
throw ValidationError(`Couldn't Fetch Entry Data`);
// ! 1 - Normal Data
let newData = {
title: entryData.title || entryData.name,
original_title: entryData.original_title || entryData.original_name,
release_date: entryData.release_date || entryData.first_air_date,
runtime: entryData.runtime || null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
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()
};
await oldEntry.update(newData);
// ! 2 - Ids
// TODO: get more ids
await oldEntry.entryId.update({
imdb_id: entryData.imdb_id,
});
// ! 3 - Ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average
});
// ! 4 - Genres
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
})
}
});
// ! 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));
for (const season of entryData.seasons) {
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);
// * find or create the season
const [oldSeason, createdSeason] = await Season.findOrCreate({
where: { tmdb_id: season.id },
defaults: {
tmdb_id: seasonData.id,
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
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
if (!createdSeason) {
await oldSeason.update({
tmdb_id: seasonData.id,
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
}
// * forging updated/created season into a variable
let existingSeason = oldSeason || createdSeason;
// ! 6 - Episodes
for (const episode of seasonData.episodes) {
// * find or create the episode
const [oldEpisode, createdEpisode] = await Episode.findOrCreate({
where: { tmdb_id: episode.id },
defaults: {
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
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
if (!createdEpisode) {
await oldEpisode.update({
tmdb_id: episode.id,
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
}
}
}
}
await oldEntry.reload();
return oldEntry;
}
}
module.exports = new EntryManager();
+308
View File
@@ -0,0 +1,308 @@
const Collection = require("../models/Collection");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const EntryRating = require("../models/EntryRating");
const EntrySeen = require("../models/EntrySeen");
const EntryGenre = require("../models/EntryGenre.js");
const Genre = require("../models/Genre");
const Media = require("../models/Media");
const Season = require("../models/Season");
const Episode = require("../models/Episode");
const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError");
const mediaOptimizerService = require("./mediaOptimizerService.js");
const mediaManager = require("./mediaManager.js");
const { fetchSeasonData } = require("./tmdbService.js");
const _mediaManager = mediaManager;
const _mediaOptimizerService = mediaOptimizerService;
class EntryService {
constructor() {
if (!EntryService.instance) {
EntryService.instance = this;
}
return EntryService.instance;
}
async getAllEntries() {
const entries = await Entry.findAll({
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Media, as: 'medias' },
{ model: Season, as: 'seasons' },
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre name
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
]
});
// converting genres from object list to string list
const entriesWithGenreNames = entries.map(entry => ({
...entry.get({ plain: true }),
genres: entry.genres.map(genre => genre.name) // Convert genre objects to string array
}));
return entriesWithGenreNames;
}
async getEntryById(id, plain = true) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
let entry = await Entry.findByPk(id, {
include: [
{ 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: Genre,
as: 'genres',
attributes: ['name', 'id'],
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
],
order: [
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
]
});
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found")
}
if (plain) {
const plainEntry = entry.get({ plain: true });
const genres = plainEntry.genres.map(genre => genre.name);
plainEntry.genres = genres;
return plainEntry;
} else {
return entry;
}
}
async createEntry(data, plain = true) {
// creating the object
var is_tvseries = data.release_date == null ? true : false;
let movie = Entry.build({
title: data.title || data.name,
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date,
release_status: data.status,
runtime: data.runtime || null,
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
is_tvseries: is_tvseries,
watchlist: true,
status: data.status,
genres: data.genre_ids,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date()
});
let savedEntry = await movie.save();
// ? ids
const ids = await EntryId.create({
entry_id: savedEntry.id,
tmdb_id: data.id,
imdb_id: data.imdb_id,
});
// ? genres
data.genres.forEach(async (genre) => {
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id
})
});
// ? ratings
const ratings = await EntryRating.create({
entry_id: savedEntry.id,
user_rating: 0,
tmdb_rating: data.vote_average,
});
// ! seasons & episodes for tv series
if (is_tvseries) {
// * seasons
let seasons = [];
for (const season of data.seasons) {
let seasonData = await fetchSeasonData(data.id, season.season_number);
const savedSeason = await Season.create({
tmdb_id: seasonData.id,
entry_id: savedEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
})
// * episodes
let episodes = [];
for (const episode of seasonData.episodes) {
const savedEpisode = await Episode.create({
tmdb_id: episode.id,
season_id: savedSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
episodes.push(savedEpisode);
}
// TODO fetch cast
savedSeason.setDataValue('episodes', episodes);
seasons.push(savedSeason)
}
savedEntry.setDataValue('seasons', seasons);
}
// + end of: seasons & episodes for tv series
// ? cast
// ? media
const downloadedImages = await _mediaManager.getEntryMedia(data.id, is_tvseries);
// console.log(`entry service, downloaded images: `, downloadedImages)
for (const image of downloadedImages) {
await Media.create({
mediaable: 'entry',
mediaableId: savedEntry.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
});
_mediaOptimizerService.doGeneratePreview('entries', image.type + 's', image.path);
}
// const currentGenresNames = await data.genres.map(genre => genre.name);
// savedEntry.setDataValue('entryId', ids);
// savedEntry.setDataValue('entryRating', ratings);
// savedEntry.setDataValue('genres', currentGenresNames);
savedEntry = await this.getEntryById(savedEntry.id, plain);
return savedEntry;
}
async updateEntryById(id, entryData, plain = true) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
// ? checking if the provied id is valid
const oldEntry = await Entry.findByPk(id);
if (!oldEntry) {
throw new NotFoundError("Entry with the provided id was not found")
}
await oldEntry.update(entryData);
const updatedEntry = await this.getEntryById(id, plain);
return updatedEntry;
}
async deleteEntryById(id) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
const deletedCount = await Entry.destroy({
where: { id: id }
});
if (deletedCount == 0) {
throw new NotFoundError("Entry with the provided id was not found")
}
return deletedCount;
}
async getEntrySeasons(id) {
if (!id) {
throw new BadRequestError("Entry id not provided");
}
const entry = await Entry.findByPk(id);
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found")
}
const seasons = await Season.findAll({
where: {
entry_id: id
},
attributes: ['id', 'season_number'],
include: [
{ model: Episode, as: 'episodes', attributes: ['id', 'episode_number'], }
],
order: [
['season_number', 'ASC'],
[{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'],
]
})
return seasons;
}
}
module.exports = new EntryService();
+9 -6
View File
@@ -1,16 +1,19 @@
const path = require('path');
const fsPromises = require('fs').promises;
const fs = require('fs');
const Media = require("../models/Media");
const { logToFile } = require('./logService');
const { getMediaFolder } = require('./mediaService');
const Media = require("../models/Media");
const { logToFile } = require('./logService');
const configService = require('./configService');
const _configService = configService;
async function deleteMissingFilesEntries(dry = false) {
const allMedia = await Media.findAll();
// Getting the userDataPath to store the images
const dataPath = await getMediaFolder();
const dataPath = await _configService.getMediaFolder();
// Handling different media types
const mediaTypeFolder = {
@@ -60,7 +63,7 @@ async function deleteMissingFilesEntries(dry = false) {
*/
async function deleteOrphanFiles(dry = false) {
// Getting the userDataPath to store the images
const dataPath = getMediaFolder();
const dataPath = _configService.getMediaFolder();
// ? Getting the path of all media files and putting them in an array
// const allMedia = (await Media.findAll()).map(m => {
@@ -104,7 +107,7 @@ async function deleteOrphanFiles(dry = false) {
// Check each file in the directory
for (let file of files) {
// const filePath = path.join(directory, file);
const filePath = path.join(directory, file);
// // Check if the constructed file path exists in the allMedia array
// // ? this step also takes into account preview files, by removing '_preview'
// // ? and verifying if the file path is in database
@@ -0,0 +1,98 @@
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 = configService;
class MediaDownloaderService {
constructor() {
if (!MediaDownloaderService.instance) {
MediaDownloaderService.instance = this;
}
return MediaDownloaderService.instance;
}
async downloadCollectionMedia(collection) {
if (!collection) return null;
// Local variables for this function invocation
let downloadTasks = [];
let downloadedImages = [];
_configService.createMediaFolders(); // Ensuring directories exist
const dataPath = _configService.getSettings().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')
this.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')
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);
});
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];
}
// Adjusted scheduleDownloads to accept local arrays
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(
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)
})
);
}
async 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);
});
}
}
module.exports = new MediaDownloaderService();
+118
View File
@@ -0,0 +1,118 @@
const path = require('path');
const Entry = require("../models/Entry");
const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError");
const configService = require("./configService");
const tmdbService = require("./tmdbService");
const mediaService = require("./mediaService");
const mediaDownloaderService = require("./mediaDownloaderService");
const mediaOptimizerService = require("./mediaOptimizerService");
const _configService = configService;
const _mediaService = mediaService;
const _tmdbService = tmdbService;
const _mediaOptimizerService = mediaOptimizerService;
const _mediaDownloaderService = mediaDownloaderService;
class MediaManager {
constructor() {
if (!MediaManager.instance) {
MediaManager.instance = this;
}
return MediaManager.instance;
}
async saveMedia(entryId, files) {
if (!files) {
throw new BadRequestError("No media uploaded");
}
const entry = await Entry.findByPk(entryId);
if (!entry) {
throw new NotFoundError("Entry not found");
}
const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]);
if (!fileType) {
throw new BadRequestError("Invalid media type");
}
// * 1 - save the media into database
const file = req.files[fileType][0];
const createdMedia = await _mediaService.createMedia({
mediaable: 'entry',
mediaableId: id,
type: fileType,
path: file.filename,
isLocal: true,
isSelected: false,
isCustom: true
});
// * 2 - generating low resolution preview
_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);
});
return createdMedia;
}
async getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos', 'backdrops']) {
// Fetching entry media
const mediaData = await _tmdbService.fetchEntryMedia(tmdb_id, is_tvserie);
if (!mediaData) {
throw new InternalServerError(`Counldn't fetch data from TMDB`);
}
// Local variables for this function invocation
let downloadTasks = [];
let downloadedImages = [];
_configService.createMediaFolders(); // Ensuring directories exist
// Getting the userDataPath to store the images
const dataPath = _configService.getSettings().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 = _mediaDownloaderService.findPreferredMedia(mediaData[type]);
if (selectedMedia) {
_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);
});
return downloadedImages;
}
}
module.exports = new MediaManager();
+57
View File
@@ -0,0 +1,57 @@
const path = require('path');
const sharp = require('sharp');
const configService = require('./configService');
const _configService = configService;
class MediaOptimizerService {
constructor() {
if (!MediaOptimizerService.instance) {
MediaOptimizerService.instance = this;
}
return MediaOptimizerService.instance;
}
// todo rename this function to prepareAndGeneratePreview
doGeneratePreview(fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80) {
const dataPath = _configService.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 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 sharp(originalPath)
// .resize({ width: previewWidth })
// .jpeg({ quality: previewQuality })
// .toFile(previewPath);
}
}
generatePreview(originalPath, previewPath, previewWidth, previewQuality = 80) {
return sharp(originalPath)
.resize({ width: previewWidth })
.jpeg({ quality: previewQuality })
.toFile(previewPath);
}
}
module.exports = new MediaOptimizerService();
+11 -190
View File
@@ -1,199 +1,20 @@
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const Media = require("../models/Media");
const { v4: uuidv4 } = require('uuid');
const { fetchEntryMedia } = require('./tmdbService');
const { getSettings } = require('./settingsService');
const sharp = require('sharp');
const { logToFile } = require('./logService');
class MediaService {
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);
}
constructor() {
if (!MediaService.instance) {
MediaService.instance = this;
}
});
// 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);
return MediaService.instance;
}
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);
async createMedia(data) {
const media = await Media.create(data);
return media;
}
// 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
};
module.exports = new MediaService();
@@ -1,142 +0,0 @@
const { Sequelize } = require("sequelize");
const Entry = require("../../models/Entry");
const EntryId = require("../../models/EntryId");
const UserCollection = require("../../models/Collection");
const { fetchCollectionData, fetchEntryData } = require("../tmdbService");
const { downloadCollectionMedia, doGeneratePreview } = require("../mediaService");
const Media = require("../../models/Media");
const Collection = require("../../models/Collection");
const { saveEntry } = require("./entryService");
const { logToFile } = require("../logService");
const EntryRating = require("../../models/EntryRating");
const Season = require("../../models/Season");
const Genre = require("../../models/Genre");
const UserCollectionEntry = require("../../models/UserCollectionEntry");
/**
* Creates or updates an official collection,
* it also create an association to all related library entries
* @collection_tmdbId tmdb id of the collection
*/
async function upsertOfficialCollection(collection_tmdbId) {
let collectionData = await fetchCollectionData(collection_tmdbId);
// * 1 - collection info
const [oldCollection, createdCollection] = await UserCollection.findOrCreate({
where: { tmdbId: collectionData.id },
defaults: {
name: collectionData.name,
posterPath: collectionData.poster_path,
backdropPath: collectionData.backdrop_path,
description: collectionData.overview
},
include: [{ model: Media, as: 'medias' }]
});
// * 2 - collection entries
let collection = oldCollection || createdCollection;
if (collection) {
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
}
}
}]
});
await collection.setEntries(entries);
// * 3 - collection media
// ? downloading
const downloadedImages = await downloadCollectionMedia(collection);
// ? generating preview & inserting data
for (const image of downloadedImages) {
// ? generating preview
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',
mediaableId: collection.id,
type: image.type,
path: image.path,
isLocal: true,
isSelected: true
})
}
}
return await Collection.findByPk(collection.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
},
}],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
});;
}
/**
* Adds the other parts of the collection to the library
* @collectionId id of the collection
*/
async function getCollectionParts(collectionId) {
const collection = await Collection.findByPk(collectionId);
const collectionData = await fetchCollectionData(collection.tmdbId);
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
}
}
}]
});
collectionData.parts.forEach(async (part) => {
if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) {
const isTvSeries = false;
const entryData = await fetchEntryData(part.id, isTvSeries);
const entry = await saveEntry(entryData);
await collection.addEntries([entry.id]);
}
});
}
module.exports = {
upsertOfficialCollection,
getCollectionParts,
}
@@ -326,6 +326,7 @@ async function updateEntry(oldEntry, data) {
return savedEntry;
}
// ! this will soon be removed to the new EntryService
async function refrechEntry(entryId) {
// ? checking if the provied id is valid
// ! note: the includes are required for the update
@@ -795,24 +796,10 @@ async function SyncSerieData(entryId) {
return oldEntry;
}
async function getEntry(id) {
return Entry.findByPk(id);
}
async function deleteEntry(id) {
await Entry.destroy({
where: {
id: id
}
});
}
module.exports = {
saveEntry,
updateEntry,
refrechEntry,
getEntry,
deleteEntry,
SyncSeriesData,
SyncSerieData,
}
+3 -3
View File
@@ -1,7 +1,7 @@
const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const { getSettings } = require('./settingsService');
const configService = require('./configService');
// ? users
const entryPicturesUpload = multer({
@@ -12,7 +12,7 @@ const entryPicturesUpload = multer({
if (file.fieldname == 'backdrop') folder = 'backdrops';
if (file.fieldname == 'logo') folder = 'logos';
const dataPath = getSettings().userDataPath;
const dataPath = configService.getSettings().userDataPath;
cb(null, path.join(dataPath, 'images', 'entries', folder));
},
@@ -32,7 +32,7 @@ const collectionPicturesUpload = multer({
if (file.fieldname == 'backdrop') folder = 'backdrops';
if (file.fieldname == 'logo') folder = 'logos';
const dataPath = getSettings().userDataPath;
const dataPath = configService.getSettings().userDataPath;
cb(null, path.join(dataPath, 'images', 'collections', folder));
},
-68
View File
@@ -1,68 +0,0 @@
const fs = require('fs');
const path = require('path');
const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}');
let userDataPath = '';
const defaultSettings = {
userDataPath: '',
tmdbApiUrl: '',
tmdbApiKey: '',
frontPort: '',
backPort: '',
portableMode: '',
libraryViewMode: '',
favoritViewMode: '',
watchlistViewMode: '',
CollectionsViewMode: '',
CollectionItemsViewMode: '',
};
function getUserDataPath() {
// return parrentProcess.electron_path || path.join(__dirname, '..', '..', 'data');
return path.join(__dirname, '..', '..');
}
function getSettingsFilePath() {
return path.join(getUserDataPath(), 'settings.json');
}
function getSettings() {
const settingsFilePath = getSettingsFilePath();
try {
const settingsData = fs.readFileSync(settingsFilePath);
// console.log(`Loaded settings file.`);
return JSON.parse(settingsData);
} catch (err) {
console.error('Error reading settings file:', err);
console.log('Creating default settings file...');
let newSettingsFile = { ...defaultSettings };
let defaultDataPath = path.join(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.');
return defaultSettings;
}
}
function updateSettings(newSettings) {
const settingsFilePath = getSettingsFilePath();
const oldSettings = getSettings();
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));
}
module.exports = {
getSettings,
updateSettings
};