Major Backend SI Update part 2: added controllers

This commit is contained in:
X4Lo committed 2025-02-15 22:42:57 +01:00
1 parent a51e207707
commit dbb00fdb61
38 files changed
+2129 -1231

No files matched your search

+45
View File
@@ -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;
-33
View File
@@ -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;
-27
View File
@@ -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;
-30
View File
@@ -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;
+10 -94
View File
@@ -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;
+2
View File
@@ -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);
+9 -127
View File
@@ -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;
+2 -10
View File
@@ -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;
+3 -9
View File
@@ -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;
+6 -21
View File
@@ -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;
+4 -72
View File
@@ -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;
+2 -3
View File
@@ -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;
+1 -7
View File
@@ -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);
+8 -82
View File
@@ -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;
+7 -112
View File
@@ -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;
-388
View File
@@ -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;