Major Backend Single Responsibility Update part 1

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

No files matched your search

+39 -390
View File
@@ -1,351 +1,27 @@
const express = require('express');
const entryRouter = express.Router();
const { fetchEntryData, fetchCollectionData } = require('../services/tmdbService');
const { saveEntry, refrechEntry, SyncSeriesData } = require('../services/models-services/entryService');
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require('../services/importerService');
const { entryPicturesUpload } = require('../services/mutlerStorageLocations');
const { doGeneratePreview } = require('../services/mediaService');
const { Sequelize } = require('sequelize');
const Entry = require('../models/Entry');
const EntryId = require('../models/EntryId');
const EntryRating = require('../models/EntryRating');
const Genre = require('../models/Genre');
const EntrySeen = require('../models/EntrySeen');
const Season = require('../models/Season');
const Media = require('../models/Media');
const Episode = require('../models/Episode');
const Collection = require('../models/Collection');
const { upsertOfficialCollection } = require('../services/models-services/collectionService');
const { logToFile } = require('../services/logService');
const entryController = require('../controllers/entryController');
const mediaOptimizerService = require('../services/mediaOptimizerService');
// ! /entries
// * GET - ALL ENTRIES
entryRouter.get('/', async (req, res) => {
const entries = await Entry.findAll({
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Media, as: 'medias' },
{ model: Season, as: 'seasons' },
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre ID
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
]
});
entryRouter.get('/sync-series', entryController.syncSeries);
// converting genres from object list to string list
const entriesWithGenreNames = entries.map(entry => ({
...entry.get({ plain: true }),
genres: entry.genres.map(genre => genre.name) // Convert genre objects to string array
}));
entryRouter.get('/', entryController.getAllEntries);
entryRouter.get('/:id', entryController.getEntryById);
entryRouter.post('/', entryController.fetchAndSaveNewEntry);
entryRouter.put('/:id', entryController.updateEntry);
entryRouter.delete('/:id', entryController.deleteEntry);
res.status(200).json(entriesWithGenreNames);
});
// * GET - SYNC ALL ENTIRES DATA
entryRouter.get('/sync-series', async (req, res, next) => {
try {
const entries = await SyncSeriesData();
res.status(201).json(entries);
} catch (error) {
next(error)
}
});
// * GET ENTRY BY ID
entryRouter.get('/:id', async (req, res) => {
try {
const { id } = req.params;
if (id == null) { // ! entry id not provided
res.status(404).json({ message: 'Entry id not provided' });
}
let entry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{
model: Collection, as: 'collections',
include: [
{ model: Media, as: 'medias' }
]
},
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre ID
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
],
order: [
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
]
});
if (!entry) { // ! entry not found
res.status(404).json({ message: 'Entry not found' });
}
const entryObjectData = entry.get({ plain: true });
const genres = entryObjectData.genres.map(genre => genre.name);
entryObjectData.genres = genres;
res.status(200).json(entryObjectData);
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error);
}
});
// * GET - Get seasons of an entry
entryRouter.get('/:id/seasons', async (req, res) => {
try {
const { id } = req.params;
if (id == null) { // ! entry id not provided
res.status(404).json({ message: 'Entry id not provided' });
}
const entry = await Entry.findByPk(id);
if (!entry) {
res.status(404).json({ message: 'Entry not found' });
}
const seasons = await Season.findAll({
where: {
entry_id: id
},
attributes: ['id', 'season_number'],
include: [
{ model: Episode, as: 'episodes', attributes: ['id', 'episode_number'], }
],
order: [
['season_number', 'ASC'],
[{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'],
]
})
if (seasons.length == 0) { // ! no content
res.status(404).json({ message: 'No seasons' });
}
res.status(200).json(seasons);
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error);
}
});
// * POST - FETCH AND CREATE USING TMDB ID
entryRouter.post('/', async (req, res) => {
const { tmdb_id, is_tvserie } = req.body;
const entryData = await fetchEntryData(tmdb_id, is_tvserie);
const entry = await saveEntry(entryData);
if (entryData.belongs_to_collection) {
upsertOfficialCollection(entryData.belongs_to_collection.id);
}
res.status(201).json(entry);
});
// ! import routes
entryRouter.post('/bulk-import-movies', async (req, res) => {
const { movies } = req.body;
let entries = [];
try {
entries = await bulkImportMovies(movies);
} catch (error) {
res.status(500);
}
res.status(201).json(entries);
});
entryRouter.post('/bulk-import-tmdb', async (req, res) => {
const { values } = req.body;
let entries = [];
try {
entries = await bulkImportTmdb(values);
} catch (error) {
res.status(500);
}
res.status(201).json(entries);
});
entryRouter.post('/bulk-import-episodes-seen', async (req, res) => {
const { values } = req.body;
let createdRows = 0;
try {
createdRows = await bulkImportEpisodes(values);
console.log(`Episodes Seen - counts ${episodes.length}`)
} catch (error) {
res.status(500);
}
res.status(201).json(createdRows);
});
// + import routes end
// * PUT - ENTRY UPDATE
entryRouter.put('/:id', async (req, res) => {
const { id } = req.params;
const { entryData } = req.body;
// ? checking if the provied id is valid
const oldEntry = await Entry.findByPk(id);
if (!oldEntry)
return res.status(404).json({ message: `Entry with the provided id was not found` });
// ? updating
await oldEntry.update(entryData);
// ? returning a new entry with updated values
// let includes = [
// { model: EntryId, as: 'entryId' },
// { model: EntryRating, as: 'entryRating' },
// { model: EntrySeen, as: 'entrySeen' },
// { model: Media, as: 'medias' },
// {
// model: Genre,
// as: 'genres',
// attributes: ['name'],
// through: {
// attributes: []
// }
// }
// ];
// if (oldEntry.is_tvseries) includes.push({ model: Season, as: 'seasons' });
// const updatedEntry = await Entry.findByPk(id, {
// include: includes,
// order: [
// [{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
// ]
// });
const updatedEntry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: EntrySeen, as: 'entrySeen' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{
model: Collection, as: 'collections',
include: [
{ model: Media, as: 'medias' }
]
},
{
model: Genre,
as: 'genres',
attributes: ['name'], // Only fetch the genre ID
through: {
attributes: [] // Do not fetch any attributes from the join table
}
}
],
order: [
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
]
});
const entryObjectData = updatedEntry.get({ plain: true });
const genres = entryObjectData.genres.map(genre => genre.name);
entryObjectData.genres = genres;
res.status(201).json(entryObjectData);
});
// * GET - REQUEST ENTRY REFRECH
entryRouter.get('/:id/refresh', async (req, res, next) => {
const { id } = req.params;
try {
const entry = await refrechEntry(id);
res.status(201).json(entry);
} catch (error) {
next(error)
}
});
// * GET - REQUEST ENTRY REFRECH
entryRouter.get('/:id/fetch-collection', async (req, res, next) => {
const { id } = req.params;
try {
const oldEntry = await Entry.findByPk(id, {
include: [
{ model: EntryId, as: 'entryId' }
]
})
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
if (entryData.belongs_to_collection) {
let collectionData = entryData.belongs_to_collection;
const [oldCollection, createdCollection] = await Collection.findOrCreate({
where: { tmdbId: collectionData.id },
defaults: {
name: collectionData.name,
posterPath: collectionData.poster_path,
backdropPath: collectionData.backdrop_path,
}
});
let userCollection = oldCollection || createdCollection;
if (userCollection) {
collectionData = await fetchCollectionData(collectionData.id);
const partIds = collectionData.parts.map(part => part.id);
const entries = await Entry.findAll({
include: [{
model: EntryId,
as: 'entryId',
where: {
tmdb_id: {
[Sequelize.Op.in]: partIds
}
}
}]
});
await userCollection.setEntries(entries);
await userCollection.update({ description: collectionData.overview })
}
res.status(201).json(userCollection);
}
} catch (error) {
next(error)
}
});
entryRouter.get('/:id/seasons', entryController.getEntrySeasons);
entryRouter.put('/:id/refresh', entryController.refrechEntry);
entryRouter.put('/:id/fetch-collection', entryController.fetchEntryCollection);
// ! ENTRY MEDIA
// * POST - ADD NEW ENTRY MEDIA (poster/backdrop/logo)
@@ -368,43 +44,35 @@ entryRouter.post('/:id/media', upload, async (req, res) => {
// Function to handle media creation based on uploaded file type
const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]);
if (fileType) {
const file = req.files[fileType][0];
const createdMedia = await Media.create({
mediaable: 'entry',
mediaableId: id,
type: fileType,
path: file.filename,
isLocal: true,
isSelected: false,
isCustom: true
});
// ? generating low resolution preview
// const fileNameWithoutExt = file.filename.split('.')[0];
// const originalPath = file.path;
// let previewWidth = 342; // ? poster preview width
// if (fileType == 'backdrop') previewWidth = 780;
// if (fileType == 'logo') previewWidth = 300;
// const previewPath = path.join(file.destination, `${fileNameWithoutExt}_preview.jpg`);
// generatePreview(originalPath, previewPath, previewWidth);
doGeneratePreview('entries', fileType + 's', file.filename).then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
const msg = `Media Route | Generated Entry Preview`
logToFile(msg);
}).catch((err) => {
const msg = `Media Route | Error Generating Entry Preview`
logToFile(msg);
});
return res.status(200).json(createdMedia);
if (!fileType) {
return res.status(400).json({ message: 'Invalid media type' });
}
return res.status(400).json({ message: 'Invalid media type' });
const file = req.files[fileType][0];
const createdMedia = await Media.create({
mediaable: 'entry',
mediaableId: id,
type: fileType,
path: file.filename,
isLocal: true,
isSelected: false,
isCustom: true
});
// ? generating low resolution preview
mediaOptimizerService.doGeneratePreview('entries', fileType + 's', file.filename).then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
const msg = `Media Route | Generated Entry Preview`
logToFile(msg);
}).catch((err) => {
const msg = `Media Route | Error Generating Entry Preview`
logToFile(msg);
});
return res.status(200).json(createdMedia);
});
// * PUT - SET ENTRY MEDIA AS SELECTED
@@ -458,7 +126,6 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => {
if (otherMedia) {
otherMedia.update({ isSelected: true });
}
// return res.status(404).json({ message: 'Media not found' });
}
await Media.destroy({ where: { id: mediaId } })
@@ -466,23 +133,5 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => {
res.status(200).json();
});
// * DELETE - ENTRY BY ID
entryRouter.delete('/:id', async (req, res) => {
const { id } = req.params;
try {
const numDeleted = await Entry.destroy({
where: { id: id }
});
if (numDeleted) {
res.status(200).json({ message: `Entry with ID ${id} deleted.` });
} else {
res.status(404).json({ message: `Entry with ID ${id} not found.` });
}
} catch (error) {
res.status(500).json({ message: `Error deleting entry with ID ${id}.`, error: error.message });
}
});
module.exports = entryRouter;
+11
View File
@@ -0,0 +1,11 @@
const express = require('express');
const importRouter = express.Router();
const importController = require('../controllers/importController');
// ! /import
importRouter.post('/movies', importController.importMovies);
importRouter.post('/tmdb', importController.importTMBD);
importRouter.post('/episodes-watch-history', importController.importEpisodeWatchHistory);
module.exports = importRouter;
+6 -5
View File
@@ -1,12 +1,13 @@
const express = require('express');
const mediaRouter = express.Router();
const path = require('path');
const fs = require('fs');
const { getSettings } = require('../services/settingsService');
const { doGeneratePreview } = require('../services/mediaService');
const configService = require('../services/configService.js');
const { logToFile } = require('../services/logService');
const mediaOptimizerService = require('../services/mediaOptimizerService.js');
const mediaRouter = express.Router();
const _mediaOptimizerService = mediaOptimizerService;
// ! /media
// ? Routes : media access routes
@@ -21,7 +22,7 @@ mediaRouter.get('/:category/:type/:size/:fileName', (req, res, next) => {
return res.status(404).send('Type Not Found');
}
const settings = getSettings();
const settings = configService.getSettings();
const dataPath = settings.userDataPath;
const mediaPath = path.join(dataPath, 'images', category, type);
@@ -52,7 +53,7 @@ mediaRouter.get('/:category/:type/:size/:fileName', (req, res, next) => {
// if (type == 'backdrops') previewWidth = 780;
// if (type == 'logos') previewWidth = 300;
doGeneratePreview(category, type, fileName).then((result) => {
_mediaOptimizerService.doGeneratePreview(category, type, fileName).then((result) => {
const stream = fs.createReadStream(filePath);
stream.pipe(res);
logToFile(`Media Route | Generated Preview`);
+2
View File
@@ -13,6 +13,7 @@ const customMediaRouter = require('./custom-media.routes');
const mediaRouter = require('./media.routes');
const episodeRouter = require('./episode.routes');
const pingRouter = require('./ping.routes');
const importRouter = require('./import.routes');
const router = express.Router();
router.use('/media', mediaRouter);
@@ -28,6 +29,7 @@ router.use('/episode-seen', episodeSeenRouter);
router.use('/custom-media', customMediaRouter);
router.use('/import', importRouter);
router.use('/statistics', statisticsRouter);
router.use('/settings', settingsRouter);
router.use('/maintenance', maintenanceRouter);
+3 -26
View File
@@ -1,33 +1,10 @@
const express = require('express');
const { updateSettings, getSettings } = require('../services/settingsService');
const settingsRouter = express.Router();
const settingsFileFormat = {
"dataFolderPath": "",
"tmdbApiUrl": "",
"tmdbApiKey": "",
"frontPort": "",
"backPort": "",
"portableMode": "",
};
const settingsController = require('../controllers/settingsController');
// ! /settings
settingsRouter.put('/', async (req, res) => {
const settings = req.body;
updateSettings(settings);
res.status(200).send(getSettings());
});
settingsRouter.get('/', (req, res) => {
try {
const settings = getSettings();
res.status(200).json(settings);
} catch (err) {
res.status(500).send('Error retrieving settings');
}
});
settingsRouter.get('/', settingsController.getSettings);
settingsRouter.put('/', settingsController.updateSettings);
module.exports = settingsRouter;
+9 -26
View File
@@ -1,8 +1,6 @@
const express = require('express');
const collectionRouter = express.Router();
const { doGeneratePreview } = require('../services/mediaService');
const { Sequelize } = require('sequelize');
const Collection = require('../models/Collection');
const UserCollectionEntry = require('../models/UserCollectionEntry');
@@ -13,9 +11,13 @@ const Season = require('../models/Season');
const Genre = require('../models/Genre');
const Media = require('../models/Media');
const { getCollectionParts, upsertOfficialCollection } = require('../services/models-services/collectionService');
const { collectionPicturesUpload } = require('../services/mutlerStorageLocations');
const { logToFile } = require('../services/logService');
const collectionManager = require('../services/collectionManager');
const mediaOptimizerService = require('../services/mediaOptimizerService');
const _mediaOptimizerService = mediaOptimizerService;
const _collectionManager = collectionManager;
// ! /collections
// * GET - ALL COLLECTIONS
@@ -120,7 +122,7 @@ collectionRouter.put('/:id', upload, async (req, res) => {
if (posterPath) {
// ? generating preview
doGeneratePreview("collections", 'posters', posterPath).then((result) => {
_mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => {
const msg = `Collection Service | Generated Collection Preview`;
logToFile(msg);
}).catch((err) => {
@@ -142,7 +144,7 @@ collectionRouter.put('/:id', upload, async (req, res) => {
if (backdropPath) {
// ? generating preview
doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => {
_mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => {
const msg = `Collection Routes | Generated Collection Preview`;
logToFile(msg);
}).catch((err) => {
@@ -202,26 +204,7 @@ collectionRouter.put('/:id/refresh', async (req, res) => {
const collectionId = req.params.id;
const oldCollection = await Collection.findByPk(collectionId);
const collection = await upsertOfficialCollection(oldCollection.tmdbId);
// const collection = await Collection.findByPk(collectionId, {
// include: [{
// model: Entry,
// as: 'entries',
// include: [
// { model: EntryId, as: 'entryId' },
// { model: EntryRating, as: 'entryRating' },
// { model: Season, as: 'seasons' },
// { model: Media, as: 'medias' },
// { model: Genre, as: 'genres' },
// ],
// through: {
// model: UserCollectionEntry,
// attributes: ['order'], // attributes (to include) from the join model
// },
// }],
// order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
// });
const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId);
if (collection) {
const collectionData = collection.get({ plain: true });
@@ -245,7 +228,7 @@ collectionRouter.put('/:id/parts', async (req, res) => {
try {
const collectionId = req.params.id;
await getCollectionParts(collectionId);
await _collectionManager.getCollectionParts(collectionId);
const collection = await Collection.findByPk(collectionId, {
include: [