Normalize to double quotes across all files with Prettier

This commit is contained in:
X4Lo committed 2026-06-21 22:28:08 +01:00
1 parent 73bff72cec
commit a5659cf4c8
190 files changed
+9523 -8859

No files matched your search

File diff suppressed because it is too large. Load diff
+170 -112
View File
@@ -1,24 +1,23 @@
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 { 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 { 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;
@@ -41,37 +40,41 @@ class CollectionController {
include: [
{
model: Entry,
as: 'entries',
as: "entries",
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' },
{ 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
attributes: ["order"], // attributes (to include) from the join model
},
},
{ model: Media, as: 'medias' },
{ model: Media, as: "medias" },
],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
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
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' });
res.status(404).json({ message: "UserCollection not found" });
}
} catch (error) {
console.log(`Error getting collection info: `, error)
console.log(`Error getting collection info: `, error);
res.status(500).json({ error: error.message });
}
}
@@ -81,7 +84,13 @@ class CollectionController {
try {
const { name, description, userRating, posterPath } = req.body;
const isUserCollection = true;
const newUserCollection = await Collection.create({ name, description, userRating, posterPath, isUserCollection });
const newUserCollection = await Collection.create({
name,
description,
userRating,
posterPath,
isUserCollection,
});
res.status(201).json(newUserCollection);
} catch (error) {
res.status(400).json({ error: error.message });
@@ -95,7 +104,9 @@ class CollectionController {
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;
const backdropFile = req.files.backdrop
? req.files.backdrop[0]
: undefined;
let posterPath = posterFile ? posterFile.filename : undefined;
let backdropPath = backdropFile ? backdropFile.filename : undefined;
@@ -109,90 +120,113 @@ class CollectionController {
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);
});
_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);
});
// Deselect existing posters for this collection
await Media.update(
{ isSelected: false },
{ where: { mediaable: 'collection', mediaableId: collectionId, type: 'poster', isSelected: true } }
{
where: {
mediaable: "collection",
mediaableId: collectionId,
type: "poster",
isSelected: true,
},
},
);
await Media.create({
mediaable: 'collection',
mediaable: "collection",
mediaableId: collectionId,
type: 'poster',
type: "poster",
path: posterPath,
isLocal: true,
isSelected: true,
isCustom: 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);
});
_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);
});
// Deselect existing backdrops for this collection
await Media.update(
{ isSelected: false },
{ where: { mediaable: 'collection', mediaableId: collectionId, type: 'backdrop', isSelected: true } }
{
where: {
mediaable: "collection",
mediaableId: collectionId,
type: "backdrop",
isSelected: true,
},
},
);
// ? inserting data
await Media.create({
mediaable: 'collection',
mediaable: "collection",
mediaableId: collectionId,
type: 'backdrop',
type: "backdrop",
path: backdropPath,
isLocal: true,
isSelected: true,
isCustom: 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
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' },
{ model: Media, as: "medias" },
],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
order: [
[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), "ASC"],
], // sort by 'order' in ascending order
});
if (!oldCollection)
res.status(404).json({ message: 'Collection not found' });
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)
console.log(`UserCollection update (put) error: `, error);
res.status(500).json({ error: error.message });
}
}
@@ -202,21 +236,25 @@ class CollectionController {
const collectionId = req.params.id;
const oldCollection = await Collection.findByPk(collectionId);
const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId);
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
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' });
res.status(404).json({ message: "Collection not found" });
}
} catch (error) {
console.log(`UserCollection update (put) error: `, error)
console.log(`UserCollection update (put) error: `, error);
res.status(500).json({ error: error.message });
}
}
@@ -231,37 +269,41 @@ class CollectionController {
include: [
{
model: Entry,
as: 'entries',
as: "entries",
include: [
{ model: EntryId, as: 'entryId' },
{ model: EntryRating, as: 'entryRating' },
{ model: Season, as: 'seasons' },
{ model: Media, as: 'medias' },
{ model: Genre, as: 'genres' },
{ 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
attributes: ["order"], // attributes (to include) from the join model
},
},
{ model: Media, as: 'medias' },
{ model: Media, as: "medias" },
],
order: [[Sequelize.literal("`entries->UserCollectionEntry`.`order`"), 'ASC']], // sort by 'order' in ascending order
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
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' });
res.status(404).json({ message: "Collection not found" });
}
} catch (error) {
console.log(`UserCollection update (put) error: `, error)
console.log(`UserCollection update (put) error: `, error);
res.status(500).json({ error: error.message });
}
}
@@ -269,11 +311,13 @@ class CollectionController {
// todo: move to collection service
async deleteCollection(req, res) {
try {
const deleted = await Collection.destroy({ where: { id: req.params.id } });
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' });
res.status(404).json({ message: "UserCollection not found" });
}
} catch (error) {
res.status(500).json({ error: error.message });
@@ -287,12 +331,15 @@ class CollectionController {
const newUserCollectionEntry = await UserCollectionEntry.create({
user_collection_id: collectionId,
entry_id: entryId
entry_id: entryId,
});
// ? set a default poster if none exists
const userCollection = await Collection.findByPk(collectionId);
if (!userCollection.poster_path || userCollection.poster_path.trim() == '') {
if (
!userCollection.poster_path ||
userCollection.poster_path.trim() == ""
) {
const entry = await Entry.findByPk(entryId);
userCollection.poster_path = entry.poster_path;
await userCollection.save();
@@ -300,7 +347,7 @@ class CollectionController {
res.status(201).json(newUserCollectionEntry);
} catch (error) {
console.log(error)
console.log(error);
res.status(400).json({ error: error.message });
}
}
@@ -315,18 +362,20 @@ class CollectionController {
const collectionEntry = await UserCollectionEntry.findOne({
where: {
user_collection_id: collectionId,
entry_id: entryId
}
entry_id: entryId,
},
});
if (!collectionEntry) {
res.status(404).json({ message: 'UserCollectionEntry not found.' });
res.status(404).json({ message: "UserCollectionEntry not found." });
}
// ? updating
await collectionEntry.update({ order: newOrder });
res.status(200).json({ message: 'UserCollectionEntry order updated successfully.' });
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 });
@@ -340,15 +389,15 @@ class CollectionController {
const deleted = await UserCollectionEntry.findOne({
where: {
user_collection_id: collectionId,
entry_id: entryId
}
entry_id: entryId,
},
});
if (deleted) {
await deleted.destroy();
res.status(204).send();
} else {
res.status(404).json({ message: 'CollectionEntry not found.' });
res.status(404).json({ message: "CollectionEntry not found." });
}
} catch (error) {
res.status(500).json({ error: error.message });
@@ -362,14 +411,19 @@ class CollectionController {
try {
const result = await sequelize.transaction(async (t) => {
// Step 1: Create the userCollection
const newUserCollection = await Collection.create(listDetails, { transaction: t });
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 });
const newUserCollectionEntry = await UserCollectionEntry.create(
{
userCollectionId: newUserCollection.id,
entryId: entryId,
entryOrder: entryOrder,
},
{ transaction: t },
);
return { newUserCollection, newUserCollectionEntry };
});
@@ -377,11 +431,15 @@ class CollectionController {
// 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 });
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();
+50 -26
View File
@@ -1,16 +1,15 @@
const EntryRating = require('../models/EntryRating');
const collectionManager = require('../services/collectionManager');
const entryManager = require('../services/entryManager');
const EntryRating = require("../models/EntryRating");
const collectionManager = require("../services/collectionManager");
const entryManager = require("../services/entryManager");
const entryService = require("../services/entryService");
const tmdbService = require('../services/tmdbService');
const asyncWrapper = require('../utils/asyncWrapper');
const tmdbService = require("../services/tmdbService");
const asyncWrapper = require("../utils/asyncWrapper");
const _collectionManager = collectionManager;
const _entryManager = entryManager;
const _entryService = entryService;
class EntryController {
constructor() {
if (!EntryController.instance) {
EntryController.instance = this;
@@ -37,7 +36,10 @@ class EntryController {
fetchAndSaveNewEntry = asyncWrapper(async (req, res) => {
const { tmdb_id, is_tvserie } = req.body;
const createdEntry = await _entryManager.fetchAndSaveNewEntry(tmdb_id, is_tvserie);
const createdEntry = await _entryManager.fetchAndSaveNewEntry(
tmdb_id,
is_tvserie,
);
res.status(201).json(createdEntry);
});
@@ -46,7 +48,11 @@ class EntryController {
const { id } = req.params;
const { entryData } = req.body;
const updatedEntry = await _entryService.updateEntryById(id, entryData, true);
const updatedEntry = await _entryService.updateEntryById(
id,
entryData,
true,
);
res.status(201).json(updatedEntry);
});
@@ -56,7 +62,10 @@ class EntryController {
const { id } = req.params;
const { entryRatings } = req.body;
const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings);
const updatedEntryRatings = await _entryService.updateEntryRatings(
id,
entryRatings,
);
res.status(200).json(updatedEntryRatings);
});
@@ -66,7 +75,10 @@ class EntryController {
const { id } = req.params;
const { entryIds } = req.body;
const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds);
const updatedEntryIds = await _entryService.updateEntryRatings(
id,
entryIds,
);
res.status(200).json(updatedEntryIds);
});
@@ -90,10 +102,10 @@ class EntryController {
getEntrySeasons = asyncWrapper(async (req, res) => {
const { id } = req.params;
const seasons = await _entryService.getEntrySeasons(id)
const seasons = await _entryService.getEntrySeasons(id);
if (seasons.length == 0) {
res.status(204).json({ message: 'Provided entry has no seasons' });
res.status(204).json({ message: "Provided entry has no seasons" });
}
res.status(200).json(seasons);
@@ -110,7 +122,7 @@ class EntryController {
refrechEntry = asyncWrapper(async (req, res, next) => {
const { id } = req.params;
const entry = await _entryManager.refrechEntryById(id)
const entry = await _entryManager.refrechEntryById(id);
res.status(201).json(entry);
});
@@ -132,7 +144,8 @@ class EntryController {
const { type } = req.params;
const { page } = req.query;
const data = await tmdbService.fetchTrending(type, page || 1);
if (!data) return res.status(500).json({ message: 'Failed to fetch trending data' });
if (!data)
return res.status(500).json({ message: "Failed to fetch trending data" });
res.status(200).json(data);
});
@@ -141,16 +154,19 @@ class EntryController {
const { type } = req.params;
const { page } = req.query;
const data = await tmdbService.fetchPopular(type, page || 1);
if (!data) return res.status(500).json({ message: 'Failed to fetch popular data' });
if (!data)
return res.status(500).json({ message: "Failed to fetch popular data" });
res.status(200).json(data);
});
// * GET - TMDB SEARCH
getTmdbSearch = asyncWrapper(async (req, res) => {
const { query, page } = req.query;
if (!query) return res.status(400).json({ message: 'Query parameter is required' });
if (!query)
return res.status(400).json({ message: "Query parameter is required" });
const data = await tmdbService.searchMulti(query, page || 1);
if (!data) return res.status(500).json({ message: 'Failed to search TMDB' });
if (!data)
return res.status(500).json({ message: "Failed to search TMDB" });
res.status(200).json(data);
});
@@ -159,7 +175,10 @@ class EntryController {
const { type } = req.params;
const { page } = req.query;
const data = await tmdbService.fetchTopRated(type, page || 1);
if (!data) return res.status(500).json({ message: 'Failed to fetch top rated data' });
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch top rated data" });
res.status(200).json(data);
});
@@ -167,16 +186,18 @@ class EntryController {
getTmdbUpcoming = asyncWrapper(async (req, res) => {
const { page } = req.query;
const data = await tmdbService.fetchUpcoming(page || 1);
if (!data) return res.status(500).json({ message: 'Failed to fetch upcoming data' });
if (!data)
return res.status(500).json({ message: "Failed to fetch upcoming data" });
res.status(200).json(data);
});
// * GET - TMDB PREVIEW (fetch details without saving to library)
getTmdbPreview = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params;
const is_tvserie = type === 'tv';
const is_tvserie = type === "tv";
const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie);
if (!data) return res.status(404).json({ message: 'Entry not found on TMDB' });
if (!data)
return res.status(404).json({ message: "Entry not found on TMDB" });
// Fetch credits in parallel
const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie);
@@ -187,10 +208,10 @@ class EntryController {
for (const c of creditsData.cast) {
credits.push({
id: c.credit_id || c.id,
cast_type: 'cast',
cast_type: "cast",
character: is_tvserie
? (c.roles?.[0]?.character || c.character || null)
: (c.character || null),
? c.roles?.[0]?.character || c.character || null
: c.character || null,
people_id: c.id,
people: {
id: c.id,
@@ -208,9 +229,12 @@ class EntryController {
title: data.title || data.name,
original_title: data.original_title || data.original_name || null,
release_date: data.release_date || data.first_air_date || null,
runtime: data.runtime || (data.episode_run_time?.[0]) || null,
runtime: data.runtime || data.episode_run_time?.[0] || null,
storyline: data.overview || null,
country: data.origin_country?.[0] || data.production_countries?.[0]?.iso_3166_1 || null,
country:
data.origin_country?.[0] ||
data.production_countries?.[0]?.iso_3166_1 ||
null,
is_tvseries: is_tvserie,
status: data.status || null,
poster_path: data.poster_path || null,
+17 -11
View File
@@ -1,8 +1,7 @@
const Entry = require("../models/Entry");
const EntrySeen = require('../models/EntrySeen');
const EntrySeen = require("../models/EntrySeen");
class EntrySeenController {
constructor() {
if (!EntrySeenController.instance) {
EntrySeenController.instance = this;
@@ -19,7 +18,7 @@ class EntrySeenController {
const entrySeen = await EntrySeen.findByPk(req.params.id);
if (!entrySeen) {
res.status(404).json({ message: 'Entry seen record not found.' });
res.status(404).json({ message: "Entry seen record not found." });
}
res.status(200).json(entrySeen);
@@ -35,7 +34,11 @@ class EntrySeenController {
}
// Create a new EntrySeen record
const newEntrySeen = await EntrySeen.create({ entry_id, date_seen, seen_with });
const newEntrySeen = await EntrySeen.create({
entry_id,
date_seen,
seen_with,
});
res.status(201).json(newEntrySeen);
}
@@ -43,26 +46,30 @@ class EntrySeenController {
const { entryId } = req.params;
const entrySeens = await EntrySeen.findAll({
where: { entry_id: entryId },
order: [['date_seen', 'DESC']]
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.' });
res
.status(404)
.json({ message: "No records found for the given entry ID." });
}
}
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 } });
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.' });
res.status(404).json({ message: "Entry seen record not found." });
}
}
@@ -70,7 +77,7 @@ class EntrySeenController {
const entrySeen = await EntrySeen.findByPk(req.params.id);
if (!entrySeen)
res.status(404).json({ message: 'Entry seen record not found.' });
res.status(404).json({ message: "Entry seen record not found." });
const deleted = await entrySeen.destroy();
@@ -78,7 +85,6 @@ class EntrySeenController {
res.status(204).send();
}
}
}
module.exports = new EntrySeenController();
+4 -3
View File
@@ -3,7 +3,6 @@ const episodeService = require("../services/episodeService");
const _episodeService = episodeService;
class EpisodeController {
constructor() {
if (!EpisodeController.instance) {
EpisodeController.instance = this;
@@ -14,13 +13,15 @@ class EpisodeController {
async getEpisodesBetweenDates(req, res) {
const { startDate, endDate } = req.params;
try {
const episodes = await _episodeService.getEpisodesBetweenDates(startDate, endDate)
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();
+38 -29
View File
@@ -4,7 +4,6 @@ const EpisodeSeen = require("../models/EpisodeSeen");
const Season = require("../models/Season");
class EpisodeSeenController {
constructor() {
if (!EpisodeSeenController.instance) {
EpisodeSeenController.instance = this;
@@ -26,7 +25,7 @@ class EpisodeSeenController {
const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
if (!episodeSeen) {
res.status(404).json({ message: 'Episode seen record not found.' });
res.status(404).json({ message: "Episode seen record not found." });
}
res.status(200).json(episodeSeen);
@@ -40,15 +39,18 @@ class EpisodeSeenController {
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" });
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" });
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 });
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 });
@@ -61,13 +63,15 @@ class EpisodeSeenController {
const { episodeId } = req.params;
const episodeSeens = await EpisodeSeen.findAll({
where: { episode_id: episodeId },
order: [['date_seen', 'DESC']]
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.' });
res
.status(404)
.json({ message: "No records found for the given episode ID." });
}
} catch (error) {
res.status(500).json({ error: error.message });
@@ -79,24 +83,29 @@ class EpisodeSeenController {
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'],
}],
include: [
{
model: Episode,
include: [
{
model: Season,
attributes: ["season_number"],
},
],
attributes: ["episode_number"],
},
],
order: [
['date_seen', 'DESC'],
[{ model: Episode }, { model: Season }, 'season_number', 'DESC'],
["date_seen", "DESC"],
[{ model: Episode }, { model: Season }, "season_number", "DESC"],
// [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this
[Episode, 'episode_number', 'DESC']]
[Episode, "episode_number", "DESC"],
],
});
res.status(200).json(episodeSeens);
} catch (error) {
console.log(`error getting episode seen of an entry: `, error)
console.log(`error getting episode seen of an entry: `, error);
res.status(500).json({ error: error.message });
}
}
@@ -105,16 +114,18 @@ class EpisodeSeenController {
try {
const { date_seen, seen_with, episode_id } = req.body;
const episodeSeen = await EpisodeSeen.findByPk(req.params.id)
const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
if (!episodeSeen)
return res.status(404).json({ message: 'Episode seen record not found.' });
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.' });
res.status(404).json({ message: "Episode seen record not found." });
}
} catch (error) {
res.status(500).json({ error: error.message });
@@ -126,19 +137,17 @@ class EpisodeSeenController {
// ? 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.' });
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();
if (deleted) res.status(204).send();
} catch (error) {
res.status(500).json({ error: error.message });
console.log(error)
console.log(error);
}
}
}
module.exports = new EpisodeSeenController();
+5 -1
View File
@@ -1,4 +1,8 @@
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require("../services/importerService");
const {
bulkImportMovies,
bulkImportTmdb,
bulkImportEpisodes,
} = require("../services/importerService");
class ImportController {
constructor() {
+1 -3
View File
@@ -1,5 +1,4 @@
class KillerController {
constructor() {
if (!KillerController.instance) {
KillerController.instance = this;
@@ -8,11 +7,10 @@ class KillerController {
}
async killBackend(req, res) {
console.log("Killing backend.")
console.log("Killing backend.");
res.status(200).json({ message: "Backend killed." });
console.log(kill);
}
}
module.exports = new KillerController();
+55 -35
View File
@@ -1,19 +1,18 @@
const path = require('path');
const fs = require('fs');
const path = require("path");
const fs = require("fs");
const Entry = require('../models/Entry');
const Media = require('../models/Media');
const Collection = require('../models/Collection');
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 asyncWrapper = require('../utils/asyncWrapper');
const configService = require("../services/configService.js");
const { logToFile } = require("../services/logService");
const mediaOptimizerService = require("../services/mediaOptimizerService.js");
const asyncWrapper = require("../utils/asyncWrapper");
const _mediaOptimizerService = mediaOptimizerService;
class MediaController {
constructor() {
if (!MediaController.instance) {
MediaController.instance = this;
@@ -21,7 +20,6 @@ class MediaController {
return MediaController.instance;
}
getMedias = asyncWrapper(async (req, res) => {
const allCustomMedia = await Media.findAll({
where: {
isCustom: true,
@@ -29,15 +27,15 @@ class MediaController {
include: [
{
model: Entry,
as: 'entry',
required: false // This ensures a LEFT OUTER JOIN
as: "entry",
required: false, // This ensures a LEFT OUTER JOIN
},
{
model: Collection,
as: 'collection',
required: false // This ensures a LEFT OUTER JOIN
}
]
as: "collection",
required: false, // This ensures a LEFT OUTER JOIN
},
],
});
res.status(200).json(allCustomMedia);
@@ -46,37 +44,57 @@ class MediaController {
getMedia(req, res, next) {
const { category, type, size, fileName } = req.params;
if (!['entries', 'collections', 'franchises', 'seasons', 'episodes', 'peoples'].includes(category)) {
return res.status(404).send('Category Not Found');
if (
![
"entries",
"collections",
"franchises",
"seasons",
"episodes",
"peoples",
].includes(category)
) {
return res.status(404).send("Category Not Found");
}
if (!['backdrops', 'posters', 'logos', 'stills', 'profiles', 'others'].includes(type)) {
return res.status(404).send('Type Not Found');
if (
![
"backdrops",
"posters",
"logos",
"stills",
"profiles",
"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(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')
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
// ? 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') {
if (err && size == "preview") {
// const originalPath = path.join(mediaPath, fileName);
// const previewFileName = fileName.split('.')[0] + '_preview.jpg'
// const previewPath = path.join(mediaPath, previewFileName);
@@ -85,14 +103,17 @@ class MediaController {
// 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);
});
_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.');
@@ -108,7 +129,6 @@ class MediaController {
}
});
}
}
module.exports = new MediaController();
+31 -12
View File
@@ -1,6 +1,6 @@
const peopleService = require("../services/peopleService");
const peopleManager = require("../services/peopleManager");
const tmdbService = require('../services/tmdbService');
const tmdbService = require("../services/tmdbService");
const _peopleService = peopleService;
const _peopleManager = peopleManager;
@@ -60,7 +60,9 @@ class PeopleController {
async fetchAndSavePersonByTmdbId(req, res) {
const { tmdb_id, pinned } = req.body;
const person = await _peopleService.fetchAndSavePersonByTmdbId(tmdb_id, { pinned: !!pinned });
const person = await _peopleService.fetchAndSavePersonByTmdbId(tmdb_id, {
pinned: !!pinned,
});
res.status(201).json(person);
}
@@ -73,7 +75,7 @@ class PeopleController {
async getPersonCredits(req, res) {
const { id } = req.params;
const person = await _peopleService.getPersonById(id);
if (!person) return res.status(404).json({ message: 'Person not found' });
if (!person) return res.status(404).json({ message: "Person not found" });
res.status(200).json(person.roles ?? []);
}
@@ -81,10 +83,15 @@ class PeopleController {
const { id } = req.params;
const person = await _peopleService.getPersonById(id);
if (!person || !person.tmdb_id) {
return res.status(404).json({ message: 'Person not found or missing TMDB ID' });
return res
.status(404)
.json({ message: "Person not found or missing TMDB ID" });
}
const data = await tmdbService.fetchPersonCombinedCredits(person.tmdb_id);
if (!data) return res.status(500).json({ message: 'Failed to fetch filmography from TMDB' });
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch filmography from TMDB" });
res.status(200).json(data);
}
@@ -93,7 +100,9 @@ class PeopleController {
const person = await _peopleService.getPersonById(id);
if (person && person.tmdb_id) {
const updatedPerson = await _peopleService.fetchAndSavePersonByTmdbId(person.tmdb_id);
const updatedPerson = await _peopleService.fetchAndSavePersonByTmdbId(
person.tmdb_id,
);
res.status(200).json(updatedPerson);
} else {
res.status(404).json({ message: "Person not found or missing TMDB ID" });
@@ -103,31 +112,41 @@ class PeopleController {
async getTmdbPopularPeople(req, res) {
const { page } = req.query;
const data = await tmdbService.fetchPopularPeople(page || 1);
if (!data) return res.status(500).json({ message: 'Failed to fetch popular people' });
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch popular people" });
res.status(200).json(data);
}
async searchTmdbPeople(req, res) {
const { query, page } = req.query;
if (!query) return res.status(400).json({ message: 'Query parameter is required' });
if (!query)
return res.status(400).json({ message: "Query parameter is required" });
const data = await tmdbService.searchPeople(query, page || 1);
if (!data) return res.status(500).json({ message: 'Failed to search TMDB people' });
if (!data)
return res.status(500).json({ message: "Failed to search TMDB people" });
res.status(200).json(data);
}
async getTmdbPersonPreview(req, res) {
const { tmdbId } = req.params;
const personData = await tmdbService.fetchPersonDetails(tmdbId);
if (!personData) return res.status(404).json({ message: 'Person not found on TMDB' });
if (!personData)
return res.status(404).json({ message: "Person not found on TMDB" });
const filmography = await tmdbService.fetchPersonCombinedCredits(tmdbId);
// Check if person already exists in local DB
let localId = null;
try {
const localPerson = await _peopleService.getPersonByTmdbId(parseInt(tmdbId));
const localPerson = await _peopleService.getPersonByTmdbId(
parseInt(tmdbId),
);
if (localPerson) localId = localPerson.id;
} catch (_) { /* not found */ }
} catch (_) {
/* not found */
}
const preview = {
tmdb_id: personData.id,
+3 -5
View File
@@ -1,5 +1,4 @@
class PingController {
constructor() {
if (!PingController.instance) {
PingController.instance = this;
@@ -8,11 +7,10 @@ class PingController {
}
ping(req, res) {
console.log("Ping Pong...")
res.status(200).json({ message: 'pong' });
}
console.log("Ping Pong...");
res.status(200).json({ message: "pong" });
}
}
module.exports = new PingController();
+16 -17
View File
@@ -2,9 +2,7 @@ const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen");
const Season = require("../models/Season");
class SeasonController {
constructor() {
if (!SeasonController.instance) {
SeasonController.instance = this;
@@ -33,16 +31,18 @@ class SeasonController {
async getSeaonById(req, res) {
try {
const season = await Season.findByPk(req.params.id, {
include: [{
model: Episode,
as: 'episodes'
}]
include: [
{
model: Episode,
as: "episodes",
},
],
});
if (season) {
res.send(season);
} else {
res.status(404).send('Season not found');
res.status(404).send("Season not found");
}
} catch (error) {
res.status(500).send(error.message);
@@ -53,19 +53,19 @@ class SeasonController {
try {
const episodes = await Episode.findAll({
where: {
season_id: req.params.id
season_id: req.params.id,
},
include: [{ model: EpisodeSeen }],
order: [
['episode_number', 'ASC'],
[EpisodeSeen, 'date_seen', 'ASC'],
["episode_number", "ASC"],
[EpisodeSeen, "date_seen", "ASC"],
],
});
if (episodes) {
res.send(episodes);
} else {
res.status(404).send('Episodes not found');
res.status(404).send("Episodes not found");
}
} catch (error) {
res.status(500).send(error.message);
@@ -75,13 +75,13 @@ class SeasonController {
async updateSeason(req, res) {
try {
const [updated] = await Season.update(req.body, {
where: { id: req.params.id }
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');
res.status(404).send("Season not found");
}
} catch (error) {
res.status(500).send(error.message);
@@ -91,18 +91,17 @@ class SeasonController {
async deleteSeason(req, res) {
try {
const deleted = await Season.destroy({
where: { id: req.params.id }
where: { id: req.params.id },
});
if (deleted) {
res.status(204).send('Season deleted');
res.status(204).send("Season deleted");
} else {
res.status(404).send('Season not found');
res.status(404).send("Season not found");
}
} catch (error) {
res.status(500).send(error.message);
}
}
}
module.exports = new SeasonController();
+2 -4
View File
@@ -1,9 +1,8 @@
const configService = require('../services/configService');
const configService = require("../services/configService");
const _configService = configService;
class SettingsController {
constructor() {
if (!SettingsController.instance) {
SettingsController.instance = this;
@@ -17,7 +16,7 @@ class SettingsController {
res.status(200).json(settings);
} catch (err) {
res.status(500).send('Error retrieving settings');
res.status(500).send("Error retrieving settings");
}
}
@@ -28,7 +27,6 @@ class SettingsController {
res.status(200).send(configService.getSettings());
}
}
module.exports = new SettingsController();
+45 -55
View File
@@ -1,12 +1,11 @@
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');
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;
@@ -16,27 +15,23 @@ class StatisticsController {
async getAllTimeWatchTime(req, res) {
const totalWatchTimeSeries = await EpisodeSeen.findOne({
include: [
{ model: Episode, as: 'episode', attributes: [] }
],
include: [{ model: Episode, as: "episode", attributes: [] }],
attributes: [
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
[sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"],
],
});
const totalWatchTimeMovies = await EntrySeen.findOne({
include: [
{ model: Entry, as: 'entry', attributes: [] }
],
include: [{ model: Entry, as: "entry", attributes: [] }],
attributes: [
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
[sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"],
],
});
const totalWatchTime = {
series: totalWatchTimeSeries.dataValues.watchTime,
movies: totalWatchTimeMovies.dataValues.watchTime
}
movies: totalWatchTimeMovies.dataValues.watchTime,
};
return res.status(200).json(totalWatchTime);
}
@@ -45,41 +40,37 @@ class StatisticsController {
const { year } = req.params;
const totalWatchTimeSeries = await EpisodeSeen.findAll({
include: [
{ model: Episode, as: 'episode', attributes: [] }
],
include: [{ model: Episode, as: "episode", attributes: [] }],
attributes: [
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
[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)]
}
[Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)],
},
},
group: [sequelize.fn('MONTH', sequelize.col('date_seen'))]
group: [sequelize.fn("MONTH", sequelize.col("date_seen"))],
});
const totalWatchTimeMovies = await EntrySeen.findAll({
include: [
{ model: Entry, as: 'entry', attributes: [] }
],
include: [{ model: Entry, as: "entry", attributes: [] }],
attributes: [
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
[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)]
}
[Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)],
},
},
group: [sequelize.fn('MONTH', sequelize.col('date_seen'))]
group: [sequelize.fn("MONTH", sequelize.col("date_seen"))],
});
const totalWatchTime = {
series: totalWatchTimeSeries,
movies: totalWatchTimeMovies
}
movies: totalWatchTimeMovies,
};
return res.status(200).json(totalWatchTime);
}
@@ -89,33 +80,33 @@ class StatisticsController {
const { year } = req.params;
const seriesCount = await EpisodeSeen.findAll({
attributes: [
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
[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)]
}
[Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)],
},
},
group: [sequelize.fn('MONTH', sequelize.col('date_seen'))]
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']
[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)]
}
[Op.between]: [new Date(year, 0, 1), new Date(year, 11, 31)],
},
},
group: [sequelize.fn('MONTH', sequelize.col('date_seen'))]
group: [sequelize.fn("MONTH", sequelize.col("date_seen"))],
});
res.status(200).json({ series: seriesCount, movies: moviesCount });
} catch (error) {
console.log(error)
console.log(error);
res.status(500).json({ error: error.message });
}
}
@@ -126,20 +117,20 @@ class StatisticsController {
// Only count records with EXACT accuracy
const episodeDays = await EpisodeSeen.findAll({
attributes: [
[sequelize.fn('DAYOFWEEK', sequelize.col('date_seen')), 'day'],
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
[sequelize.fn("DAYOFWEEK", sequelize.col("date_seen")), "day"],
[sequelize.fn("COUNT", sequelize.col("*")), "count"],
],
where: { accuracy: 'EXACT' },
group: [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen'))]
where: { accuracy: "EXACT" },
group: [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen"))],
});
const movieDays = await EntrySeen.findAll({
attributes: [
[sequelize.fn('DAYOFWEEK', sequelize.col('date_seen')), 'day'],
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
[sequelize.fn("DAYOFWEEK", sequelize.col("date_seen")), "day"],
[sequelize.fn("COUNT", sequelize.col("*")), "count"],
],
where: { accuracy: 'EXACT' },
group: [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen'))]
where: { accuracy: "EXACT" },
group: [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen"))],
});
res.status(200).json({ episodes: episodeDays, movies: movieDays });
@@ -148,7 +139,6 @@ class StatisticsController {
res.status(500).json({ error: error.message });
}
}
}
module.exports = new StatisticsController();