diff --git a/backend/controllers/collectionController.js b/backend/controllers/collectionController.js new file mode 100644 index 0000000..03211cf --- /dev/null +++ b/backend/controllers/collectionController.js @@ -0,0 +1,375 @@ +const { Sequelize } = require('sequelize'); +const Collection = require('../models/Collection'); +const UserCollectionEntry = require('../models/UserCollectionEntry'); +const Entry = require('../models/Entry'); +const EntryId = require('../models/EntryId'); +const EntryRating = require('../models/EntryRating'); +const Season = require('../models/Season'); +const Genre = require('../models/Genre'); +const Media = require('../models/Media'); + +const { logToFile } = require('../services/logService'); +const collectionManager = require('../services/collectionManager'); +const mediaOptimizerService = require('../services/mediaOptimizerService'); +const collectionService = require('../services/collectionService'); + +const _mediaOptimizerService = mediaOptimizerService; +const _collectionManager = collectionManager; +const _collectionService = collectionService; + +class CollectionController { + + constructor() { + if (!CollectionController.instance) { + CollectionController.instance = this; + } + return CollectionController.instance; + } + + async getCollections(req, res) { + const collections = await _collectionService.getCollections(); + + res.status(200).json(collections); + } + + // todo: move to collection service + async getCollectionById(req, res) { + try { + const collectionId = req.params.id; + + 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 + }, + }, + { model: Media, as: 'medias' }, + ], + order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + }); + + if (collection) { + const collectionData = collection.get({ plain: true }); + for (let i = 0; i < collectionData.entries.length; i++) { + const genres = collectionData.entries[i].genres.map(genre => genre.name); + collectionData.entries[i].genres = genres + } + + res.status(200).json(collectionData); + } else { + res.status(404).json({ message: 'UserCollection not found' }); + } + } catch (error) { + console.log(`Error getting collection info: `, error) + res.status(500).json({ error: error.message }); + } + } + + // todo: move to collection service + async createCollection(req, res) { + try { + const { name, description, userRating, posterPath } = req.body; + const isUserCollection = true; + const newUserCollection = await Collection.create({ name, description, userRating, posterPath, isUserCollection }); + res.status(201).json(newUserCollection); + } catch (error) { + res.status(400).json({ error: error.message }); + } + } + + // todo: move to collection service + async updateCollection(req, res) { + try { + const collectionId = req.params.id; + const { name, description, userRating } = req.body; + + const posterFile = req.files.poster ? req.files.poster[0] : undefined; + const backdropFile = req.files.backdrop ? req.files.backdrop[0] : undefined; + + let posterPath = posterFile ? posterFile.filename : undefined; + let backdropPath = backdropFile ? backdropFile.filename : undefined; + + const updateData = { + name, + description, + userRating: parseInt(userRating, 10), + isLocal: false, + }; + + if (posterPath) { + // ? generating preview + _mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => { + const msg = `Collection Service | Generated Collection Preview`; + logToFile(msg); + }).catch((err) => { + const msg = `Collection Service | Error Generating Collection Preview`; + logToFile(msg); + logToFile(err); + }); + + await Media.create({ + mediaable: 'collection', + mediaableId: collectionId, + type: 'poster', + path: posterPath, + isLocal: true, + isSelected: true, + isCustom: true + }) + } + + if (backdropPath) { + // ? generating preview + _mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => { + const msg = `Collection Routes | Generated Collection Preview`; + logToFile(msg); + }).catch((err) => { + const msg = `Collection Routes | Error Generating Collection Preview`; + logToFile(msg); + logToFile(err); + }); + + // ? inserting data + await Media.create({ + mediaable: 'collection', + mediaableId: collectionId, + type: 'backdrop', + path: backdropPath, + isLocal: true, + isSelected: true, + isCustom: true + }) + } + + const oldCollection = 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 + }, + }, + { model: Media, as: 'medias' }, + ], + order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + }); + + if (!oldCollection) + res.status(404).json({ message: 'Collection not found' }); + + await oldCollection.update(updateData); + + res.status(200).json(oldCollection); + } catch (error) { + console.log(`UserCollection update (put) error: `, error) + res.status(500).json({ error: error.message }); + } + } + + async refrechCollection(req, res) { + try { + const collectionId = req.params.id; + const oldCollection = await Collection.findByPk(collectionId); + + const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId); + + if (collection) { + const collectionData = collection.get({ plain: true }); + for (let i = 0; i < collectionData.entries.length; i++) { + const genres = collectionData.entries[i].genres.map(genre => genre.name); + collectionData.entries[i].genres = genres + } + + res.status(200).json(collectionData); + } else { + res.status(404).json({ message: 'Collection not found' }); + } + } catch (error) { + console.log(`UserCollection update (put) error: `, error) + res.status(500).json({ error: error.message }); + } + } + + async getCollectionParts(req, res) { + try { + const collectionId = req.params.id; + + await _collectionManager.getCollectionParts(collectionId); + + 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 + }, + }, + { model: Media, as: 'medias' }, + ], + order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order + }); + + if (collection) { + const collectionData = collection.get({ plain: true }); + for (let i = 0; i < collectionData.entries.length; i++) { + const genres = collectionData.entries[i].genres.map(genre => genre.name); + collectionData.entries[i].genres = genres + } + + res.status(200).json(collectionData); + } else { + res.status(404).json({ message: 'Collection not found' }); + } + } catch (error) { + console.log(`UserCollection update (put) error: `, error) + res.status(500).json({ error: error.message }); + } + } + + // todo: move to collection service + async deleteCollection(req, res) { + try { + const deleted = await Collection.destroy({ where: { id: req.params.id } }); + if (deleted) { + res.status(204).send(); + } else { + res.status(404).json({ message: 'UserCollection not found' }); + } + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + + // todo: move to collection service + async addEntryToCollection(req, res) { + try { + const { collectionId, entryId } = req.params; + + const newUserCollectionEntry = await UserCollectionEntry.create({ + user_collection_id: collectionId, + entry_id: entryId + }); + + // ? set a default poster if none exists + const userCollection = await Collection.findByPk(collectionId); + if (!userCollection.poster_path || userCollection.poster_path.trim() == '') { + const entry = await Entry.findByPk(entryId); + userCollection.poster_path = entry.poster_path; + await userCollection.save(); + } + + res.status(201).json(newUserCollectionEntry); + } catch (error) { + console.log(error) + res.status(400).json({ error: error.message }); + } + } + + // todo: move to collection manager + async updateCollectionEntryOrder(req, res) { + try { + const { collectionId, entryId } = req.params; + const { newOrder } = req.body; + + // ? getting the collectionEntry + const collectionEntry = await UserCollectionEntry.findOne({ + where: { + user_collection_id: collectionId, + entry_id: entryId + } + }); + + if (!collectionEntry) { + res.status(404).json({ message: 'UserCollectionEntry not found.' }); + } + + // ? updating + await collectionEntry.update({ order: newOrder }); + + res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' }); + } catch (error) { + console.log(`Error Updating UserCollectionEntry order: `, error); + res.status(500).json({ error: error.message }); + } + } + + // todo: move to collection manager + async removeEntryFromCollection(req, res) { + try { + const { collectionId, entryId } = req.params; + const deleted = await UserCollectionEntry.findOne({ + where: { + user_collection_id: collectionId, + entry_id: entryId + } + }); + + if (deleted) { + await deleted.destroy(); + res.status(204).send(); + } else { + res.status(404).json({ message: 'CollectionEntry not found.' }); + } + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + + // todo: move to collection manager + async createCollectionWithEntry(req, res) { + const { listDetails, entryId, entryOrder } = req.body; // Destructure needed properties from the request body + + try { + const result = await sequelize.transaction(async (t) => { + // Step 1: Create the userCollection + const newUserCollection = await Collection.create(listDetails, { transaction: t }); + + // Step 2: Add an entry to the newly created userCollection + const newUserCollectionEntry = await UserCollectionEntry.create({ + userCollectionId: newUserCollection.id, + entryId: entryId, + entryOrder: entryOrder + }, { transaction: t }); + + return { newUserCollection, newUserCollectionEntry }; + }); + + // If the transaction is successful, send back the created userCollection and entry relationship + res.status(201).json(result); + } catch (error) { + console.error('Failed to create userCollection and add entry:', error); + res.status(500).json({ message: 'Failed to create userCollection and add entry', error: error.message }); + } + } + +} + +module.exports = new CollectionController(); diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js index 3fddf78..b4ebe4d 100644 --- a/backend/controllers/entryController.js +++ b/backend/controllers/entryController.js @@ -1,3 +1,4 @@ +const EntryRating = require('../models/EntryRating'); const collectionManager = require('../services/collectionManager'); const entryManager = require('../services/entryManager'); const entryService = require("../services/entryService"); @@ -49,6 +50,26 @@ class EntryController { res.status(201).json(updatedEntry); } + // * PUT - ENTRY Ratings UPDATE + async updateEntryRatings(req, res) { + const { id } = req.params; + const { entryRatings } = req.body; + + const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings); + + res.status(200).json(updatedEntryRatings); + } + + // * PUT - ENTRY Ratings UPDATE + async updateEntryIds(req, res) { + const { id } = req.params; + const { entryIds } = req.body; + + const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds); + + res.status(200).json(updatedEntryIds); + } + // * DELETE - ENTRY BY ID async deleteEntry(req, res) { const { id } = req.params; diff --git a/backend/controllers/entrySeenController.js b/backend/controllers/entrySeenController.js new file mode 100644 index 0000000..9e4fbcd --- /dev/null +++ b/backend/controllers/entrySeenController.js @@ -0,0 +1,88 @@ +const Entry = require("../models/Entry"); +const EntrySeen = require('../models/EntrySeen'); + +class EntrySeenController { + + constructor() { + if (!EntrySeenController.instance) { + EntrySeenController.instance = this; + } + return EntrySeenController.instance; + } + + async getEntrySeens(req, res) { + const entrySeens = await EntrySeen.findAll(); + res.status(200).json(entrySeens); + } + + async getEntrySeenById(req, res) { + const entrySeen = await EntrySeen.findByPk(req.params.id); + + if (!entrySeen) { + res.status(404).json({ message: 'Entry seen record not found.' }); + } + + res.status(200).json(entrySeen); + } + + async createEntrySeen(req, res) { + const { entry_id, date_seen, seen_with } = req.body; + + // ? checking the an entry with the given id does exist + const entry = await Entry.findByPk(entry_id); + if (!entry) { + return res.status(404).json({ error: "Entry not found" }); + } + + // Create a new EntrySeen record + const newEntrySeen = await EntrySeen.create({ entry_id, date_seen, seen_with }); + res.status(201).json(newEntrySeen); + } + + async getEntrySeensByEntryId(req, res) { + const { entryId } = req.params; + const entrySeens = await EntrySeen.findAll({ + where: { entry_id: entryId }, + order: [['date_seen', 'DESC']] + }); + + if (entrySeens.length > 0) { + res.status(200).json(entrySeens); + } else { + res.status(404).json({ message: 'No records found for the given entry ID.' }); + } + + } + + async getEntrySeensByEntryId(req, res) { + + } + + async updateEntrySeen(req, res) { + const { date_seen, seen_with } = req.body; + const updated = await EntrySeen.update({ date_seen, seen_with }, { where: { id: req.params.id } }); + + if (updated[0] > 0) { + const updatedEntrySeen = await EntrySeen.findByPk(req.params.id); + res.status(200).json(updatedEntrySeen); + } else { + res.status(404).json({ message: 'Entry seen record not found.' }); + } + } + + async deleteEntrySeen(req, res) { + const entrySeen = await EntrySeen.findByPk(req.params.id); + + if (!entrySeen) + res.status(404).json({ message: 'Entry seen record not found.' }); + + const deleted = await entrySeen.destroy(); + + if (deleted) { + res.status(204).send(); + } + } + +} + +module.exports = new EntrySeenController(); diff --git a/backend/controllers/episodeController.js b/backend/controllers/episodeController.js new file mode 100644 index 0000000..bae3a1c --- /dev/null +++ b/backend/controllers/episodeController.js @@ -0,0 +1,26 @@ +const episodeService = require("../services/episodeService"); + +const _episodeService = episodeService; + +class EpisodeController { + + constructor() { + if (!EpisodeController.instance) { + EpisodeController.instance = this; + } + return EpisodeController.instance; + } + + async getEpisodesBetweenDates(req, res) { + const { startDate, endDate } = req.params; + try { + const episodes = await _episodeService.getEpisodesBetweenDates(startDate, endDate) + res.status(200).json(episodes); + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + +} + +module.exports = new EpisodeController(); diff --git a/backend/controllers/episodeSeenController.js b/backend/controllers/episodeSeenController.js new file mode 100644 index 0000000..f3b93db --- /dev/null +++ b/backend/controllers/episodeSeenController.js @@ -0,0 +1,144 @@ +const Entry = require("../models/Entry"); +const Episode = require("../models/Episode"); +const EpisodeSeen = require("../models/EpisodeSeen"); +const Season = require("../models/Season"); + +class EpisodeSeenController { + + constructor() { + if (!EpisodeSeenController.instance) { + EpisodeSeenController.instance = this; + } + return EpisodeSeenController.instance; + } + + async getEpisodesSeen(req, res) { + try { + const episodeSeens = await EpisodeSeen.findAll(); + res.status(200).json(episodeSeens); + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + + async getEpisodeSeenById(req, res) { + try { + const episodeSeen = await EpisodeSeen.findByPk(req.params.id); + + if (!episodeSeen) { + res.status(404).json({ message: 'Episode seen record not found.' }); + } + + res.status(200).json(episodeSeen); + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + + async createEpisodeSeen(req, res) { + try { + const { entry_id, episode_id, date_seen, seen_with } = req.body; + + const entry = await Entry.findByPk(entry_id); + if (!entry) + return res.status(404).json({ error: "Entry not found" }); + + const episode = await Episode.findByPk(episode_id); + if (!episode) + return res.status(404).json({ error: "Episode not found" }); + + // Create a new EpisodeSeen record + const newEpisodeSeen = await EpisodeSeen.create({ entry_id, episode_id, date_seen, seen_with }); + res.status(201).json(newEpisodeSeen); + } catch (error) { + res.status(400).json({ error: error.message }); + console.log(error); + } + } + + async getEpisodeSeensByEpisodeId(req, res) { + try { + const { episodeId } = req.params; + const episodeSeens = await EpisodeSeen.findAll({ + where: { episode_id: episodeId }, + order: [['date_seen', 'DESC']] + }); + + if (episodeSeens.length > 0) { + res.status(200).json(episodeSeens); + } else { + res.status(404).json({ message: 'No records found for the given episode ID.' }); + } + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + + async getEpisodeSeensByEntryId(req, res) { + try { + const { entryId } = req.params; + const episodeSeens = await EpisodeSeen.findAll({ + where: { entry_id: entryId }, + include: [{ + model: Episode, + include: [{ + model: Season, + attributes: ['season_number'], + }], + attributes: ['episode_number'], + }], + order: [ + ['date_seen', 'DESC'], + [{ model: Episode }, { model: Season }, 'season_number', 'DESC'], + // [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this + [Episode, 'episode_number', 'DESC']] + }); + + res.status(200).json(episodeSeens); + } catch (error) { + console.log(`error getting episode seen of an entry: `, error) + res.status(500).json({ error: error.message }); + } + } + + async updateEpisodeSeen(req, res) { + try { + const { date_seen, seen_with, episode_id } = req.body; + + const episodeSeen = await EpisodeSeen.findByPk(req.params.id) + if (!episodeSeen) + return res.status(404).json({ message: 'Episode seen record not found.' }); + + const updated = await episodeSeen.update({ date_seen, seen_with }); + + if (updated) { + res.status(200).json(updated); + } else { + res.status(404).json({ message: 'Episode seen record not found.' }); + } + } catch (error) { + res.status(500).json({ error: error.message }); + } + } + + async deleteEpisodeSeen(req, res) { + try { + // ? getting the episode seen object + const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); + if (!oldEpisodeSeen) + res.status(404).json({ message: 'Episode seen record not found.' }); + + // ?deleting the episode seen + const deleted = await oldEpisodeSeen.destroy(); + + if (deleted) + res.status(204).send(); + } catch (error) { + res.status(500).json({ error: error.message }); + console.log(error) + } + } + +} + +module.exports = new EpisodeSeenController(); diff --git a/backend/controllers/importController.js b/backend/controllers/importController.js index 4f27da4..dd95eed 100644 --- a/backend/controllers/importController.js +++ b/backend/controllers/importController.js @@ -1,25 +1,36 @@ const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require("../services/importerService"); -exports.importMovies = async (req, res) => { - const { movies } = req.body; +class ImportController { + constructor() { + if (!ImportController.instance) { + ImportController.instance = this; + } + return ImportController.instance; + } - const entries = await bulkImportMovies(movies); + async importMovies(req, res) { + const { movies } = req.body; - res.status(201).json(entries); + const entries = await bulkImportMovies(movies); + + res.status(201).json(entries); + } + + async importTMBD(req, res) { + const { values } = req.body; + + const entries = await bulkImportTmdb(values); + + res.status(201).json(entries); + } + + async importEpisodeWatchHistory(req, res) { + const { values } = req.body; + + const createdRows = await bulkImportEpisodes(values); + + res.status(201).json(createdRows); + } } -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 +module.exports = new ImportController(); diff --git a/backend/controllers/killerController.js b/backend/controllers/killerController.js new file mode 100644 index 0000000..6f97b6c --- /dev/null +++ b/backend/controllers/killerController.js @@ -0,0 +1,18 @@ +class KillerController { + + constructor() { + if (!KillerController.instance) { + KillerController.instance = this; + } + return KillerController.instance; + } + + async killBackend(req, res) { + console.log("Killing backend.") + res.status(200).json({ message: "Backend killed." }); + console.log(kill); + } + +} + +module.exports = new KillerController(); diff --git a/backend/controllers/maintenanceController.js b/backend/controllers/maintenanceController.js new file mode 100644 index 0000000..136ee4e --- /dev/null +++ b/backend/controllers/maintenanceController.js @@ -0,0 +1,40 @@ +const maintenanceService = require('../services/maintenanceService'); + +const _maintenanceService = maintenanceService; + +class MaintenanceController { + + constructor() { + if (!MaintenanceController.instance) { + MaintenanceController.instance = this; + } + return MaintenanceController.instance; + } + + async getOrpanFiles(req, res) { + const deleted = await _maintenanceService.deleteOrphanFiles(true); + + return res.status(200).json(deleted); + } + + async getOrphanMediaRecords(req, res) { + const deleted = await _maintenanceService.deleteOrphanMediaRecords(true); + + return res.status(200).json(deleted); + } + + async deleteOrpanFiles(req, res) { + const deleted = await _maintenanceService.deleteOrphanFiles(); + + return res.status(200).json(deleted); + } + + async deleteOrphanMediaRecords(req, res) { + const deleted = await _maintenanceService.deleteOrphanMediaRecords(); + + return res.status(200).json(deleted); + } + +} + +module.exports = new MaintenanceController(); diff --git a/backend/controllers/mediaController.js b/backend/controllers/mediaController.js new file mode 100644 index 0000000..9114495 --- /dev/null +++ b/backend/controllers/mediaController.js @@ -0,0 +1,114 @@ +const path = require('path'); +const fs = require('fs'); + +const Entry = require('../models/Entry'); +const Media = require('../models/Media'); +const Collection = require('../models/Collection'); + +const configService = require('../services/configService.js'); +const { logToFile } = require('../services/logService'); +const mediaOptimizerService = require('../services/mediaOptimizerService.js'); + +const _mediaOptimizerService = mediaOptimizerService; + +class MediaController { + + constructor() { + if (!MediaController.instance) { + MediaController.instance = this; + } + return MediaController.instance; + } + + async getMedias(req, res) { + + const allCustomMedia = await Media.findAll({ + where: { + isCustom: true, + }, + include: [ + { + model: Entry, + as: 'entry', + required: false // This ensures a LEFT OUTER JOIN + }, + { + model: Collection, + as: 'collection', + required: false // This ensures a LEFT OUTER JOIN + } + ] + }); + + res.status(200).json(allCustomMedia); + } + + getMedia(req, res, next) { + const { category, type, size, fileName } = req.params; + + if (!['entries', 'collections', 'franchises'].includes(category)) { + return res.status(404).send('Category Not Found'); + } + + if (!['backdrops', 'posters', 'logos', 'others'].includes(type)) { + return res.status(404).send('Type Not Found'); + } + + const settings = configService.getSettings(); + const dataPath = settings.userDataPath; + + const mediaPath = path.join(dataPath, 'images', category, type); + // const mediaPath = path.join(__dirname, '..', `data/images/${category}/${type}`); + + // * preparing to serve the preview + // ? basicaly im checking if the file requested is a preview file + // ? if so I make sure to change the extention to '_preview.jpg' (bcs all previews are jpg) + let filePath = path.join(mediaPath, fileName); + if (size == 'preview') { + const previewFileName = fileName.split('.')[0] + (type == 'logos' ? '_preview.png' : '_preview.jpg') + filePath = path.join(mediaPath, previewFileName); + } + + fs.access(filePath, fs.constants.F_OK, (err) => { + // * generating a preview if it doesn't exist + // ? then if the preview doesn't exist I generate a new one + // ? by taking the file name and removing '_preview' from it to get + // ? the original file name, and starting from that I join it to the media path + // ? and generate a preview file, but still return 202 http code since the file + // ? is still generating + if (err && size == 'preview') { + // const originalPath = path.join(mediaPath, fileName); + // const previewFileName = fileName.split('.')[0] + '_preview.jpg' + // const previewPath = path.join(mediaPath, previewFileName); + + // let previewWidth = 342; + // if (type == 'backdrops') previewWidth = 780; + // if (type == 'logos') previewWidth = 300; + + _mediaOptimizerService.doGeneratePreview(category, type, fileName).then((result) => { + const stream = fs.createReadStream(filePath); + stream.pipe(res); + logToFile(`Media Route | Generated Preview`); + }).catch((err) => { + logToFile(`Media Route | Error Generating Preview`); + logToFile(err); + }); + // const stream = fs.createReadStream(filePath); + // stream.pipe(res); + // return res.status(202).send('Preview is still generating. Please try again later.'); + } else { + const options = { + fallthrough: false, // ! Important: don't call next middleware if file isn't found + }; + + // express.static(filePath, options)(req, res, next); + // Serve the file using fs.createReadStream + const stream = fs.createReadStream(filePath); + stream.pipe(res); + } + }); + } + +} + +module.exports = new MediaController(); diff --git a/backend/controllers/pingController.js b/backend/controllers/pingController.js new file mode 100644 index 0000000..0943c15 --- /dev/null +++ b/backend/controllers/pingController.js @@ -0,0 +1,18 @@ +class PingController { + + constructor() { + if (!PingController.instance) { + PingController.instance = this; + } + return PingController.instance; + } + + ping(req, res) { + console.log("Ping Pong...") + + res.status(200).json({ message: 'pong' }); + } + +} + +module.exports = new PingController(); diff --git a/backend/controllers/seasonController.js b/backend/controllers/seasonController.js new file mode 100644 index 0000000..62ef442 --- /dev/null +++ b/backend/controllers/seasonController.js @@ -0,0 +1,102 @@ +const Episode = require("../models/Episode"); +const Season = require("../models/Season"); + + +class SeasonController { + + constructor() { + if (!SeasonController.instance) { + SeasonController.instance = this; + } + return SeasonController.instance; + } + + async createSeason(req, res) { + try { + const season = await Season.create(req.body); + res.status(201).send(season); + } catch (error) { + res.status(400).send(error.message); + } + } + + async getSeasons(req, res) { + try { + const seasons = await Season.findAll(); + res.send(seasons); + } catch (error) { + res.status(500).send(error.message); + } + } + + async getSeaonById(req, res) { + try { + const season = await Season.findByPk(req.params.id, { + include: [{ + model: Episode, + as: 'episodes' + }] + }); + + if (season) { + res.send(season); + } else { + res.status(404).send('Season not found'); + } + } catch (error) { + res.status(500).send(error.message); + } + } + + async getSeasonEpisodes(req, res) { + try { + const episodes = await Episode.findAll({ + where: { + season_id: req.params.id + } + }); + + if (episodes) { + res.send(episodes); + } else { + res.status(404).send('Episodes not found'); + } + } catch (error) { + res.status(500).send(error.message); + } + } + + async updateSeason(req, res) { + try { + const [updated] = await Season.update(req.body, { + where: { id: req.params.id } + }); + if (updated) { + const updatedSeason = await Season.findByPk(req.params.id); + res.send(updatedSeason); + } else { + res.status(404).send('Season not found'); + } + } catch (error) { + res.status(500).send(error.message); + } + } + + async deleteSeason(req, res) { + try { + const deleted = await Season.destroy({ + where: { id: req.params.id } + }); + if (deleted) { + res.status(204).send('Season deleted'); + } else { + res.status(404).send('Season not found'); + } + } catch (error) { + res.status(500).send(error.message); + } + } + +} + +module.exports = new SeasonController(); diff --git a/backend/controllers/settingsController.js b/backend/controllers/settingsController.js index 5446f66..5a52304 100644 --- a/backend/controllers/settingsController.js +++ b/backend/controllers/settingsController.js @@ -2,20 +2,33 @@ const configService = require('../services/configService'); const _configService = configService; -exports.getSettings = (req, res) => { - try { - const settings = _configService.getSettings(); +class SettingsController { - res.status(200).json(settings); - } catch (err) { - res.status(500).send('Error retrieving settings'); + constructor() { + if (!SettingsController.instance) { + SettingsController.instance = this; + } + return SettingsController.instance; } + + getSettings(req, res) { + try { + const settings = _configService.getSettings(); + + res.status(200).json(settings); + } catch (err) { + res.status(500).send('Error retrieving settings'); + } + } + + async updateSettings(req, res) { + const settings = req.body; + + _configService.updateSettings(settings); + + res.status(200).send(configService.getSettings()); + } + } -exports.updateSettings = async (req, res) => { - const settings = req.body; - - _configService.updateSettings(settings); - - res.status(200).send(configService.getSettings()); -} \ No newline at end of file +module.exports = new SettingsController(); diff --git a/backend/controllers/statisticsController.js b/backend/controllers/statisticsController.js new file mode 100644 index 0000000..6177842 --- /dev/null +++ b/backend/controllers/statisticsController.js @@ -0,0 +1,125 @@ +const sequelize = require('../config/database'); +const { Op } = require('sequelize'); +const Entry = require('../models/Entry'); +const EntrySeen = require('../models/EntrySeen'); +const Episode = require('../models/Episode'); +const EpisodeSeen = require('../models/EpisodeSeen'); + +class StatisticsController { + + constructor() { + if (!StatisticsController.instance) { + StatisticsController.instance = this; + } + return StatisticsController.instance; + } + + async getAllTimeWatchTime(req, res) { + const totalWatchTimeSeries = await EpisodeSeen.findOne({ + include: [ + { model: Episode, as: 'episode', attributes: [] } + ], + attributes: [ + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + }); + + const totalWatchTimeMovies = await EntrySeen.findOne({ + include: [ + { model: Entry, as: 'entry', attributes: [] } + ], + attributes: [ + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + }); + + const totalWatchTime = { + series: totalWatchTimeSeries.dataValues.watchTime, + movies: totalWatchTimeMovies.dataValues.watchTime + } + + return res.status(200).json(totalWatchTime); + } + + async getYearlyWatchTime(req, res) { + const { year } = req.params; + + const totalWatchTimeSeries = await EpisodeSeen.findAll({ + include: [ + { model: Episode, as: 'episode', attributes: [] } + ], + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + const totalWatchTimeMovies = await EntrySeen.findAll({ + include: [ + { model: Entry, as: 'entry', attributes: [] } + ], + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + const totalWatchTime = { + series: totalWatchTimeSeries, + movies: totalWatchTimeMovies + } + + return res.status(200).json(totalWatchTime); + } + + async getYearlyWatchCountGroupByMonth(req, res) { + try { + const { year } = req.params; + const seriesCount = await EpisodeSeen.findAll({ + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + const moviesCount = await EntrySeen.findAll({ + attributes: [ + [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], + [sequelize.fn('COUNT', sequelize.col('*')), 'count'] + ], + where: { + date_seen: { + [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] + } + }, + group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] + }); + + res.status(200).json({ series: seriesCount, movies: moviesCount }); + } catch (error) { + console.log(error) + res.status(500).json({ error: error.message }); + } + } + +} + +module.exports = new StatisticsController(); diff --git a/backend/package-lock.json b/backend/package-lock.json index 5d11c21..8ce5ab9 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,21 +1,376 @@ { - "name": "showybackend", + "name": "showy_backend", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "showybackend", + "name": "showy_backend", "version": "1.0.0", "license": "ISC", "dependencies": { + "axios": "^1.7.9", "body-parser": "^1.20.3", "dotenv": "^16.4.7", "express": "^4.21.2", "multer": "^1.4.5-lts.1", "mysql2": "^3.12.0", "nodemon": "^3.1.9", - "sequelize": "^6.37.5" + "optional": "^0.1.4", + "sequelize": "^6.37.5", + "sharp": "^0.33.5", + "uuid": "^11.0.5" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.3.1.tgz", + "integrity": "sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", + "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", + "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", + "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", + "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", + "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", + "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", + "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", + "cpu": [ + "s390x" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", + "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", + "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", + "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", + "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", + "cpu": [ + "arm" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.0.5" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", + "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", + "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", + "cpu": [ + "s390x" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.0.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", + "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", + "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", + "cpu": [ + "arm64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", + "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.0.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", + "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", + "cpu": [ + "wasm32" + ], + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.2.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", + "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", + "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" } }, "node_modules/@types/debug": { @@ -78,6 +433,11 @@ "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "node_modules/aws-ssl-profiles": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", @@ -86,6 +446,16 @@ "node": ">= 6.0.0" } }, + "node_modules/axios": { + "version": "1.7.9", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz", + "integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -232,6 +602,54 @@ "fsevents": "~2.3.2" } }, + "node_modules/color": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", + "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", + "dependencies": { + "color-convert": "^2.0.1", + "color-string": "^1.9.0" + }, + "engines": { + "node": ">=12.5.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/color-string": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", + "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", + "dependencies": { + "color-name": "^1.0.0", + "simple-swizzle": "^0.2.2" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -304,6 +722,14 @@ } } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/denque": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", @@ -329,6 +755,14 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/detect-libc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "engines": { + "node": ">=8" + } + }, "node_modules/dotenv": { "version": "16.4.7", "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", @@ -510,6 +944,38 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -694,6 +1160,11 @@ "node": ">= 0.10" } }, + "node_modules/is-arrayish": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.2.tgz", + "integrity": "sha512-eVRqCvVlZbuw3GrM63ovNSNAeA1K16kaR/LRY/92w0zxQ5/1YzwblUX652i4Xs9RwAGjW9d9y6X88t8OaAJfWQ==" + }, "node_modules/is-binary-path": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", @@ -1021,6 +1492,11 @@ "node": ">= 0.8" } }, + "node_modules/optional": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/optional/-/optional-0.1.4.tgz", + "integrity": "sha512-gtvrrCfkE08wKcgXaVwQVgwEQ8vel2dc5DDBn9RLQZ3YtmtkBss6A2HY6BnJH4N/4Ku97Ri/SF8sNWE2225WJw==" + }, "node_modules/parseurl": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", @@ -1067,6 +1543,11 @@ "node": ">= 0.10" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/pstree.remy": { "version": "1.1.8", "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", @@ -1296,6 +1777,14 @@ "node": ">= 10.0.0" } }, + "node_modules/sequelize/node_modules/uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/serve-static": { "version": "1.16.2", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", @@ -1315,6 +1804,44 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, + "node_modules/sharp": { + "version": "0.33.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", + "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", + "hasInstallScript": true, + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -1383,6 +1910,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/simple-swizzle": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz", + "integrity": "sha512-JA//kQgZtbuY83m+xT+tXJkmJncGMTFT+C+g2h2R9uxkYIrE2yy9sgmcLhCnw57/WSD+Eh3J97FPEDFnbXnDUg==", + "dependencies": { + "is-arrayish": "^0.3.1" + } + }, "node_modules/simple-update-notifier": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", @@ -1474,6 +2009,12 @@ "nodetouch": "bin/nodetouch.js" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "optional": true + }, "node_modules/type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", @@ -1523,11 +2064,15 @@ } }, "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", + "version": "11.0.5", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.5.tgz", + "integrity": "sha512-508e6IcKLrhxKdBbcA2b4KQZlLVp2+J5UwQ6F7Drckkc5N9ZJwFa4TgWtsww9UG8fGHbm6gbV19TdM5pQ4GaIA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], "bin": { - "uuid": "dist/bin/uuid" + "uuid": "dist/esm/bin/uuid" } }, "node_modules/validator": { diff --git a/backend/package.json b/backend/package.json index 91bb90d..20d7c87 100644 --- a/backend/package.json +++ b/backend/package.json @@ -5,7 +5,22 @@ "main": "server.js", "scripts": { "backend": "nodemon server.js --trace-warnings", - "test": "echo \"Error: no test specified\" && exit 1" + "package": "pkg server.js --output ../dist/backend/backend --targets node18-win-x64" + }, + "pkg": { + "scripts": [ + "node_modules/**/*" + ], + "assets": [ + "node_modules/**/*" + ], + "targets": [ + "win-x64" + ], + "outputPath": "../dist/backend/backend.exe" + }, + "bin": { + "showy-backend": "server.js" }, "keywords": [], "author": "", @@ -23,4 +38,4 @@ "sharp": "^0.33.5", "uuid": "^11.0.5" } -} +} \ No newline at end of file diff --git a/backend/routes/collection.routes.js b/backend/routes/collection.routes.js new file mode 100644 index 0000000..b9915b3 --- /dev/null +++ b/backend/routes/collection.routes.js @@ -0,0 +1,45 @@ +const express = require('express'); +const collectionRouter = express.Router(); + +const collectionController = require('../controllers/collectionController'); +const { collectionPicturesUpload } = require('../services/mutlerStorageLocations'); + +// ! /collections +// * GET - ALL COLLECTIONS +collectionRouter.get('/', collectionController.getCollections); + +// * GET - COLLECTION BY ID +collectionRouter.get('/:id', collectionController.getCollectionById); + +// * POST - CREATE COLLECTION +collectionRouter.post('/', collectionController.createCollection); + +// * PUT - UPDATE COLLECTION +const upload = collectionPicturesUpload.fields([ + { name: 'poster', maxCount: 1 }, + { name: 'backdrop', maxCount: 1 } +]); +collectionRouter.put('/:id', upload, collectionController.updateCollection); + +// * PUT - REFRESH COLLECTION +collectionRouter.put('/:id/refresh', collectionController.refrechCollection); + +// * PUT - GET COLLECTION PARTS +collectionRouter.put('/:id/parts', collectionController.getCollectionParts); + +// * DELETE - DELETE COLLECTION +collectionRouter.delete('/:id', collectionController.deleteCollection); + +// * POST - ADD ENTRY TO A COLLECTION +collectionRouter.post('/:collectionId/entries/:entryId', collectionController.addEntryToCollection); + +// * PATCH - UPDATE ENTRY ORDER IN COLLECTION +collectionRouter.patch('/:collectionId/entries/:entryId', collectionController.updateCollectionEntryOrder); + +// * DELETE - REMOVE AN ENTRY FROM A COLLECTION +collectionRouter.delete('/:collectionId/entries/:entryId', collectionController.removeEntryFromCollection); + +// * POST - CREATE COLLECTION WITH ENTRY +collectionRouter.post('/collection-with-entry', collectionController.createCollectionWithEntry); + +module.exports = collectionRouter; diff --git a/backend/routes/custom-media.routes.js b/backend/routes/custom-media.routes.js deleted file mode 100644 index b0f5845..0000000 --- a/backend/routes/custom-media.routes.js +++ /dev/null @@ -1,33 +0,0 @@ -const express = require('express'); -const Entry = require('../models/Entry'); -const Media = require('../models/Media'); -const Collection = require('../models/Collection'); - -const customMediaRouter = express.Router(); - -// ! /custom-media -// * GET - ALL CUSTOM MEDIA -customMediaRouter.get('/', async (req, res) => { - - const allCustomMedia = await Media.findAll({ - where: { - isCustom: true, - }, - include: [ - { - model: Entry, - as: 'entry', - required: false // This ensures a LEFT OUTER JOIN - }, - { - model: Collection, - as: 'collection', - required: false // This ensures a LEFT OUTER JOIN - } - ] - }); - - res.status(200).json(allCustomMedia); -}); - -module.exports = customMediaRouter; diff --git a/backend/routes/entry-ids.routes.js b/backend/routes/entry-ids.routes.js deleted file mode 100644 index 25c64a7..0000000 --- a/backend/routes/entry-ids.routes.js +++ /dev/null @@ -1,27 +0,0 @@ -const express = require('express'); -const entryIdsRouter = express.Router(); - -// ! /entry-ids -// * PUT - UPDATE ENTRY RATING BY ID -entryIdsRouter.put('/:id', async (req, res) => { - try { - const { id } = req.params; - const { tmdb_id, imdb_id, tvdb_id } = req.body; - - const entryId = await EntryId.findByPk(id); - if (!entryId) { // ! entry not found - return res.status(404).send('EntryId not found'); - } - - entryId.tmdb_id = tmdb_id ?? entryId.tmdb_id; - entryId.imdb_id = imdb_id ?? entryId.imdb_id; - entryId.tvdb_id = tvdb_id ?? entryId.tvdb_id; - - await entryId.save(); - res.status(200).json(entryId); - } catch (error) { - res.status(500).send('Server error'); - } -}); - -module.exports = entryIdsRouter; diff --git a/backend/routes/entry-ratings.routes.js b/backend/routes/entry-ratings.routes.js deleted file mode 100644 index 0d9fac5..0000000 --- a/backend/routes/entry-ratings.routes.js +++ /dev/null @@ -1,30 +0,0 @@ -const express = require('express'); -const EntrySeen = require('../models/EntrySeen'); -const EntryRating = require('../models/EntryRating'); -const entryRatingsRouter = express.Router(); - -// ! /entry-ratings -// * PUT - UPDATE ENTRY RATING BY ID -entryRatingsRouter.put('/:id', async (req, res) => { - try { - const { id } = req.params; - const { entryR } = req.body; - - const entryRating = await EntryRating.findByPk(id); - if (!entryRating) { - return res.status(404).json({ message: 'EntryRating not found' }); - } - - entryRating.user_rating = entryR.user_rating ?? entryRating.user_rating; - entryRating.tmdb_rating = entryR.tmdb_rating ?? entryRating.tmdb_rating; - entryRating.imdb_rating = entryR.imdb_rating ?? entryRating.imdb_rating; - entryRating.rotten_tomatoes_rating = entryR.rotten_tomatoes_rating ?? entryRating.rotten_tomatoes_rating; - - await entryRating.save(); - res.status(200).json(entryRating); - } catch (error) { - res.status(500).json({ message: 'Server error', error: error.message }); - } -}); - -module.exports = entryRatingsRouter; diff --git a/backend/routes/entry-seen.routes.js b/backend/routes/entry-seen.routes.js index ba66f60..a284f27 100644 --- a/backend/routes/entry-seen.routes.js +++ b/backend/routes/entry-seen.routes.js @@ -1,109 +1,25 @@ const express = require('express'); -const EntrySeen = require('../models/EntrySeen'); -const Entry = require('../models/Entry'); -const sequelize = require('../config/database'); -const { Op } = require('sequelize'); const entrySeenRouter = express.Router(); +const entrySeenController = require('../controllers/entrySeenController'); + // ! /entry-seen -// * POST - CREATE ENTRY SEEN -entrySeenRouter.post('/', async (req, res) => { - try { - const { entry_id, date_seen, seen_with } = req.body; - - // ? checking the an entry with the given id does exist - const entry = await Entry.findByPk(entry_id); - if (!entry) { - return res.status(404).json({ error: "Entry not found" }); - } - - // Create a new EntrySeen record - const newEntrySeen = await EntrySeen.create({ entry_id, date_seen, seen_with }); - res.status(201).json(newEntrySeen); - } catch (error) { - console.log(`Entry Seen create (post) error: `, error); - res.status(400).json({ error: error.message }); - } -}); - // * GET - ALL ENTRY SEEN -entrySeenRouter.get('/', async (req, res) => { - try { - const entrySeens = await EntrySeen.findAll(); - res.status(200).json(entrySeens); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +entrySeenRouter.get('/', entrySeenController.getEntrySeens); // * GET - ENTRY SEEN BY ID -entrySeenRouter.get('/:id', async (req, res) => { - try { - const entrySeen = await EntrySeen.findByPk(req.params.id); +entrySeenRouter.get('/:id', entrySeenController.getEntrySeenById); - if (!entrySeen) { - res.status(404).json({ message: 'Entry seen record not found.' }); - } +// * POST - CREATE ENTRY SEEN +entrySeenRouter.post('/', entrySeenController.createEntrySeen); - res.status(200).json(entrySeen); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// * GET - ENTRY SEEN LIST BY ENTRY ID -entrySeenRouter.get('/by-entry/:entryId', async (req, res) => { - try { - const { entryId } = req.params; - const entrySeens = await EntrySeen.findAll({ - where: { entry_id: entryId }, - order: [['date_seen', 'DESC']] - }); - - if (entrySeens.length > 0) { - res.status(200).json(entrySeens); - } else { - res.status(404).json({ message: 'No records found for the given entry ID.' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +// * GET - ENTRY SEEN BY ENTRY ID +entrySeenRouter.get('/by-entry/:entryId', entrySeenController.getEntrySeensByEntryId); // * PUT - UPDATE ENTRY SEEN -entrySeenRouter.put('/:id', async (req, res) => { - try { - const { date_seen, seen_with } = req.body; - const updated = await EntrySeen.update({ date_seen, seen_with }, { where: { id: req.params.id } }); - - if (updated[0] > 0) { - const updatedEntrySeen = await EntrySeen.findByPk(req.params.id); - res.status(200).json(updatedEntrySeen); - } else { - res.status(404).json({ message: 'Entry seen record not found.' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +entrySeenRouter.put('/:id', entrySeenController.updateEntrySeen); // * DELETE - ENTRY SEEN -entrySeenRouter.delete('/:id', async (req, res) => { - try { - const entrySeen = await EntrySeen.findByPk(req.params.id); - - if (!entrySeen) - res.status(404).json({ message: 'Entry seen record not found.' }); - - const deleted = await entrySeen.destroy(); - - if (deleted) { - res.status(204).send(); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - +entrySeenRouter.delete('/:id', entrySeenController.deleteEntrySeen); module.exports = entrySeenRouter; diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index c18916f..6626c65 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -17,6 +17,8 @@ entryRouter.get('/', entryController.getAllEntries); entryRouter.get('/:id', entryController.getEntryById); entryRouter.post('/', entryController.fetchAndSaveNewEntry); entryRouter.put('/:id', entryController.updateEntry); +entryRouter.put('/:id/ratings', entryController.updateEntryRatings); +entryRouter.put('/:id/ids', entryController.updateEntryIds); entryRouter.delete('/:id', entryController.deleteEntry); entryRouter.get('/:id/seasons', entryController.getEntrySeasons); diff --git a/backend/routes/episode-seen.routes.js b/backend/routes/episode-seen.routes.js index 5f0f1c1..293f4d4 100644 --- a/backend/routes/episode-seen.routes.js +++ b/backend/routes/episode-seen.routes.js @@ -1,146 +1,28 @@ const express = require('express'); -const Episode = require('../models/Episode'); -const EpisodeSeen = require('../models/EpisodeSeen'); -const Season = require('../models/Season'); -const sequelize = require('../config/database'); -const { Op } = require('sequelize'); -const Entry = require('../models/Entry'); const episodeSeenRouter = express.Router(); +const episodeSeenController = require('../controllers/episodeSeenController'); + // ! /episode-seen // * POST - CREATE ENTRY SEEN -episodeSeenRouter.post('/', async (req, res) => { - try { - const { entry_id, episode_id, date_seen, seen_with } = req.body; - - const entry = await Entry.findByPk(entry_id); - if (!entry) - return res.status(404).json({ error: "Entry not found" }); - - const episode = await Episode.findByPk(episode_id); - if (!episode) - return res.status(404).json({ error: "Episode not found" }); - - // Create a new EpisodeSeen record - const newEpisodeSeen = await EpisodeSeen.create({ entry_id, episode_id, date_seen, seen_with }); - res.status(201).json(newEpisodeSeen); - } catch (error) { - res.status(400).json({ error: error.message }); - console.log(error); - } -}); +episodeSeenRouter.post('/', episodeSeenController.createEpisodeSeen); // * GET - ALL EPISODE SEEN -episodeSeenRouter.get('/', async (req, res) => { - try { - const episodeSeens = await EpisodeSeen.findAll(); - res.status(200).json(episodeSeens); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +episodeSeenRouter.get('/', episodeSeenController.getEpisodesSeen); // * GET - EPISODE SEEN BY ID -episodeSeenRouter.get('/:id', async (req, res) => { - try { - const episodeSeen = await EpisodeSeen.findByPk(req.params.id); - - if (!episodeSeen) { - res.status(404).json({ message: 'Episode seen record not found.' }); - } - - res.status(200).json(episodeSeen); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +episodeSeenRouter.get('/:id', episodeSeenController.getEpisodeSeenById); // * GET - EPISODE SEEN BY EPISODE ID -episodeSeenRouter.get('/by-episode/:episodeId', async (req, res) => { - try { - const { episodeId } = req.params; - const episodeSeens = await EpisodeSeen.findAll({ - where: { episode_id: episodeId }, - order: [['date_seen', 'DESC']] - }); - - if (episodeSeens.length > 0) { - res.status(200).json(episodeSeens); - } else { - res.status(404).json({ message: 'No records found for the given episode ID.' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +episodeSeenRouter.get('/by-episode/:episodeId', episodeSeenController.getEpisodeSeensByEpisodeId); // * GET - EPISODE SEEN BY ENTRY ID -episodeSeenRouter.get('/by-entry/:entryId', async (req, res) => { - try { - const { entryId } = req.params; - const episodeSeens = await EpisodeSeen.findAll({ - where: { entry_id: entryId }, - include: [{ - model: Episode, - include: [{ - model: Season, - attributes: ['season_number'], - }], - attributes: ['episode_number'], - }], - order: [ - ['date_seen', 'DESC'], - [{ model: Episode }, { model: Season }, 'season_number', 'DESC'], - // [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this - [Episode, 'episode_number', 'DESC']] - }); - - res.status(200).json(episodeSeens); - } catch (error) { - console.log(`error getting episode seen of an entry: `, error) - res.status(500).json({ error: error.message }); - } -}); +episodeSeenRouter.get('/by-entry/:entryId', episodeSeenController.getEpisodeSeensByEntryId); // * PUT - UPDATE EPISODE SEEN -episodeSeenRouter.put('/:id', async (req, res) => { - try { - const { date_seen, seen_with, episode_id } = req.body; - - const episodeSeen = await EpisodeSeen.findByPk(req.params.id) - if (!episodeSeen) - return res.status(404).json({ message: 'Episode seen record not found.' }); - - const updated = await episodeSeen.update({ date_seen, seen_with }); - - if (updated) { - res.status(200).json(updated); - } else { - res.status(404).json({ message: 'Episode seen record not found.' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +episodeSeenRouter.put('/:id', episodeSeenController.updateEpisodeSeen); // * DELETE - EPISODE SEEN -episodeSeenRouter.delete('/:id', async (req, res) => { - try { - // ? getting the episode seen object - const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id); - if (!oldEpisodeSeen) - res.status(404).json({ message: 'Episode seen record not found.' }); - - // ?deleting the episode seen - const deleted = await oldEpisodeSeen.destroy(); - - if (deleted) - res.status(204).send(); - } catch (error) { - res.status(500).json({ error: error.message }); - console.log(error) - } -}); - +episodeSeenRouter.delete('/:id', episodeSeenController.deleteEpisodeSeen); module.exports = episodeSeenRouter; diff --git a/backend/routes/episode.routes.js b/backend/routes/episode.routes.js index 9452993..87c0e01 100644 --- a/backend/routes/episode.routes.js +++ b/backend/routes/episode.routes.js @@ -1,16 +1,8 @@ const express = require('express'); -const { getEpisodesBetweenDates } = require('../services/models-services/episodeService'); +const episodeController = require('../controllers/episodeController'); const episodeRouter = express.Router(); // ! /episodes -episodeRouter.get('/month/:startDate/:endDate', async (req, res) => { - const { startDate, endDate } = req.params; - try { - const episodes = await getEpisodesBetweenDates(startDate, endDate) - res.status(200).json(episodes); - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); +episodeRouter.get('/month/:startDate/:endDate', episodeController.getEpisodesBetweenDates); module.exports = episodeRouter; diff --git a/backend/routes/killer.routes.js b/backend/routes/killer.routes.js index c64d720..d0e4ca2 100644 --- a/backend/routes/killer.routes.js +++ b/backend/routes/killer.routes.js @@ -1,17 +1,11 @@ const express = require('express'); +const killerController = require('../controllers/killerController'); const killerRouter = express.Router(); // ! /killer // * POST -killerRouter.post('/', async (req, res) => { - console.log("Killing backend.") - console.log(haha) -}); - +killerRouter.post('/', killerController.killBackend); // * GET -killerRouter.get('/', async (req, res) => { - console.log("Killing backend.") - console.log(haha) -}); +killerRouter.get('/', killerController.killBackend); module.exports = killerRouter; diff --git a/backend/routes/maintenance.routes.js b/backend/routes/maintenance.routes.js index 6ac7998..c7eb12e 100644 --- a/backend/routes/maintenance.routes.js +++ b/backend/routes/maintenance.routes.js @@ -1,34 +1,19 @@ const express = require('express'); -const { deleteMissingFilesEntries, deleteOrphanFiles } = require('../services/maintenanceService'); const maintenanceRouter = express.Router(); +const maintenanceController = require('../controllers/maintenanceController'); + // ! /maintenance // * GET - Orphan files -maintenanceRouter.get('/orphan-files', async (req, res) => { - const deleted = await deleteOrphanFiles(true); - - return res.status(200).json(deleted); -}); +maintenanceRouter.get('/orphan-files', maintenanceController.getOrpanFiles); // * GET - Missing files -maintenanceRouter.get('/missing-files', async (req, res) => { - const deleted = await deleteMissingFilesEntries(true); - - return res.status(200).json(deleted); -}); +maintenanceRouter.get('/orphan-media-records', maintenanceController.getOrphanMediaRecords); // * DELETE - Orphan files -maintenanceRouter.delete('/orphan-files', async (req, res) => { - const deleted = await deleteOrphanFiles(); - - return res.status(200).json(deleted); -}); +maintenanceRouter.delete('/orphan-files', maintenanceController.deleteOrpanFiles); // * DELETE - Missing files -maintenanceRouter.delete('/missing-files', async (req, res) => { - const deleted = await deleteMissingFilesEntries(); - - return res.status(200).json(deleted); -}); +maintenanceRouter.delete('/orphan-media-records', maintenanceController.deleteOrphanMediaRecords); module.exports = maintenanceRouter; diff --git a/backend/routes/media.routes.js b/backend/routes/media.routes.js index 3d51eb2..e32e4cf 100644 --- a/backend/routes/media.routes.js +++ b/backend/routes/media.routes.js @@ -1,80 +1,12 @@ const express = require('express'); const mediaRouter = express.Router(); -const path = require('path'); -const fs = require('fs'); -const configService = require('../services/configService.js'); -const { logToFile } = require('../services/logService'); -const mediaOptimizerService = require('../services/mediaOptimizerService.js'); - -const _mediaOptimizerService = mediaOptimizerService; +const mediaController = require('../controllers/mediaController.js'); // ! /media +mediaRouter.get('/', mediaController.getMedias); + // ? Routes : media access routes -mediaRouter.get('/:category/:type/:size/:fileName', (req, res, next) => { - const { category, type, size, fileName } = req.params; - - if (!['entries', 'collections', 'franchises'].includes(category)) { - return res.status(404).send('Category Not Found'); - } - - if (!['backdrops', 'posters', 'logos', 'others'].includes(type)) { - return res.status(404).send('Type Not Found'); - } - - const settings = configService.getSettings(); - const dataPath = settings.userDataPath; - - const mediaPath = path.join(dataPath, 'images', category, type); - // const mediaPath = path.join(__dirname, '..', `data/images/${category}/${type}`); - - // * preparing to serve the preview - // ? basicaly im checking if the file requested is a preview file - // ? if so I make sure to change the extention to '_preview.jpg' (bcs all previews are jpg) - let filePath = path.join(mediaPath, fileName); - if (size == 'preview') { - const previewFileName = fileName.split('.')[0] + (type == 'logos' ? '_preview.png' : '_preview.jpg') - filePath = path.join(mediaPath, previewFileName); - } - - fs.access(filePath, fs.constants.F_OK, (err) => { - // * generating a preview if it doesn't exist - // ? then if the preview doesn't exist I generate a new one - // ? by taking the file name and removing '_preview' from it to get - // ? the original file name, and starting from that I join it to the media path - // ? and generate a preview file, but still return 202 http code since the file - // ? is still generating - if (err && size == 'preview') { - // const originalPath = path.join(mediaPath, fileName); - // const previewFileName = fileName.split('.')[0] + '_preview.jpg' - // const previewPath = path.join(mediaPath, previewFileName); - - // let previewWidth = 342; - // if (type == 'backdrops') previewWidth = 780; - // if (type == 'logos') previewWidth = 300; - - _mediaOptimizerService.doGeneratePreview(category, type, fileName).then((result) => { - const stream = fs.createReadStream(filePath); - stream.pipe(res); - logToFile(`Media Route | Generated Preview`); - }).catch((err) => { - logToFile(`Media Route | Error Generating Preview`); - logToFile(err); - }); - // const stream = fs.createReadStream(filePath); - // stream.pipe(res); - // return res.status(202).send('Preview is still generating. Please try again later.'); - } else { - const options = { - fallthrough: false, // ! Important: don't call next middleware if file isn't found - }; - - // express.static(filePath, options)(req, res, next); - // Serve the file using fs.createReadStream - const stream = fs.createReadStream(filePath); - stream.pipe(res); - } - }); -}); +mediaRouter.get('/:category/:type/:size/:fileName', mediaController.getMedia); module.exports = mediaRouter; diff --git a/backend/routes/ping.routes.js b/backend/routes/ping.routes.js index 55da226..7d8a5af 100644 --- a/backend/routes/ping.routes.js +++ b/backend/routes/ping.routes.js @@ -1,9 +1,8 @@ const express = require('express'); +const PingController = require('../controllers/PingController'); const pingRouter = express.Router(); // ! /ping -pingRouter.get('/', (req, res) => { - res.status(200).json({ message: 'pong' }); -}); +pingRouter.get('/', PingController.ping); module.exports = pingRouter; diff --git a/backend/routes/routes.js b/backend/routes/routes.js index 7f53277..49d9468 100644 --- a/backend/routes/routes.js +++ b/backend/routes/routes.js @@ -1,15 +1,12 @@ const express = require('express'); -const collectionRouter = require('./user-collection.routes'); -const entryIdsRouter = require('./entry-ids.routes'); +const collectionRouter = require('./collection.routes'); const entrySeenRouter = require('./entry-seen.routes'); const entryRouter = require('./entry.routes'); -const entryRatingsRouter = require('./entry-ratings.routes'); const seasonRouter = require('./season.routes'); const episodeSeenRouter = require('./episode-seen.routes'); const settingsRouter = require('./settings.routes'); const maintenanceRouter = require('./maintenance.routes'); const statisticsRouter = require('./statistics.routes'); -const customMediaRouter = require('./custom-media.routes'); const mediaRouter = require('./media.routes'); const episodeRouter = require('./episode.routes'); const pingRouter = require('./ping.routes'); @@ -20,13 +17,10 @@ router.use('/media', mediaRouter); router.use('/entries', entryRouter); router.use('/collections', collectionRouter); router.use('/entry-seen', entrySeenRouter); -router.use('/entry-ids', entryIdsRouter); -router.use('/entry-ratings', entryRatingsRouter); router.use('/seasons', seasonRouter); router.use('/episodes', episodeRouter); router.use('/episode-seen', episodeSeenRouter); -router.use('/custom-media', customMediaRouter); router.use('/import', importRouter); diff --git a/backend/routes/season.routes.js b/backend/routes/season.routes.js index 2a1e8fd..b494498 100644 --- a/backend/routes/season.routes.js +++ b/backend/routes/season.routes.js @@ -1,99 +1,25 @@ const express = require('express'); -const Season = require('../models/Season'); -const Episode = require('../models/Episode'); const seasonRouter = express.Router(); +const seasonController = require('../controllers/seasonController'); + // ! /seasons // * POST - Create a new season -seasonRouter.post('/', async (req, res) => { - try { - const season = await Season.create(req.body); - res.status(201).send(season); - } catch (error) { - res.status(400).send(error.message); - } -}); +seasonRouter.post('/', seasonController.createSeason); // * GET - Retrieve all seasons -seasonRouter.get('/', async (req, res) => { - try { - const seasons = await Season.findAll(); - res.send(seasons); - } catch (error) { - res.status(500).send(error.message); - } -}); +seasonRouter.get('/', seasonController.getSeasons); // * GET - Retrieve a specific season by id -seasonRouter.get('/:id', async (req, res) => { - try { - const season = await Season.findByPk(req.params.id, { - include: [{ - model: Episode, - as: 'episodes' - }] - }); - - if (season) { - res.send(season); - } else { - res.status(404).send('Season not found'); - } - } catch (error) { - res.status(500).send(error.message); - } -}); +seasonRouter.get('/:id', seasonController.getSeaonById); // * GET - Retrieve episodes of a season -seasonRouter.get('/:id/episodes', async (req, res) => { - try { - const episodes = await Episode.findAll({ - where: { - season_id: req.params.id - } - }); - - if (episodes) { - res.send(episodes); - } else { - res.status(404).send('Episodes not found'); - } - } catch (error) { - res.status(500).send(error.message); - } -}); +seasonRouter.get('/:id/episodes', seasonController.getSeasonEpisodes); // * PUT - Update a season -seasonRouter.put('/:id', async (req, res) => { - try { - const [updated] = await Season.update(req.body, { - where: { id: req.params.id } - }); - if (updated) { - const updatedSeason = await Season.findByPk(req.params.id); - res.send(updatedSeason); - } else { - res.status(404).send('Season not found'); - } - } catch (error) { - res.status(500).send(error.message); - } -}); +seasonRouter.put('/:id', seasonController.updateSeason); // * DELETE - Delete a season -seasonRouter.delete('/:id', async (req, res) => { - try { - const deleted = await Season.destroy({ - where: { id: req.params.id } - }); - if (deleted) { - res.status(204).send('Season deleted'); - } else { - res.status(404).send('Season not found'); - } - } catch (error) { - res.status(500).send(error.message); - } -}); +seasonRouter.delete('/:id', seasonController.deleteSeason); module.exports = seasonRouter; \ No newline at end of file diff --git a/backend/routes/statistics.routes.js b/backend/routes/statistics.routes.js index f021930..49adbee 100644 --- a/backend/routes/statistics.routes.js +++ b/backend/routes/statistics.routes.js @@ -1,121 +1,16 @@ const express = require('express'); const statisticsRouter = express.Router(); -const sequelize = require('../config/database'); -const { Op } = require('sequelize'); -const EpisodeSeen = require('../models/EpisodeSeen'); -const EntrySeen = require('../models/EntrySeen'); -const Episode = require('../models/Episode'); -const Entry = require('../models/Entry'); +const statisticsController = require('../controllers/statisticsController'); // ! /statistics -// * GET - Total Watch Time -statisticsRouter.get('/watch-time', async (req, res) => { - const totalWatchTimeSeries = await EpisodeSeen.findOne({ - include: [ - { model: Episode, as: 'episode', attributes: [] } - ], - attributes: [ - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] - ], - }); +// * GET - All Time, Watch Time +statisticsRouter.get('/watch-time', statisticsController.getAllTimeWatchTime); - const totalWatchTimeMovies = await EntrySeen.findOne({ - include: [ - { model: Entry, as: 'entry', attributes: [] } - ], - attributes: [ - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] - ], - }); +// * GET - Yearly Watch Time +statisticsRouter.get('/watch-time/year/:year', statisticsController.getYearlyWatchTime); - const totalWatchTime = { - series: totalWatchTimeSeries.dataValues.watchTime, - movies: totalWatchTimeMovies.dataValues.watchTime - } - - return res.status(200).json(totalWatchTime); -}); - -// * GET - Total Watch Time -statisticsRouter.get('/watch-time/year/:year', async (req, res) => { - const { year } = req.params; - - const totalWatchTimeSeries = await EpisodeSeen.findAll({ - include: [ - { model: Episode, as: 'episode', attributes: [] } - ], - attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] - ], - where: { - date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } - }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] - }); - - const totalWatchTimeMovies = await EntrySeen.findAll({ - include: [ - { model: Entry, as: 'entry', attributes: [] } - ], - attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime'] - ], - where: { - date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } - }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] - }); - - const totalWatchTime = { - series: totalWatchTimeSeries, - movies: totalWatchTimeMovies - } - - return res.status(200).json(totalWatchTime); -}); - -// * GET - YEAR SEEN HISTORY GROUPED BY MONTH -statisticsRouter.get('/watch-count/year/:year', async (req, res) => { - try { - const { year } = req.params; - const seriesCount = await EpisodeSeen.findAll({ - attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('COUNT', sequelize.col('*')), 'count'] - ], - where: { - date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } - }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] - }); - - const moviesCount = await EntrySeen.findAll({ - attributes: [ - [sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'], - [sequelize.fn('COUNT', sequelize.col('*')), 'count'] - ], - where: { - date_seen: { - [Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)] - } - }, - group: [sequelize.fn('MONTH', sequelize.col('date_seen'))] - }); - - res.status(200).json({ series: seriesCount, movies: moviesCount }); - } catch (error) { - console.log(error) - res.status(500).json({ error: error.message }); - } -}); +// * GET - Yearly Watch Count Grouped By Month +statisticsRouter.get('/watch-count/year/:year', statisticsController.getYearlyWatchCountGroupByMonth); module.exports = statisticsRouter; diff --git a/backend/routes/user-collection.routes.js b/backend/routes/user-collection.routes.js deleted file mode 100644 index a602ae2..0000000 --- a/backend/routes/user-collection.routes.js +++ /dev/null @@ -1,388 +0,0 @@ -const express = require('express'); -const collectionRouter = express.Router(); - -const { Sequelize } = require('sequelize'); -const Collection = require('../models/Collection'); -const UserCollectionEntry = require('../models/UserCollectionEntry'); -const Entry = require('../models/Entry'); -const EntryId = require('../models/EntryId'); -const EntryRating = require('../models/EntryRating'); -const Season = require('../models/Season'); -const Genre = require('../models/Genre'); -const Media = require('../models/Media'); - -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 -collectionRouter.get('/', async (req, res) => { - let collections; // Declare outside to broaden scope, albeit unnecessary in your given context - try { - collections = await Collection.findAll({ - include: [ - { - model: Entry, as: 'entries', - include: { model: Media, as: 'medias' } - }, - { model: Media, as: 'medias' } - ], - order: [['name', 'ASC']] - }); - res.status(200).json(collections); - } catch (error) { - console.error("Error fetching UserCollections:", error); // More detailed error logging - res.status(500).json({ error: error.message }); - } -}); - -// * GET - COLLECTION BY ID -collectionRouter.get('/:id', async (req, res) => { - try { - const collectionId = req.params.id; - - 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 - }, - }, - { model: Media, as: 'medias' }, - ], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order - }); - - if (collection) { - const collectionData = collection.get({ plain: true }); - for (let i = 0; i < collectionData.entries.length; i++) { - const genres = collectionData.entries[i].genres.map(genre => genre.name); - collectionData.entries[i].genres = genres - } - - res.status(200).json(collectionData); - } else { - res.status(404).json({ message: 'UserCollection not found' }); - } - } catch (error) { - console.log(`Error getting collection info: `, error) - res.status(500).json({ error: error.message }); - } -}); - -// * POST - CREATE COLLECTION -collectionRouter.post('/', async (req, res) => { - try { - const { name, description, userRating, posterPath } = req.body; - const isUserCollection = true; - const newUserCollection = await Collection.create({ name, description, userRating, posterPath, isUserCollection }); - res.status(201).json(newUserCollection); - } catch (error) { - res.status(400).json({ error: error.message }); - } -}); - -// * PUT - UPDATE COLLECTION -const upload = collectionPicturesUpload.fields([ - { name: 'poster', maxCount: 1 }, - { name: 'backdrop', maxCount: 1 } -]); -collectionRouter.put('/:id', upload, async (req, res) => { - try { - const collectionId = req.params.id; - const { name, description, userRating } = req.body; - - const posterFile = req.files.poster ? req.files.poster[0] : undefined; - const backdropFile = req.files.backdrop ? req.files.backdrop[0] : undefined; - - let posterPath = posterFile ? posterFile.filename : undefined; - let backdropPath = backdropFile ? backdropFile.filename : undefined; - - const updateData = { - name, - description, - userRating: parseInt(userRating, 10), - isLocal: false, - }; - - if (posterPath) { - // ? generating preview - _mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => { - const msg = `Collection Service | Generated Collection Preview`; - logToFile(msg); - }).catch((err) => { - const msg = `Collection Service | Error Generating Collection Preview`; - logToFile(msg); - logToFile(err); - }); - - await Media.create({ - mediaable: 'collection', - mediaableId: collectionId, - type: 'poster', - path: posterPath, - isLocal: true, - isSelected: true, - isCustom: true - }) - } - - if (backdropPath) { - // ? generating preview - _mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => { - const msg = `Collection Routes | Generated Collection Preview`; - logToFile(msg); - }).catch((err) => { - const msg = `Collection Routes | Error Generating Collection Preview`; - logToFile(msg); - logToFile(err); - }); - - // ? inserting data - await Media.create({ - mediaable: 'collection', - mediaableId: collectionId, - type: 'backdrop', - path: backdropPath, - isLocal: true, - isSelected: true, - isCustom: true - }) - } - - const oldCollection = 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 - }, - }, - { model: Media, as: 'medias' }, - ], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order - }); - - if (!oldCollection) - res.status(404).json({ message: 'Collection not found' }); - - await oldCollection.update(updateData); - - res.status(200).json(oldCollection); - } catch (error) { - console.log(`UserCollection update (put) error: `, error) - res.status(500).json({ error: error.message }); - } -}); - -// * PUT - REFRESH COLLECTION -collectionRouter.put('/:id/refresh', async (req, res) => { - try { - const collectionId = req.params.id; - const oldCollection = await Collection.findByPk(collectionId); - - const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId); - - if (collection) { - const collectionData = collection.get({ plain: true }); - for (let i = 0; i < collectionData.entries.length; i++) { - const genres = collectionData.entries[i].genres.map(genre => genre.name); - collectionData.entries[i].genres = genres - } - - res.status(200).json(collectionData); - } else { - res.status(404).json({ message: 'Collection not found' }); - } - } catch (error) { - console.log(`UserCollection update (put) error: `, error) - res.status(500).json({ error: error.message }); - } -}); - -// * PUT - GET COLLECTION PARTS -collectionRouter.put('/:id/parts', async (req, res) => { - try { - const collectionId = req.params.id; - - await _collectionManager.getCollectionParts(collectionId); - - 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 - }, - }, - { model: Media, as: 'medias' }, - ], - order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order - }); - - if (collection) { - const collectionData = collection.get({ plain: true }); - for (let i = 0; i < collectionData.entries.length; i++) { - const genres = collectionData.entries[i].genres.map(genre => genre.name); - collectionData.entries[i].genres = genres - } - - res.status(200).json(collectionData); - } else { - res.status(404).json({ message: 'Collection not found' }); - } - } catch (error) { - console.log(`UserCollection update (put) error: `, error) - res.status(500).json({ error: error.message }); - } -}); - -// * DELETE - DELETE COLLECTION -collectionRouter.delete('/:id', async (req, res) => { - try { - const deleted = await Collection.destroy({ where: { id: req.params.id } }); - if (deleted) { - res.status(204).send(); - } else { - res.status(404).json({ message: 'UserCollection not found' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// * POST - ADD ENTRY TO A COLLECTION -collectionRouter.post('/:collectionId/entries/:entryId', async (req, res) => { - try { - const { collectionId, entryId } = req.params; - - const newUserCollectionEntry = await UserCollectionEntry.create({ - user_collection_id: collectionId, - entry_id: entryId - }); - - // ? set a default poster if none exists - const userCollection = await Collection.findByPk(collectionId); - if (!userCollection.poster_path || userCollection.poster_path.trim() == '') { - const entry = await Entry.findByPk(entryId); - userCollection.poster_path = entry.poster_path; - await userCollection.save(); - } - - res.status(201).json(newUserCollectionEntry); - } catch (error) { - console.log(error) - res.status(400).json({ error: error.message }); - } -}); - -// * PATCH - UPDATE ENTRY ORDER IN COLLECTION -collectionRouter.patch('/:collectionId/entries/:entryId', async (req, res) => { - try { - const { collectionId, entryId } = req.params; - const { newOrder } = req.body; - - // ? getting the collectionEntry - const collectionEntry = await UserCollectionEntry.findOne({ - where: { - user_collection_id: collectionId, - entry_id: entryId - } - }); - - if (!collectionEntry) { - res.status(404).json({ message: 'UserCollectionEntry not found.' }); - } - - // ? updating - await collectionEntry.update({ order: newOrder }); - - res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' }); - } catch (error) { - console.log(`Error Updating UserCollectionEntry order: `, error); - res.status(500).json({ error: error.message }); - } -}); - -// * DELETE - REMOVE AN ENTRY FROM A COLLECTION -collectionRouter.delete('/:collectionId/entries/:entryId', async (req, res) => { - try { - const { collectionId, entryId } = req.params; - const deleted = await UserCollectionEntry.findOne({ - where: { - user_collection_id: collectionId, - entry_id: entryId - } - }); - - if (deleted) { - await deleted.destroy(); - res.status(204).send(); - } else { - res.status(404).json({ message: 'CollectionEntry not found.' }); - } - } catch (error) { - res.status(500).json({ error: error.message }); - } -}); - -// * POST - CREATE UserCollection WITH ENTRY -collectionRouter.post('/lists-with-entry', async (req, res) => { - const { listDetails, entryId, entryOrder } = req.body; // Destructure needed properties from the request body - - try { - const result = await sequelize.transaction(async (t) => { - // Step 1: Create the userCollection - const newUserCollection = await Collection.create(listDetails, { transaction: t }); - - // Step 2: Add an entry to the newly created userCollection - const newUserCollectionEntry = await UserCollectionEntry.create({ - userCollectionId: newUserCollection.id, - entryId: entryId, - entryOrder: entryOrder - }, { transaction: t }); - - return { newUserCollection, newUserCollectionEntry }; - }); - - // If the transaction is successful, send back the created userCollection and entry relationship - res.status(201).json(result); - } catch (error) { - console.error('Failed to create userCollection and add entry:', error); - res.status(500).json({ message: 'Failed to create userCollection and add entry', error: error.message }); - } -}); - -module.exports = collectionRouter; diff --git a/backend/services/collectionService.js b/backend/services/collectionService.js index 772162f..90d7e80 100644 --- a/backend/services/collectionService.js +++ b/backend/services/collectionService.js @@ -18,8 +18,23 @@ class CollectionService { return CollectionService.instance; } + async getCollections() { + const collections = await Collection.findAll({ + include: [ + { + model: Entry, as: 'entries', + include: { model: Media, as: 'medias' } + }, + { model: Media, as: 'medias' } + ], + order: [['name', 'ASC']] + }); + + return collections; + } + async getCollectionById(id) { - return await Collection.findByPk(id, { + const collection = await Collection.findByPk(id, { include: [{ model: Entry, as: 'entries', @@ -37,6 +52,8 @@ class CollectionService { }], order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order }); + + return collection; } async createOrUpdateCollection(collectionData) { diff --git a/backend/services/entryManager.js b/backend/services/entryManager.js index c93f2f7..2752270 100644 --- a/backend/services/entryManager.js +++ b/backend/services/entryManager.js @@ -20,11 +20,14 @@ const { logToFile } = require("./logService.js"); const collectionManager = require('./collectionManager.js'); const entryService = require("./entryService"); const mediaManager = require("./mediaManager.js"); +const EntryNetwork = require("../models/EntryNetwork.js"); +const networkService = require("./networkService.js"); +const Network = require("../models/Network.js"); const _collectionManager = collectionManager; const _entryService = entryService; const _mediaManager = mediaManager; - +const _networkService = networkService; class EntryManager { constructor() { @@ -128,6 +131,25 @@ class EntryManager { }) }); + // * networks + if (entryData.networks) { + const oldNetworksIds = oldEntry.networks.map(network => network.id); + for (const networkData of entryData.networks) { + // If the entry already has this network, skip it + if (oldNetworksIds.includes(networkData.id)) continue; + + // Create or update the network + const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData); + let network = oldNetwork || newNetwork; + if (!network) { + throw new NotFoundError("Network not found"); + } + + // Associate the new network with the entry + await oldEntry.addNetwork(network); + } + } + // * For TV-Series (Seasons & Episodes) if (oldEntry.is_tvseries) { // ? Only refrech if the series's status is not 'Ended' diff --git a/backend/services/entryService.js b/backend/services/entryService.js index cf46698..9569bac 100644 --- a/backend/services/entryService.js +++ b/backend/services/entryService.js @@ -15,12 +15,15 @@ const NotFoundError = require("../errors/NotFoundError"); const mediaOptimizerService = require("./mediaOptimizerService.js"); const mediaManager = require("./mediaManager.js"); const { fetchSeasonData } = require("./tmdbService.js"); +const Network = require("../models/Network.js"); +const networkService = require("./networkService.js"); const _mediaManager = mediaManager; const _mediaOptimizerService = mediaOptimizerService; +const _networkService = networkService; class EntryService { - + constructor() { if (!EntryService.instance) { EntryService.instance = this; @@ -35,6 +38,7 @@ class EntryService { { model: EntryRating, as: 'entryRating' }, { model: Media, as: 'medias' }, { model: Season, as: 'seasons' }, + { model: Network, as: 'networks' }, { model: Genre, as: 'genres', @@ -67,6 +71,7 @@ class EntryService { { model: EntrySeen, as: 'entrySeen' }, { model: Season, as: 'seasons' }, { model: Media, as: 'medias' }, + { model: Network, as: 'networks' }, { model: Collection, as: 'collections', include: [ @@ -133,7 +138,7 @@ class EntryService { let savedEntry = await movie.save(); // ? ids - const ids = await EntryId.create({ + await EntryId.create({ entry_id: savedEntry.id, tmdb_id: data.id, imdb_id: data.imdb_id, @@ -147,8 +152,23 @@ class EntryService { }) }); + // ? networks + if (data.networks) { + for (const networkData of data.networks) { + // Create or update the network + const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData); + let network = oldNetwork || newNetwork; + if (!network) { + throw new NotFoundError("Network not found"); + } + + // Associate the new network with the entry + await savedEntry.addNetwork(network); + } + } + // ? ratings - const ratings = await EntryRating.create({ + await EntryRating.create({ entry_id: savedEntry.id, user_rating: 0, tmdb_rating: data.vote_average, @@ -260,6 +280,59 @@ class EntryService { return updatedEntry; } + async updateEntryRatings(id, entryRatingsData) { + if (!id) { + throw new BadRequestError("Entry id not provided"); + } + + let entry = await Entry.findByPk(id, { + include: [ + { model: EntryRating, as: 'entryRating' }, + ] + }); + + if (!entry) { + throw new NotFoundError("Entry with the provided id was not found") + } + + if (entry.entryRating.id != entryRatingsData.id) { + throw new BadRequestError("EntryRatings id does not match"); + } + + entry.entryRating.user_rating = entryRatingsData.user_rating ?? entry.entryRating.user_rating; + entry.entryRating.tmdb_rating = entryRatingsData.tmdb_rating ?? entry.entryRating.tmdb_rating; + entry.entryRating.imdb_rating = entryRatingsData.imdb_rating ?? entry.entryRating.imdb_rating; + entry.entryRating.rotten_tomatoes_rating = entryRatingsData.rotten_tomatoes_rating ?? entry.entryRating.rotten_tomatoes_rating; + + return await entry.entryRating.save(); + } + + async updateEntryIds(id, entryIdsData) { + if (!id) { + throw new BadRequestError("Entry id not provided"); + } + + let entry = await Entry.findByPk(id, { + include: [ + { model: EntryId, as: 'entryId' }, + ] + }); + + if (!entry) { + throw new NotFoundError("Entry with the provided id was not found") + } + + if (entry.entryRating.id != entryRatingsData.id) { + throw new BadRequestError("EntryIds id does not match"); + } + + entry.entryId.tmdb_id = entryIdsData.tmdb_id ?? entry.entryId.tmdb_id; + entry.entryId.imdb_id = entryIdsData.imdb_id ?? entry.entryId.imdb_id; + entry.entryId.tvdb_id = entryIdsData.tvdb_id ?? entry.entryId.tvdb_id; + + await entry.entryId.save(); + } + async deleteEntryById(id) { if (!id) { throw new BadRequestError("Entry id not provided"); diff --git a/backend/services/episodeService.js b/backend/services/episodeService.js new file mode 100644 index 0000000..cd40311 --- /dev/null +++ b/backend/services/episodeService.js @@ -0,0 +1,73 @@ +const moment = require("../utils/moment"); + +const { Op } = require("sequelize") +const Episode = require("../models/Episode"); +const Season = require("../models/Season"); +const Entry = require("../models/Entry"); +const EntryId = require("../models/EntryId"); +const Media = require("../models/Media"); + +const BadRequestError = require("../errors/BadRequestError"); + +class EpisodeService { + + constructor() { + if (!EpisodeService.instance) { + EpisodeService.instance = this; + } + return EpisodeService.instance; + } + + async getEpisodesBetweenDates(startDate, endDate) { + if (!startDate) { + throw new BadRequestError("Start Date not provided"); + } + + if (!endDate) { + throw new BadRequestError("end Date not provided"); + } + + const formatedStartDate = moment(startDate).format('YYYY-MM-DD'); + const formatedEndDate = moment(endDate).format('YYYY-MM-DD'); + + // fetch episodes that aired within the current month + const episodes = await Episode.findAll({ + where: { + air_date: { + [Op.between]: [formatedStartDate, formatedEndDate] + }, + }, + include: [ + { + model: Season, + as: 'season', + include: { + model: Entry, + as: 'entry', + include: [ + { model: EntryId, as: 'entryId' }, + { + model: Media, + as: 'medias', + }, + ], + } + } + ] + }); + + const modifiedEpisodes = episodes.map(episode => { + const episodeJSON = episode.toJSON(); + if (episodeJSON.season && episodeJSON.season.entry) { + episodeJSON.entry = episodeJSON.season.entry; + episodeJSON.season.entry = null; + } + return episodeJSON; + }); + + return modifiedEpisodes; + } + +} + +module.exports = new EpisodeService(); diff --git a/backend/services/maintenanceService.js b/backend/services/maintenanceService.js index 7a7ba7d..7786d4d 100644 --- a/backend/services/maintenanceService.js +++ b/backend/services/maintenanceService.js @@ -9,134 +9,149 @@ const configService = require('./configService'); const _configService = configService; -async function deleteMissingFilesEntries(dry = false) { - const allMedia = await Media.findAll(); +class MaintenanceService { - // Getting the userDataPath to store the images - const dataPath = await _configService.getMediaFolder(); - - // Handling different media types - const mediaTypeFolder = { - 'entryposter': path.join(dataPath, 'images', 'entries', 'posters'), - 'entrylogo': path.join(dataPath, 'images', 'entries', 'logos'), - 'entrybackdrop': path.join(dataPath, 'images', 'entries', 'backdrops'), - - 'collectionposter': path.join(dataPath, 'images', 'collections', 'posters'), - 'collectionlogo': path.join(dataPath, 'images', 'collections', 'logos'), - 'collectionbackdrop': path.join(dataPath, 'images', 'collections', 'backdrops') - }; - - let missingFiles = []; - for (let i = 0; i < allMedia.length; i++) { - const folderType = `${allMedia[i].mediaable}${allMedia[i].type.replace("_preview", "")}`; - - const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path) - if (!fs.existsSync(filePath)) { - missingFiles.push(allMedia[i]); + constructor() { + if (!MaintenanceService.instance) { + MaintenanceService.instance = this; } + return MaintenanceService.instance; } - let removed = { - 'posters': 0, - 'logos': 0, - 'backdrops': 0 - }; + /** + * Delete orphan media records from database, + * orphan media records are media records that exist in the database + * but do not have a file in the `folder data` + * @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false` + */ + async deleteOrphanMediaRecords(dry = false) { + const allMedia = await Media.findAll(); - // if (missingFiles.length == 0) - // return removed; + // Getting the userDataPath to store the images + const dataPath = await _configService.getMediaFolder(); - for (let i = 0; i < missingFiles.length; i++) { - removed[missingFiles[i].type + 's'] += 1; - if (!dry) missingFiles[i].destroy(); - } + // Handling different media types + const mediaTypeFolder = { + 'entryposter': path.join(dataPath, 'images', 'entries', 'posters'), + 'entrylogo': path.join(dataPath, 'images', 'entries', 'logos'), + 'entrybackdrop': path.join(dataPath, 'images', 'entries', 'backdrops'), - if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) - else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) + 'collectionposter': path.join(dataPath, 'images', 'collections', 'posters'), + 'collectionlogo': path.join(dataPath, 'images', 'collections', 'logos'), + 'collectionbackdrop': path.join(dataPath, 'images', 'collections', 'backdrops') + }; - return removed; -} -/** - * Delete orphan files from media folder data, - * orphan files are files that exist in the `folder data` - * but do not have an instance in the database - * @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false` - */ -async function deleteOrphanFiles(dry = false) { - // Getting the userDataPath to store the images - const dataPath = _configService.getMediaFolder(); + let missingFiles = []; + for (let i = 0; i < allMedia.length; i++) { + const folderType = `${allMedia[i].mediaable}${allMedia[i].type.replace("_preview", "")}`; - // ? Getting the path of all media files and putting them in an array - // const allMedia = (await Media.findAll()).map(m => { - // if (m.mediaable == 'entry') - // return path.join(dataPath, 'images', 'entries', m.type + 's', m.path) - // else if (m.mediaable == 'collection') - // return path.join(dataPath, 'images', 'collections', m.type + 's', m.path) - // }); - - // ? Getting the name (without extention) of all media in database - const allMedia = (await Media.findAll()).map(m => { - return m.path.split('.')[0] - }); - - - // ? Loop trough the files of the images folder and check - // ? if a file doesnt exist in the allMedia array and mark it to delete - const mediaTypeFolder = { - 'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'), - 'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'), - 'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'), - - 'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'), - 'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops') - }; - - // * counter - let removed = { - 'posters': 0, - 'logos': 0, - 'backdrops': 0 - }; - - // Iterate over each media type directory and check for orphan files - for (let folderType in mediaTypeFolder) { - const directory = mediaTypeFolder[folderType]; - try { - // ? getting all files inside that folder - const files = await fsPromises.readdir(directory).then(); - // console.log(`${directory}, files count: ${files.length}`); - - // Check each file in the directory - for (let file of files) { - 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 - // const hasJpgFormat = allMedia.includes(filePath.replace("_preview.jpg", ".jpg")); - // const hasPngFormat = allMedia.includes(filePath.replace("_preview.jpg", ".png")); - // const hasGifFormat = allMedia.includes(filePath.replace("_preview.jpg", ".gif")); - - // preparing the file name - const fileName = file.split('.')[0].replace("_preview", ""); - const isInDatabase = allMedia.includes(fileName); - - // if the file isn't in database even on other extentions then delete it - if (!isInDatabase) { - removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files - if (!dry) await fsPromises.unlink(filePath); - } + const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path) + if (!fs.existsSync(filePath)) { + missingFiles.push(allMedia[i]); } - } catch (err) { - console.error(`Error handling files in ${directory}:`, err); } + + let removed = { + 'posters': 0, + 'logos': 0, + 'backdrops': 0 + }; + + // if (missingFiles.length == 0) + // return removed; + + for (let i = 0; i < missingFiles.length; i++) { + removed[missingFiles[i].type + 's'] += 1; + if (!dry) missingFiles[i].destroy(); + } + + if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) + else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) + + return removed; } - if (dry) logToFile(`Run a dry orphan files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) - else logToFile(`Run an orphan files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) + /** + * Delete orphan files from media folder data, + * orphan files are files that exist in the `folder data` + * but do not have an instance in the database + * @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false` + */ + async deleteOrphanFiles(dry = false) { + // Getting the userDataPath to store the images + const dataPath = _configService.getMediaFolder(); + + // ? Getting the path of all media files and putting them in an array + // const allMedia = (await Media.findAll()).map(m => { + // if (m.mediaable == 'entry') + // return path.join(dataPath, 'images', 'entries', m.type + 's', m.path) + // else if (m.mediaable == 'collection') + // return path.join(dataPath, 'images', 'collections', m.type + 's', m.path) + // }); + + // ? Getting the name (without extention) of all media in database + const allMedia = (await Media.findAll()).map(m => { + return m.path.split('.')[0] + }); + + + // ? Loop trough the files of the images folder and check + // ? if a file doesnt exist in the allMedia array and mark it to delete + const mediaTypeFolder = { + 'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'), + 'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'), + 'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'), + + 'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'), + 'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops') + }; + + // * counter + let removed = { + 'posters': 0, + 'logos': 0, + 'backdrops': 0 + }; + + // Iterate over each media type directory and check for orphan files + for (let folderType in mediaTypeFolder) { + const directory = mediaTypeFolder[folderType]; + try { + // ? getting all files inside that folder + const files = await fsPromises.readdir(directory).then(); + // console.log(`${directory}, files count: ${files.length}`); + + // Check each file in the directory + for (let file of files) { + 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 + // const hasJpgFormat = allMedia.includes(filePath.replace("_preview.jpg", ".jpg")); + // const hasPngFormat = allMedia.includes(filePath.replace("_preview.jpg", ".png")); + // const hasGifFormat = allMedia.includes(filePath.replace("_preview.jpg", ".gif")); + + // preparing the file name + const fileName = file.split('.')[0].replace("_preview", ""); + const isInDatabase = allMedia.includes(fileName); + + // if the file isn't in database even on other extentions then delete it + if (!isInDatabase) { + removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files + if (!dry) await fsPromises.unlink(filePath); + } + } + } catch (err) { + console.error(`Error handling files in ${directory}:`, err); + } + } + + if (dry) logToFile(`Run a dry orphan files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) + else logToFile(`Run an orphan files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`) + + return removed; + } - return removed; } -module.exports = { - deleteMissingFilesEntries, - deleteOrphanFiles -}; \ No newline at end of file +module.exports = new MaintenanceService(); diff --git a/backend/services/models-services/episodeService.js b/backend/services/models-services/episodeService.js deleted file mode 100644 index ba83435..0000000 --- a/backend/services/models-services/episodeService.js +++ /dev/null @@ -1,55 +0,0 @@ -const { Op } = require("sequelize") -const Episode = require("../../models/Episode"); -const moment = require("../../utils/moment"); -const Season = require("../../models/Season"); -const Entry = require("../../models/Entry"); -const EntryId = require("../../models/EntryId"); -const Media = require("../../models/Media"); - - -async function getEpisodesBetweenDates(startDate, endDate) { - const formatedStartDate = moment(startDate).format('YYYY-MM-DD'); - const formatedEndDate = moment(endDate).format('YYYY-MM-DD'); - - // fetch episodes that aired within the current month - const episodes = await Episode.findAll({ - where: { - air_date: { - [Op.between]: [formatedStartDate, formatedEndDate] - }, - }, - include: [ - { - model: Season, - as: 'season', - include: { - model: Entry, - as: 'entry', - include: [ - { model: EntryId, as: 'entryId' }, - { - model: Media, - as: 'medias', - }, - ], - } - } - ] - }); - - const modifiedEpisodes = episodes.map(episode => { - const episodeJSON = episode.toJSON(); - if (episodeJSON.season && episodeJSON.season.entry) { - episodeJSON.entry = episodeJSON.season.entry; - episodeJSON.season.entry = null; - } - return episodeJSON; - }); - - return modifiedEpisodes; -} - - -module.exports = { - getEpisodesBetweenDates, -} \ No newline at end of file diff --git a/backend/settings.json.example b/backend/settings.json.example new file mode 100644 index 0000000..67886cd --- /dev/null +++ b/backend/settings.json.example @@ -0,0 +1,14 @@ +{ + "userDataPath": "C:\\Users\\\\Documents\\Showy Data", + "tmdbApiUrl": "https://api.themoviedb.org/3", + "tmdbApiKey": "your_tmdb_api_key", + "frontPort": "8000", + "backPort": 4000, + "portableMode": "", + "libraryViewMode": "grid", + "favoritViewMode": "", + "watchlistViewMode": "grid", + "CollectionsViewMode": "", + "CollectionItemsViewMode": "", + "favoritsViewMode": "" +} \ No newline at end of file