Major Backend SI Update part 2: added controllers
This commit is contained in:
1 parent
a51e207707
commit
dbb00fdb61
38 files changed
+2129
-1231
No files matched your search
@@ -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();
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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);
|
||||
}
|
||||
module.exports = new ImportController();
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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();
|
||||
@@ -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());
|
||||
}
|
||||
module.exports = new SettingsController();
|
||||
@@ -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();
|
||||
Reference in new issue
Block a user