diff --git a/angular.json b/angular.json index 954fd4c..22609fc 100644 --- a/angular.json +++ b/angular.json @@ -3,7 +3,7 @@ "version": 1, "newProjectRoot": "projects", "projects": { - "ShowZ": { + "Showy": { "projectType": "application", "schematics": {}, "root": "", @@ -99,10 +99,10 @@ "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { - "buildTarget": "ShowZ:build:production" + "buildTarget": "Showy:build:production" }, "development": { - "buildTarget": "ShowZ:build:development" + "buildTarget": "Showy:build:development" } }, "defaultConfiguration": "development" @@ -110,7 +110,7 @@ "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { - "buildTarget": "ShowZ:build" + "buildTarget": "Showy:build" } }, "test": { diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js new file mode 100644 index 0000000..3fddf78 --- /dev/null +++ b/backend/controllers/entryController.js @@ -0,0 +1,102 @@ +const collectionManager = require('../services/collectionManager'); +const entryManager = require('../services/entryManager'); +const entryService = require("../services/entryService"); + +const _collectionManager = collectionManager; +const _entryManager = entryManager; +const _entryService = entryService; + +class EntryController { + + constructor() { + if (!EntryController.instance) { + EntryController.instance = this; + } + return EntryController.instance; + } + + // * GET ENTRY BY ID + async getAllEntries(req, res) { + const entries = await _entryService.getAllEntries(); + + res.status(200).json(entries); + } + + // * GET ENTRY BY ID + async getEntryById(req, res) { + const { id } = req.params; + + let entry = await _entryService.getEntryById(id, true); + + res.status(200).json(entry); + } + + // * POST - FETCH AND CREATE ENTRY USING TMDB ID + async fetchAndSaveNewEntry(req, res) { + const { tmdb_id, is_tvserie } = req.body; + + const createdEntry = await _entryManager.fetchAndSaveNewEntry(tmdb_id, is_tvserie); + + res.status(201).json(createdEntry); + } + // * PUT - ENTRY UPDATE + async updateEntry(req, res) { + const { id } = req.params; + const { entryData } = req.body; + + const updatedEntry = await _entryService.updateEntryById(id, entryData, true); + + res.status(201).json(updatedEntry); + } + + // * DELETE - ENTRY BY ID + async deleteEntry(req, res) { + const { id } = req.params; + + await _entryService.deleteEntryById(id); + res.status(200).json({ message: `Entry with ID ${id} deleted.` }); + } + + // * GET - SYNC ALL ENTIRES DATA + async syncSeries(req, res, next) { + const entries = await _entryManager.SyncSeriesData(); + + res.status(201).json(entries); + } + + // * GET - Get seasons of an entry + async getEntrySeasons(req, res) { + const { id } = req.params; + + const seasons = await _entryService.getEntrySeasons(id) + + if (seasons.length == 0) { + res.status(204).json({ message: 'Provided entry has no seasons' }); + } + + res.status(200).json(seasons); + } + + // * PUT - REQUEST ENTRY REFRECH + async refrechEntry(req, res, next) { + const { id } = req.params; + + const entry = await _entryManager.refrechEntryById(id) + res.status(201).json(entry); + } + + // * PUT - REQUEST COLLECTION REFRECH + async fetchEntryCollection(req, res, next) { + const { id } = req.params; + + const collection = await _collectionManager.fetchCollectionByEntryId(id); + + if (collection) { + res.status(201).json(collection); + } else { + res.status(204); + } + } +} + +module.exports = new EntryController(); \ No newline at end of file diff --git a/backend/controllers/importController.js b/backend/controllers/importController.js new file mode 100644 index 0000000..4f27da4 --- /dev/null +++ b/backend/controllers/importController.js @@ -0,0 +1,25 @@ +const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require("../services/importerService"); + +exports.importMovies = async (req, res) => { + const { movies } = req.body; + + const entries = await bulkImportMovies(movies); + + res.status(201).json(entries); +} + +exports.importTMBD = async (req, res) => { + const { values } = req.body; + + const entries = await bulkImportTmdb(values); + + res.status(201).json(entries); +} + +exports.importEpisodeWatchHistory = async (req, res) => { + const { values } = req.body; + + const createdRows = await bulkImportEpisodes(values); + + res.status(201).json(createdRows); +} \ No newline at end of file diff --git a/backend/controllers/settingsController.js b/backend/controllers/settingsController.js new file mode 100644 index 0000000..5446f66 --- /dev/null +++ b/backend/controllers/settingsController.js @@ -0,0 +1,21 @@ +const configService = require('../services/configService'); + +const _configService = configService; + +exports.getSettings = (req, res) => { + try { + const settings = _configService.getSettings(); + + res.status(200).json(settings); + } catch (err) { + res.status(500).send('Error retrieving settings'); + } +} + +exports.updateSettings = async (req, res) => { + const settings = req.body; + + _configService.updateSettings(settings); + + res.status(200).send(configService.getSettings()); +} \ No newline at end of file diff --git a/backend/errors/BadRequestError.js b/backend/errors/BadRequestError.js new file mode 100644 index 0000000..8e3855d --- /dev/null +++ b/backend/errors/BadRequestError.js @@ -0,0 +1,17 @@ +const CustomError = require('./CustomError'); + +/** + * Represents an error for HTTP 400 Bad Request. + * This error indicates that the server cannot process the request due to a client error. + */ +class BadRequestError extends CustomError { + constructor(message) { + super(message); + } + + statusCode() { + return 400; // Bad Request + } +} + +module.exports = BadRequestError; \ No newline at end of file diff --git a/backend/errors/ConflictError.js b/backend/errors/ConflictError.js index 380cefd..61a8732 100644 --- a/backend/errors/ConflictError.js +++ b/backend/errors/ConflictError.js @@ -1,5 +1,9 @@ const CustomError = require('./CustomError'); +/** + * Represents an error for HTTP 409 Conflict. + * This error indicates that the request could not be processed due to a conflict with the current state of the resource. + */ class ConflictError extends CustomError { constructor(message) { super(message); diff --git a/backend/errors/CustomError.js b/backend/errors/CustomError.js index 2282968..217b262 100644 --- a/backend/errors/CustomError.js +++ b/backend/errors/CustomError.js @@ -1,3 +1,7 @@ +/** + * Base class for custom HTTP errors. + * Extend this class to create specific error types with custom properties and behavior. + */ class CustomError extends Error { constructor(message) { super(message); diff --git a/backend/errors/ForbiddenError.js b/backend/errors/ForbiddenError.js index 004774d..b8633d4 100644 --- a/backend/errors/ForbiddenError.js +++ b/backend/errors/ForbiddenError.js @@ -1,5 +1,9 @@ const CustomError = require('./CustomError'); +/** + * Represents an error for HTTP 403 Forbidden. + * This error indicates that the client does not have permission to access the requested resource. + */ class ForbiddenError extends CustomError { constructor(message) { super(message); diff --git a/backend/errors/InternalServerError.js b/backend/errors/InternalServerError.js index 26b636d..4aef166 100644 --- a/backend/errors/InternalServerError.js +++ b/backend/errors/InternalServerError.js @@ -1,5 +1,9 @@ const CustomError = require('./CustomError'); +/** + * Represents an error for HTTP 500 Internal Server Error. + * This error indicates that the server encountered an unexpected condition that prevented it from fulfilling the request. + */ class InternalServerError extends CustomError { constructor(message) { super(message); diff --git a/backend/errors/NotFoundError.js b/backend/errors/NotFoundError.js index cd798df..c792b47 100644 --- a/backend/errors/NotFoundError.js +++ b/backend/errors/NotFoundError.js @@ -1,5 +1,9 @@ const CustomError = require('./CustomError'); +/** + * Represents an error for HTTP 404 Not Found. + * This error indicates that the requested resource could not be found on the server. + */ class NotFoundError extends CustomError { constructor(message) { super(message); diff --git a/backend/errors/UnauthorizedError.js b/backend/errors/UnauthorizedError.js index ed99a13..af26d37 100644 --- a/backend/errors/UnauthorizedError.js +++ b/backend/errors/UnauthorizedError.js @@ -1,5 +1,9 @@ const CustomError = require('./CustomError'); +/** + * Represents an error for HTTP 401 Unauthorized. + * This error indicates that the request requires user authentication. + */ class UnauthorizedError extends CustomError { constructor(message) { super(message); diff --git a/backend/errors/ValidationError.js b/backend/errors/ValidationError.js index 109698c..d4704b1 100644 --- a/backend/errors/ValidationError.js +++ b/backend/errors/ValidationError.js @@ -1,5 +1,9 @@ const CustomError = require('./CustomError'); +/** + * Represents an error for HTTP 422 Unprocessable Entity. + * This error indicates that the server understands the request but cannot process it due to semantic validation errors. + */ class ValidationError extends CustomError { constructor(message) { super(message); diff --git a/backend/mappers/entryMapper.js b/backend/mappers/entryMapper.js new file mode 100644 index 0000000..e69de29 diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index 6091e7a..c18916f 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -1,351 +1,27 @@ const express = require('express'); const entryRouter = express.Router(); -const { fetchEntryData, fetchCollectionData } = require('../services/tmdbService'); -const { saveEntry, refrechEntry, SyncSeriesData } = require('../services/models-services/entryService'); -const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService'); const { entryPicturesUpload } = require('../services/mutlerStorageLocations'); -const { doGeneratePreview } = require('../services/mediaService'); - -const { Sequelize } = require('sequelize'); const Entry = require('../models/Entry'); -const EntryId = require('../models/EntryId'); -const EntryRating = require('../models/EntryRating'); -const Genre = require('../models/Genre'); -const EntrySeen = require('../models/EntrySeen'); -const Season = require('../models/Season'); const Media = require('../models/Media'); -const Episode = require('../models/Episode'); -const Collection = require('../models/Collection'); -const { upsertOfficialCollection } = require('../services/models-services/collectionService'); const { logToFile } = require('../services/logService'); +const entryController = require('../controllers/entryController'); +const mediaOptimizerService = require('../services/mediaOptimizerService'); + // ! /entries -// * GET - ALL ENTRIES -entryRouter.get('/', async (req, res) => { - 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 ID - through: { - attributes: [] // Do not fetch any attributes from the join table - } - } - ] - }); +entryRouter.get('/sync-series', entryController.syncSeries); - // 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 - })); +entryRouter.get('/', entryController.getAllEntries); +entryRouter.get('/:id', entryController.getEntryById); +entryRouter.post('/', entryController.fetchAndSaveNewEntry); +entryRouter.put('/:id', entryController.updateEntry); +entryRouter.delete('/:id', entryController.deleteEntry); - res.status(200).json(entriesWithGenreNames); -}); - -// * GET - SYNC ALL ENTIRES DATA -entryRouter.get('/sync-series', async (req, res, next) => { - try { - const entries = await SyncSeriesData(); - - res.status(201).json(entries); - } catch (error) { - next(error) - } -}); - -// * GET ENTRY BY ID -entryRouter.get('/:id', async (req, res) => { - try { - const { id } = req.params; - - if (id == null) { // ! entry id not provided - res.status(404).json({ message: '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'], // Only fetch the genre 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) { // ! entry not found - res.status(404).json({ message: 'Entry not found' }); - } - - const entryObjectData = entry.get({ plain: true }); - const genres = entryObjectData.genres.map(genre => genre.name); - - entryObjectData.genres = genres; - - res.status(200).json(entryObjectData); - } catch (error) { - res.status(500).json({ error: error.message }); - console.log(error); - } -}); - -// * GET - Get seasons of an entry -entryRouter.get('/:id/seasons', async (req, res) => { - try { - const { id } = req.params; - - if (id == null) { // ! entry id not provided - res.status(404).json({ message: 'Entry id not provided' }); - } - - const entry = await Entry.findByPk(id); - - if (!entry) { - res.status(404).json({ message: 'Entry 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'], - ] - }) - - if (seasons.length == 0) { // ! no content - res.status(404).json({ message: 'No seasons' }); - } - - res.status(200).json(seasons); - } catch (error) { - res.status(500).json({ error: error.message }); - console.log(error); - } -}); - -// * POST - FETCH AND CREATE USING TMDB ID -entryRouter.post('/', async (req, res) => { - const { tmdb_id, is_tvserie } = req.body; - - const entryData = await fetchEntryData(tmdb_id, is_tvserie); - const entry = await saveEntry(entryData); - - if (entryData.belongs_to_collection) { - upsertOfficialCollection(entryData.belongs_to_collection.id); - } - - res.status(201).json(entry); -}); - -// ! import routes -entryRouter.post('/bulk-import-movies', async (req, res) => { - const { movies } = req.body; - - let entries = []; - try { - entries = await bulkImportMovies(movies); - } catch (error) { - res.status(500); - } - - res.status(201).json(entries); -}); - -entryRouter.post('/bulk-import-tmdb', async (req, res) => { - const { values } = req.body; - - let entries = []; - try { - entries = await bulkImportTmdb(values); - } catch (error) { - res.status(500); - } - - res.status(201).json(entries); -}); - -entryRouter.post('/bulk-import-episodes-seen', async (req, res) => { - const { values } = req.body; - - let createdRows = 0; - try { - createdRows = await bulkImportEpisodes(values); - console.log(`Episodes Seen - counts ${episodes.length}`) - } catch (error) { - res.status(500); - } - - res.status(201).json(createdRows); -}); -// + import routes end - -// * PUT - ENTRY UPDATE -entryRouter.put('/:id', async (req, res) => { - const { id } = req.params; - const { entryData } = req.body; - - // ? checking if the provied id is valid - const oldEntry = await Entry.findByPk(id); - - if (!oldEntry) - return res.status(404).json({ message: `Entry with the provided id was not found` }); - - // ? updating - await oldEntry.update(entryData); - - // ? returning a new entry with updated values - // let includes = [ - // { model: EntryId, as: 'entryId' }, - // { model: EntryRating, as: 'entryRating' }, - // { model: EntrySeen, as: 'entrySeen' }, - // { model: Media, as: 'medias' }, - // { - // model: Genre, - // as: 'genres', - // attributes: ['name'], - // through: { - // attributes: [] - // } - // } - // ]; - - // if (oldEntry.is_tvseries) includes.push({ model: Season, as: 'seasons' }); - - // const updatedEntry = await Entry.findByPk(id, { - // include: includes, - // order: [ - // [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list - // ] - // }); - - const updatedEntry = 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'], // Only fetch the genre 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 - ] - }); - - const entryObjectData = updatedEntry.get({ plain: true }); - const genres = entryObjectData.genres.map(genre => genre.name); - - entryObjectData.genres = genres; - - res.status(201).json(entryObjectData); -}); - -// * GET - REQUEST ENTRY REFRECH -entryRouter.get('/:id/refresh', async (req, res, next) => { - const { id } = req.params; - - try { - const entry = await refrechEntry(id); - - res.status(201).json(entry); - } catch (error) { - next(error) - } -}); - -// * GET - REQUEST ENTRY REFRECH -entryRouter.get('/:id/fetch-collection', async (req, res, next) => { - const { id } = req.params; - - try { - const oldEntry = await Entry.findByPk(id, { - include: [ - { model: EntryId, as: 'entryId' } - ] - }) - - const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries); - if (entryData.belongs_to_collection) { - let collectionData = entryData.belongs_to_collection; - - const [oldCollection, createdCollection] = await Collection.findOrCreate({ - where: { tmdbId: collectionData.id }, - defaults: { - name: collectionData.name, - posterPath: collectionData.poster_path, - backdropPath: collectionData.backdrop_path, - } - }); - - let userCollection = oldCollection || createdCollection; - if (userCollection) { - collectionData = await fetchCollectionData(collectionData.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 - } - } - }] - }); - - await userCollection.setEntries(entries); - await userCollection.update({ description: collectionData.overview }) - } - res.status(201).json(userCollection); - } - } catch (error) { - next(error) - } -}); +entryRouter.get('/:id/seasons', entryController.getEntrySeasons); +entryRouter.put('/:id/refresh', entryController.refrechEntry); +entryRouter.put('/:id/fetch-collection', entryController.fetchEntryCollection); // ! ENTRY MEDIA // * POST - ADD NEW ENTRY MEDIA (poster/backdrop/logo) @@ -368,43 +44,35 @@ entryRouter.post('/:id/media', upload, async (req, res) => { // Function to handle media creation based on uploaded file type const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]); - if (fileType) { - const file = req.files[fileType][0]; - const createdMedia = await Media.create({ - mediaable: 'entry', - mediaableId: id, - type: fileType, - path: file.filename, - isLocal: true, - isSelected: false, - isCustom: true - }); - - // ? generating low resolution preview - // const fileNameWithoutExt = file.filename.split('.')[0]; - // const originalPath = file.path; - - // let previewWidth = 342; // ? poster preview width - // if (fileType == 'backdrop') previewWidth = 780; - // if (fileType == 'logo') previewWidth = 300; - - // const previewPath = path.join(file.destination, `${fileNameWithoutExt}_preview.jpg`); - // generatePreview(originalPath, previewPath, previewWidth); - doGeneratePreview('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 res.status(200).json(createdMedia); + if (!fileType) { + return res.status(400).json({ message: 'Invalid media type' }); } - return res.status(400).json({ message: 'Invalid media type' }); + const file = req.files[fileType][0]; + const createdMedia = await Media.create({ + mediaable: 'entry', + mediaableId: id, + type: fileType, + path: file.filename, + isLocal: true, + isSelected: false, + isCustom: true + }); + + // ? generating low resolution preview + mediaOptimizerService.doGeneratePreview('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 res.status(200).json(createdMedia); + }); // * PUT - SET ENTRY MEDIA AS SELECTED @@ -458,7 +126,6 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => { if (otherMedia) { otherMedia.update({ isSelected: true }); } - // return res.status(404).json({ message: 'Media not found' }); } await Media.destroy({ where: { id: mediaId } }) @@ -466,23 +133,5 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => { res.status(200).json(); }); -// * DELETE - ENTRY BY ID -entryRouter.delete('/:id', async (req, res) => { - const { id } = req.params; - - try { - const numDeleted = await Entry.destroy({ - where: { id: id } - }); - - if (numDeleted) { - res.status(200).json({ message: `Entry with ID ${id} deleted.` }); - } else { - res.status(404).json({ message: `Entry with ID ${id} not found.` }); - } - } catch (error) { - res.status(500).json({ message: `Error deleting entry with ID ${id}.`, error: error.message }); - } -}); module.exports = entryRouter; diff --git a/backend/routes/import.routes.js b/backend/routes/import.routes.js new file mode 100644 index 0000000..ccc89e7 --- /dev/null +++ b/backend/routes/import.routes.js @@ -0,0 +1,11 @@ +const express = require('express'); +const importRouter = express.Router(); + +const importController = require('../controllers/importController'); + +// ! /import +importRouter.post('/movies', importController.importMovies); +importRouter.post('/tmdb', importController.importTMBD); +importRouter.post('/episodes-watch-history', importController.importEpisodeWatchHistory); + +module.exports = importRouter; diff --git a/backend/routes/media.routes.js b/backend/routes/media.routes.js index b3c861b..3d51eb2 100644 --- a/backend/routes/media.routes.js +++ b/backend/routes/media.routes.js @@ -1,12 +1,13 @@ const express = require('express'); +const mediaRouter = express.Router(); const path = require('path'); const fs = require('fs'); -const { getSettings } = require('../services/settingsService'); -const { doGeneratePreview } = require('../services/mediaService'); +const configService = require('../services/configService.js'); const { logToFile } = require('../services/logService'); +const mediaOptimizerService = require('../services/mediaOptimizerService.js'); -const mediaRouter = express.Router(); +const _mediaOptimizerService = mediaOptimizerService; // ! /media // ? Routes : media access routes @@ -21,7 +22,7 @@ mediaRouter.get('/:category/:type/:size/:fileName', (req, res, next) => { return res.status(404).send('Type Not Found'); } - const settings = getSettings(); + const settings = configService.getSettings(); const dataPath = settings.userDataPath; const mediaPath = path.join(dataPath, 'images', category, type); @@ -52,7 +53,7 @@ mediaRouter.get('/:category/:type/:size/:fileName', (req, res, next) => { // if (type == 'backdrops') previewWidth = 780; // if (type == 'logos') previewWidth = 300; - doGeneratePreview(category, type, fileName).then((result) => { + _mediaOptimizerService.doGeneratePreview(category, type, fileName).then((result) => { const stream = fs.createReadStream(filePath); stream.pipe(res); logToFile(`Media Route | Generated Preview`); diff --git a/backend/routes/routes.js b/backend/routes/routes.js index 19245c1..7f53277 100644 --- a/backend/routes/routes.js +++ b/backend/routes/routes.js @@ -13,6 +13,7 @@ const customMediaRouter = require('./custom-media.routes'); const mediaRouter = require('./media.routes'); const episodeRouter = require('./episode.routes'); const pingRouter = require('./ping.routes'); +const importRouter = require('./import.routes'); const router = express.Router(); router.use('/media', mediaRouter); @@ -28,6 +29,7 @@ router.use('/episode-seen', episodeSeenRouter); router.use('/custom-media', customMediaRouter); +router.use('/import', importRouter); router.use('/statistics', statisticsRouter); router.use('/settings', settingsRouter); router.use('/maintenance', maintenanceRouter); diff --git a/backend/routes/settings.routes.js b/backend/routes/settings.routes.js index 2e6ed11..37895f2 100644 --- a/backend/routes/settings.routes.js +++ b/backend/routes/settings.routes.js @@ -1,33 +1,10 @@ const express = require('express'); -const { updateSettings, getSettings } = require('../services/settingsService'); const settingsRouter = express.Router(); -const settingsFileFormat = { - "dataFolderPath": "", - "tmdbApiUrl": "", - "tmdbApiKey": "", - "frontPort": "", - "backPort": "", - "portableMode": "", -}; +const settingsController = require('../controllers/settingsController'); // ! /settings -settingsRouter.put('/', async (req, res) => { - const settings = req.body; - - updateSettings(settings); - - res.status(200).send(getSettings()); -}); - -settingsRouter.get('/', (req, res) => { - try { - const settings = getSettings(); - - res.status(200).json(settings); - } catch (err) { - res.status(500).send('Error retrieving settings'); - } -}); +settingsRouter.get('/', settingsController.getSettings); +settingsRouter.put('/', settingsController.updateSettings); module.exports = settingsRouter; diff --git a/backend/routes/user-collection.routes.js b/backend/routes/user-collection.routes.js index bda6511..a602ae2 100644 --- a/backend/routes/user-collection.routes.js +++ b/backend/routes/user-collection.routes.js @@ -1,8 +1,6 @@ const express = require('express'); const collectionRouter = express.Router(); -const { doGeneratePreview } = require('../services/mediaService'); - const { Sequelize } = require('sequelize'); const Collection = require('../models/Collection'); const UserCollectionEntry = require('../models/UserCollectionEntry'); @@ -13,9 +11,13 @@ const Season = require('../models/Season'); const Genre = require('../models/Genre'); const Media = require('../models/Media'); -const { getCollectionParts, upsertOfficialCollection } = require('../services/models-services/collectionService'); const { collectionPicturesUpload } = require('../services/mutlerStorageLocations'); const { logToFile } = require('../services/logService'); +const collectionManager = require('../services/collectionManager'); +const mediaOptimizerService = require('../services/mediaOptimizerService'); + +const _mediaOptimizerService = mediaOptimizerService; +const _collectionManager = collectionManager; // ! /collections // * GET - ALL COLLECTIONS @@ -120,7 +122,7 @@ collectionRouter.put('/:id', upload, async (req, res) => { if (posterPath) { // ? generating preview - doGeneratePreview("collections", 'posters', posterPath).then((result) => { + _mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => { const msg = `Collection Service | Generated Collection Preview`; logToFile(msg); }).catch((err) => { @@ -142,7 +144,7 @@ collectionRouter.put('/:id', upload, async (req, res) => { if (backdropPath) { // ? generating preview - doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => { + _mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => { const msg = `Collection Routes | Generated Collection Preview`; logToFile(msg); }).catch((err) => { @@ -202,26 +204,7 @@ collectionRouter.put('/:id/refresh', async (req, res) => { const collectionId = req.params.id; const oldCollection = await Collection.findByPk(collectionId); - const collection = await upsertOfficialCollection(oldCollection.tmdbId); - - // const collection = await Collection.findByPk(collectionId, { - // 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 - // }); + const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId); if (collection) { const collectionData = collection.get({ plain: true }); @@ -245,7 +228,7 @@ collectionRouter.put('/:id/parts', async (req, res) => { try { const collectionId = req.params.id; - await getCollectionParts(collectionId); + await _collectionManager.getCollectionParts(collectionId); const collection = await Collection.findByPk(collectionId, { include: [ diff --git a/backend/server.js b/backend/server.js index b388e57..9614cf3 100644 --- a/backend/server.js +++ b/backend/server.js @@ -10,12 +10,12 @@ const sequelizeHooks = require('./db/sequelizeHooks.js'); const { initializeData } = require('./db/dataInitializer.js'); const killerRouter = require('./routes/killer.routes.js'); const errorHandler = require('./middleware/errorHandler'); -const { getSettings } = require('./services/settingsService.js'); +const configService = require('./services/configService.js'); const { logToFile } = require('./services/logService.js'); const { generatePreview } = require('./services/mediaService.js'); // ? variables -let settings = getSettings() +let settings = configService.getSettings() const PORT = settings["backPort"] || 4000; const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}'); diff --git a/backend/services/collectionManager.js b/backend/services/collectionManager.js new file mode 100644 index 0000000..422e88c --- /dev/null +++ b/backend/services/collectionManager.js @@ -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} 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} 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} 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(); \ No newline at end of file diff --git a/backend/services/collectionService.js b/backend/services/collectionService.js new file mode 100644 index 0000000..772162f --- /dev/null +++ b/backend/services/collectionService.js @@ -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(); \ No newline at end of file diff --git a/backend/services/configService.js b/backend/services/configService.js new file mode 100644 index 0000000..fb6e486 --- /dev/null +++ b/backend/services/configService.js @@ -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(); \ No newline at end of file diff --git a/backend/services/entryManager.js b/backend/services/entryManager.js new file mode 100644 index 0000000..c93f2f7 --- /dev/null +++ b/backend/services/entryManager.js @@ -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(); diff --git a/backend/services/entryService.js b/backend/services/entryService.js new file mode 100644 index 0000000..cf46698 --- /dev/null +++ b/backend/services/entryService.js @@ -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(); \ No newline at end of file diff --git a/backend/services/maintenanceService.js b/backend/services/maintenanceService.js index a5a6670..7a7ba7d 100644 --- a/backend/services/maintenanceService.js +++ b/backend/services/maintenanceService.js @@ -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 diff --git a/backend/services/mediaDownloaderService.js b/backend/services/mediaDownloaderService.js new file mode 100644 index 0000000..df4ef53 --- /dev/null +++ b/backend/services/mediaDownloaderService.js @@ -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(); \ No newline at end of file diff --git a/backend/services/mediaManager.js b/backend/services/mediaManager.js new file mode 100644 index 0000000..688f4bf --- /dev/null +++ b/backend/services/mediaManager.js @@ -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(); diff --git a/backend/services/mediaOptimizerService.js b/backend/services/mediaOptimizerService.js new file mode 100644 index 0000000..305a32d --- /dev/null +++ b/backend/services/mediaOptimizerService.js @@ -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(); \ No newline at end of file diff --git a/backend/services/mediaService.js b/backend/services/mediaService.js index d2a08d9..d0638b5 100644 --- a/backend/services/mediaService.js +++ b/backend/services/mediaService.js @@ -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 -}; \ No newline at end of file +module.exports = new MediaService(); \ No newline at end of file diff --git a/backend/services/models-services/collectionService.js b/backend/services/models-services/collectionService.js deleted file mode 100644 index bc16334..0000000 --- a/backend/services/models-services/collectionService.js +++ /dev/null @@ -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, -} \ No newline at end of file diff --git a/backend/services/models-services/entryService.js b/backend/services/models-services/entryService.js index 5a591a7..6387efa 100644 --- a/backend/services/models-services/entryService.js +++ b/backend/services/models-services/entryService.js @@ -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, } \ No newline at end of file diff --git a/backend/services/mutlerStorageLocations.js b/backend/services/mutlerStorageLocations.js index 10de07e..0a985b1 100644 --- a/backend/services/mutlerStorageLocations.js +++ b/backend/services/mutlerStorageLocations.js @@ -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)); }, diff --git a/backend/services/settingsService.js b/backend/services/settingsService.js deleted file mode 100644 index a0657d8..0000000 --- a/backend/services/settingsService.js +++ /dev/null @@ -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 -}; \ No newline at end of file diff --git a/circular-dependencies.png b/circular-dependencies.png new file mode 100644 index 0000000..5276e45 Binary files /dev/null and b/circular-dependencies.png differ diff --git a/frontend/src/app/core/services/entry.service.ts b/frontend/src/app/core/services/entry.service.ts index 8376830..65a3cab 100644 --- a/frontend/src/app/core/services/entry.service.ts +++ b/frontend/src/app/core/services/entry.service.ts @@ -66,8 +66,9 @@ export class EntryService { // update entry refrechEntryById(entryId: number) { - return this.http.get( - `${this.backend_apiUrl}/${this.apiAction}/${entryId}/refresh` + return this.http.put( + `${this.backend_apiUrl}/${this.apiAction}/${entryId}/refresh`, + {} ); } @@ -78,8 +79,9 @@ export class EntryService { } fetchEntryCollectionById(entryId: number) { - return this.http.get( - `${this.backend_apiUrl}/${this.apiAction}/${entryId}/fetch-collection` + return this.http.put( + `${this.backend_apiUrl}/${this.apiAction}/${entryId}/fetch-collection`, + {} ); } diff --git a/frontend/src/favicon.png b/frontend/src/favicon.png new file mode 100644 index 0000000..8ae2e69 Binary files /dev/null and b/frontend/src/favicon.png differ diff --git a/frontend/src/index.html b/frontend/src/index.html index cd55f48..868d18c 100644 --- a/frontend/src/index.html +++ b/frontend/src/index.html @@ -4,9 +4,9 @@ Showy - + - + diff --git a/main.js b/main.js index 8b6560c..736d93d 100644 --- a/main.js +++ b/main.js @@ -2,18 +2,18 @@ const { spawn } = require('child_process'); const { app, BrowserWindow } = require('electron'); const path = require('path'); const url = require('url'); +const configService = require('./backend/services/configService'); let backendExpressProcess; let mainWindow; - -const { createMediaFolders } = require('./backend/services/mediaService'); +const _configService = configService; app.on('ready', () => { // ! Start the Express server loop startExpressServer(); - createMediaFolders(); + _configService.createMediaFolders(); // Start the Electron app createWindow(); @@ -53,14 +53,14 @@ function startExpressServer() { } // Start the Express server backendExpressProcess = spawn('node', ['backend/server.js'], { env: { PARENT_PROCESS: JSON.stringify(parrentProcess) } }); - + backendExpressProcess.stdout.on('data', (data) => { console.log(`Express stdout: ${data}`); if (data.toString().includes('Server started')) { // Adjust to match backend's startup message mainWindow.webContents.send('backend-ready'); // Send event to frontend } }); - + backendExpressProcess.stderr.on('data', (data) => { console.error(`Express stderr: ${data}`); }); diff --git a/package.json b/package.json index 5a1cd88..1218a86 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,9 @@ "version": "0.0.0", "main": "main.js", "scripts": { - "Backend": "nodemon backend/server.js", + "Backend": "nodemon backend/server.js --trace-warnings", "Frontend": "ng serve", + "Check Circular": "madge --circular --image circular-dependencies.png backend/server.js", "build-and-copy": "ng build --configuration production --base-href ./ && copyfiles backend/**/* dist/showy", "watch": "ng build --watch --configuration development", "electron-build:all": "ng build --configuration=production --base-href ./ && copyfiles backend/**/* dist/showy && electron . && electron-builder", @@ -57,6 +58,7 @@ "angular-star-rating": "^7.0.0", "apexcharts": "^3.49.0", "axios": "^1.6.8", + "body-parser": "^1.20.3", "bootstrap": "^5.3.3", "date-fns": "^3.6.0", "express": "^4.19.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 93f1c6b..9267fa9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -59,6 +59,9 @@ importers: axios: specifier: ^1.6.8 version: 1.7.5 + body-parser: + specifier: ^1.20.3 + version: 1.20.3 bootstrap: specifier: ^5.3.3 version: 5.3.3(@popperjs/core@2.11.8)