Normalize to double quotes across all files with Prettier
This commit is contained in:
1 parent
73bff72cec
commit
a5659cf4c8
189 files changed
+6212
-5548
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": false,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"tabWidth": 2,
|
||||||
|
"semi": true
|
||||||
|
}
|
||||||
@@ -5,14 +5,12 @@ const Entry = require("../models/Entry");
|
|||||||
const Genre = require("../models/Genre");
|
const Genre = require("../models/Genre");
|
||||||
const Media = require("../models/Media");
|
const Media = require("../models/Media");
|
||||||
|
|
||||||
|
|
||||||
async function initializeData() {
|
async function initializeData() {
|
||||||
initializeGenres();
|
initializeGenres();
|
||||||
//markEntriesRequireCreditsSync();
|
//markEntriesRequireCreditsSync();
|
||||||
// migrateAccuracyField();
|
// migrateAccuracyField();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// const collections = await Collection.findAll({
|
// const collections = await Collection.findAll({
|
||||||
// where: {
|
// where: {
|
||||||
// posterPath: { [Sequelize.Op.notLike]: '/%' }
|
// posterPath: { [Sequelize.Op.notLike]: '/%' }
|
||||||
@@ -36,14 +34,14 @@ async function initializeData() {
|
|||||||
async function markEntriesRequireCreditsSync() {
|
async function markEntriesRequireCreditsSync() {
|
||||||
try {
|
try {
|
||||||
const [affectedCount] = await Entry.update(
|
const [affectedCount] = await Entry.update(
|
||||||
{ entry_sync_status: 'RequireCreditsSync' },
|
{ entry_sync_status: "RequireCreditsSync" },
|
||||||
{ where: { entry_sync_status: null } }
|
{ where: { entry_sync_status: null } },
|
||||||
);
|
);
|
||||||
if (affectedCount > 0) {
|
if (affectedCount > 0) {
|
||||||
console.log(`Marked ${affectedCount} entries as RequireCreditsSync`);
|
console.log(`Marked ${affectedCount} entries as RequireCreditsSync`);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error marking entries for credits sync:', error);
|
console.error("Error marking entries for credits sync:", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,33 +49,33 @@ async function initializeGenres() {
|
|||||||
try {
|
try {
|
||||||
// * data to insert:
|
// * data to insert:
|
||||||
const initialGenres = [
|
const initialGenres = [
|
||||||
{ id: 10759, name: 'Action & Adventure' },
|
{ id: 10759, name: "Action & Adventure" },
|
||||||
{ id: 16, name: 'Animation' },
|
{ id: 16, name: "Animation" },
|
||||||
{ id: 35, name: 'Comedy' },
|
{ id: 35, name: "Comedy" },
|
||||||
{ id: 80, name: 'Crime' },
|
{ id: 80, name: "Crime" },
|
||||||
{ id: 99, name: 'Documentary' },
|
{ id: 99, name: "Documentary" },
|
||||||
{ id: 18, name: 'Drama' },
|
{ id: 18, name: "Drama" },
|
||||||
{ id: 10751, name: 'Family' },
|
{ id: 10751, name: "Family" },
|
||||||
{ id: 10762, name: 'Kids' },
|
{ id: 10762, name: "Kids" },
|
||||||
{ id: 9648, name: 'Mystery' },
|
{ id: 9648, name: "Mystery" },
|
||||||
{ id: 10763, name: 'News' },
|
{ id: 10763, name: "News" },
|
||||||
{ id: 10764, name: 'Reality' },
|
{ id: 10764, name: "Reality" },
|
||||||
{ id: 10765, name: 'Sci-Fi & Fantasy' },
|
{ id: 10765, name: "Sci-Fi & Fantasy" },
|
||||||
{ id: 10766, name: 'Soap' },
|
{ id: 10766, name: "Soap" },
|
||||||
{ id: 10767, name: 'Talk' },
|
{ id: 10767, name: "Talk" },
|
||||||
{ id: 10768, name: 'War & Politics' },
|
{ id: 10768, name: "War & Politics" },
|
||||||
{ id: 37, name: 'Western' },
|
{ id: 37, name: "Western" },
|
||||||
{ id: 28, name: 'Action' },
|
{ id: 28, name: "Action" },
|
||||||
{ id: 12, name: 'Adventure' },
|
{ id: 12, name: "Adventure" },
|
||||||
{ id: 14, name: 'Fantasy' },
|
{ id: 14, name: "Fantasy" },
|
||||||
{ id: 36, name: 'History' },
|
{ id: 36, name: "History" },
|
||||||
{ id: 27, name: 'Horror' },
|
{ id: 27, name: "Horror" },
|
||||||
{ id: 10402, name: 'Music' },
|
{ id: 10402, name: "Music" },
|
||||||
{ id: 10749, name: 'Romance' },
|
{ id: 10749, name: "Romance" },
|
||||||
{ id: 878, name: 'Science Fiction' },
|
{ id: 878, name: "Science Fiction" },
|
||||||
{ id: 10770, name: 'TV Movie' },
|
{ id: 10770, name: "TV Movie" },
|
||||||
{ id: 53, name: 'Thriller' },
|
{ id: 53, name: "Thriller" },
|
||||||
{ id: 10752, name: 'War' }
|
{ id: 10752, name: "War" },
|
||||||
];
|
];
|
||||||
|
|
||||||
// * Check if the data already exists
|
// * Check if the data already exists
|
||||||
@@ -85,7 +83,7 @@ async function initializeGenres() {
|
|||||||
|
|
||||||
// ? If data already exists, return
|
// ? If data already exists, return
|
||||||
if (existingGenres.length == initialGenres.length) {
|
if (existingGenres.length == initialGenres.length) {
|
||||||
console.log('Genres already initialized');
|
console.log("Genres already initialized");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,7 +92,7 @@ async function initializeGenres() {
|
|||||||
|
|
||||||
console.log(`${initialGenres.length} Genres initialized successfully`);
|
console.log(`${initialGenres.length} Genres initialized successfully`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error initializing data:', error);
|
console.error("Error initializing data:", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +100,7 @@ module.exports = {
|
|||||||
initializeData,
|
initializeData,
|
||||||
initializeGenres,
|
initializeGenres,
|
||||||
markEntriesRequireCreditsSync,
|
markEntriesRequireCreditsSync,
|
||||||
}
|
};
|
||||||
|
|
||||||
// async function migrateAccuracyField() {
|
// async function migrateAccuracyField() {
|
||||||
// try {
|
// try {
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
const { Sequelize } = require('sequelize');
|
const { Sequelize } = require("sequelize");
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
|
|
||||||
const logStream = fs.createWriteStream('sequelize.log', { flags: 'a' });
|
const logStream = fs.createWriteStream("sequelize.log", { flags: "a" });
|
||||||
|
|
||||||
const sequelize = new Sequelize('Showzy', 'root', 'password', {
|
const sequelize = new Sequelize("Showzy", "root", "password", {
|
||||||
host: 'localhost',
|
host: "localhost",
|
||||||
dialect: 'mysql',
|
dialect: "mysql",
|
||||||
logging: (msg) => {
|
logging: (msg) => {
|
||||||
logStream.write(msg + '\n');
|
logStream.write(msg + "\n");
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = sequelize;
|
module.exports = sequelize;
|
||||||
+131
-106
@@ -1,22 +1,21 @@
|
|||||||
// Import models
|
// Import models
|
||||||
const Franchise = require('../models/Franchise');
|
const Franchise = require("../models/Franchise");
|
||||||
const Entry = require('../models/Entry')
|
const Entry = require("../models/Entry");
|
||||||
const EntryId = require('../models/EntryId')
|
const EntryId = require("../models/EntryId");
|
||||||
const EntryRating = require('../models/EntryRating')
|
const EntryRating = require("../models/EntryRating");
|
||||||
const EntrySeen = require('../models/EntrySeen');
|
const EntrySeen = require("../models/EntrySeen");
|
||||||
const Collection = require('../models/Collection');
|
const Collection = require("../models/Collection");
|
||||||
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
const UserCollectionEntry = require("../models/UserCollectionEntry");
|
||||||
const Season = require('../models/Season');
|
const Season = require("../models/Season");
|
||||||
const Episode = require('../models/Episode');
|
const Episode = require("../models/Episode");
|
||||||
const EpisodeSeen = require('../models/EpisodeSeen');
|
const EpisodeSeen = require("../models/EpisodeSeen");
|
||||||
const Genre = require('../models/Genre');
|
const Genre = require("../models/Genre");
|
||||||
const EntryGenre = require('../models/EntryGenre');
|
const EntryGenre = require("../models/EntryGenre");
|
||||||
const Media = require('../models/Media');
|
const Media = require("../models/Media");
|
||||||
const Network = require('../models/Network');
|
const Network = require("../models/Network");
|
||||||
const EntryNetwork = require('../models/EntryNetwork');
|
const EntryNetwork = require("../models/EntryNetwork");
|
||||||
const People = require('../models/People');
|
const People = require("../models/People");
|
||||||
const Credit = require('../models/Credit');
|
const Credit = require("../models/Credit");
|
||||||
|
|
||||||
|
|
||||||
// ? one to one
|
// ? one to one
|
||||||
// A hasOne B = A > B
|
// A hasOne B = A > B
|
||||||
@@ -25,197 +24,223 @@ const Credit = require('../models/Credit');
|
|||||||
// A hasMany B = A > B
|
// A hasMany B = A > B
|
||||||
// A belongsTo B = A < B
|
// A belongsTo B = A < B
|
||||||
|
|
||||||
|
|
||||||
// * ENTRY & EntryId - ONE TO ONE
|
// * ENTRY & EntryId - ONE TO ONE
|
||||||
Entry.hasOne(EntryId, {
|
Entry.hasOne(EntryId, {
|
||||||
foreignKey: 'entry_id', as: 'entryId', onDelete: 'CASCADE',
|
foreignKey: "entry_id",
|
||||||
|
as: "entryId",
|
||||||
|
onDelete: "CASCADE",
|
||||||
});
|
});
|
||||||
EntryId.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
EntryId.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
|
|
||||||
// * ENTRY & EntryRating - ONE TO ONE
|
// * ENTRY & EntryRating - ONE TO ONE
|
||||||
Entry.hasOne(EntryRating, {
|
Entry.hasOne(EntryRating, {
|
||||||
foreignKey: 'entry_id', as: 'entryRating', onDelete: 'CASCADE',
|
foreignKey: "entry_id",
|
||||||
|
as: "entryRating",
|
||||||
|
onDelete: "CASCADE",
|
||||||
});
|
});
|
||||||
EntryRating.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
EntryRating.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
|
|
||||||
// * ENTRY & ENTRY_SEEN - ONE TO MANY
|
// * ENTRY & ENTRY_SEEN - ONE TO MANY
|
||||||
Entry.hasMany(EntrySeen, {
|
Entry.hasMany(EntrySeen, {
|
||||||
foreignKey: 'entry_id', as: 'entrySeen', onDelete: 'CASCADE',
|
foreignKey: "entry_id",
|
||||||
|
as: "entrySeen",
|
||||||
|
onDelete: "CASCADE",
|
||||||
});
|
});
|
||||||
EntrySeen.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
EntrySeen.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
|
|
||||||
// * ENTRY & LIST - MANY TO MANY
|
// * ENTRY & LIST - MANY TO MANY
|
||||||
Entry.belongsToMany(Collection, {
|
Entry.belongsToMany(Collection, {
|
||||||
through: UserCollectionEntry,
|
through: UserCollectionEntry,
|
||||||
foreignKey: 'entry_id',
|
foreignKey: "entry_id",
|
||||||
otherKey: 'user_collection_id',
|
otherKey: "user_collection_id",
|
||||||
onDelete: 'CASCADE',
|
onDelete: "CASCADE",
|
||||||
as: 'collections',
|
as: "collections",
|
||||||
});
|
});
|
||||||
|
|
||||||
Collection.belongsToMany(Entry, {
|
Collection.belongsToMany(Entry, {
|
||||||
through: UserCollectionEntry,
|
through: UserCollectionEntry,
|
||||||
foreignKey: 'user_collection_id',
|
foreignKey: "user_collection_id",
|
||||||
otherKey: 'entry_id',
|
otherKey: "entry_id",
|
||||||
onDelete: 'CASCADE',
|
onDelete: "CASCADE",
|
||||||
as: 'entries',
|
as: "entries",
|
||||||
});
|
});
|
||||||
|
|
||||||
Entry.hasMany(UserCollectionEntry, { foreignKey: 'entry_id', as: 'userCollectionEntries' });
|
Entry.hasMany(UserCollectionEntry, {
|
||||||
UserCollectionEntry.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
foreignKey: "entry_id",
|
||||||
Collection.hasMany(UserCollectionEntry, { foreignKey: 'user_collection_id', as: 'userCollectionEntries' });
|
as: "userCollectionEntries",
|
||||||
UserCollectionEntry.belongsTo(Collection, { foreignKey: 'user_collection_id', as: 'userCollection' });
|
});
|
||||||
|
UserCollectionEntry.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
|
Collection.hasMany(UserCollectionEntry, {
|
||||||
|
foreignKey: "user_collection_id",
|
||||||
|
as: "userCollectionEntries",
|
||||||
|
});
|
||||||
|
UserCollectionEntry.belongsTo(Collection, {
|
||||||
|
foreignKey: "user_collection_id",
|
||||||
|
as: "userCollection",
|
||||||
|
});
|
||||||
|
|
||||||
// * ENTRY & GENRE - MANY TO MANY
|
// * ENTRY & GENRE - MANY TO MANY
|
||||||
Entry.belongsToMany(Genre, {
|
Entry.belongsToMany(Genre, {
|
||||||
through: EntryGenre,
|
through: EntryGenre,
|
||||||
foreignKey: 'entry_id',
|
foreignKey: "entry_id",
|
||||||
otherKey: 'genre_id',
|
otherKey: "genre_id",
|
||||||
onDelete: 'CASCADE',
|
onDelete: "CASCADE",
|
||||||
as: 'genres',
|
as: "genres",
|
||||||
});
|
});
|
||||||
|
|
||||||
Genre.belongsToMany(Entry, {
|
Genre.belongsToMany(Entry, {
|
||||||
through: EntryGenre,
|
through: EntryGenre,
|
||||||
foreignKey: 'genre_id',
|
foreignKey: "genre_id",
|
||||||
otherKey: 'entry_id',
|
otherKey: "entry_id",
|
||||||
onDelete: 'CASCADE',
|
onDelete: "CASCADE",
|
||||||
as: 'entries',
|
as: "entries",
|
||||||
});
|
});
|
||||||
|
|
||||||
Entry.hasMany(EntryGenre, { foreignKey: 'entry_id', as: 'entryGenres' });
|
Entry.hasMany(EntryGenre, { foreignKey: "entry_id", as: "entryGenres" });
|
||||||
EntryGenre.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
EntryGenre.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
Genre.hasMany(EntryGenre, { foreignKey: 'genre_id', as: 'entryGenres' });
|
Genre.hasMany(EntryGenre, { foreignKey: "genre_id", as: "entryGenres" });
|
||||||
EntryGenre.belongsTo(Genre, { foreignKey: 'genre_id', as: 'genre' });
|
EntryGenre.belongsTo(Genre, { foreignKey: "genre_id", as: "genre" });
|
||||||
|
|
||||||
// * ENTRY & NETWORK - MANY TO MANY
|
// * ENTRY & NETWORK - MANY TO MANY
|
||||||
Entry.belongsToMany(Network, {
|
Entry.belongsToMany(Network, {
|
||||||
through: EntryNetwork,
|
through: EntryNetwork,
|
||||||
foreignKey: 'entry_id',
|
foreignKey: "entry_id",
|
||||||
otherKey: 'network_id',
|
otherKey: "network_id",
|
||||||
onDelete: 'CASCADE',
|
onDelete: "CASCADE",
|
||||||
as: 'networks',
|
as: "networks",
|
||||||
});
|
});
|
||||||
|
|
||||||
Network.belongsToMany(Entry, {
|
Network.belongsToMany(Entry, {
|
||||||
through: EntryNetwork,
|
through: EntryNetwork,
|
||||||
foreignKey: 'network_id',
|
foreignKey: "network_id",
|
||||||
otherKey: 'entry_id',
|
otherKey: "entry_id",
|
||||||
onDelete: 'CASCADE',
|
onDelete: "CASCADE",
|
||||||
as: 'entries',
|
as: "entries",
|
||||||
});
|
});
|
||||||
|
|
||||||
// ! MEDIA
|
// ! MEDIA
|
||||||
// * MEDIA & ENTRY - MANY TO ONE
|
// * MEDIA & ENTRY - MANY TO ONE
|
||||||
Media.belongsTo(Entry, {
|
Media.belongsTo(Entry, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
as: 'entry',
|
as: "entry",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'entry'
|
mediaable: "entry",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Entry.hasMany(Media, {
|
Entry.hasMany(Media, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
as: 'medias',
|
as: "medias",
|
||||||
scope: { mediaable: 'entry' }
|
scope: { mediaable: "entry" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// * MEDIA & People - MANY TO ONE
|
// * MEDIA & People - MANY TO ONE
|
||||||
Media.belongsTo(People, {
|
Media.belongsTo(People, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
as: 'people',
|
as: "people",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'people'
|
mediaable: "people",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
People.hasMany(Media, {
|
People.hasMany(Media, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
as: 'medias',
|
as: "medias",
|
||||||
scope: { mediaable: 'people' }
|
scope: { mediaable: "people" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// * MEDIA & Collection - MANY TO ONE
|
// * MEDIA & Collection - MANY TO ONE
|
||||||
Media.belongsTo(Collection, {
|
Media.belongsTo(Collection, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
as: 'collection',
|
as: "collection",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'collection'
|
mediaable: "collection",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Collection.hasMany(Media, {
|
Collection.hasMany(Media, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
as: 'medias',
|
as: "medias",
|
||||||
scope: { mediaable: 'collection' }
|
scope: { mediaable: "collection" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// * MEDIA & Season - MANY TO ONE
|
// * MEDIA & Season - MANY TO ONE
|
||||||
Media.belongsTo(Season, {
|
Media.belongsTo(Season, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
as: 'season',
|
as: "season",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'season'
|
mediaable: "season",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Season.hasMany(Media, {
|
Season.hasMany(Media, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
as: 'medias',
|
as: "medias",
|
||||||
scope: { mediaable: 'season' }
|
scope: { mediaable: "season" },
|
||||||
});
|
});
|
||||||
|
|
||||||
// * MEDIA & Episode - MANY TO ONE
|
// * MEDIA & Episode - MANY TO ONE
|
||||||
Media.belongsTo(Episode, {
|
Media.belongsTo(Episode, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
as: 'episode',
|
as: "episode",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'episode'
|
mediaable: "episode",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
Episode.hasMany(Media, {
|
Episode.hasMany(Media, {
|
||||||
foreignKey: 'mediaableId',
|
foreignKey: "mediaableId",
|
||||||
constraints: false,
|
constraints: false,
|
||||||
as: 'medias',
|
as: "medias",
|
||||||
scope: { mediaable: 'episode' }
|
scope: { mediaable: "episode" },
|
||||||
});
|
});
|
||||||
// ! MEDIA END
|
// ! MEDIA END
|
||||||
|
|
||||||
// * ENTRY & SEASON - ONE TO MANY
|
// * ENTRY & SEASON - ONE TO MANY
|
||||||
Entry.hasMany(Season, { foreignKey: 'entry_id', as: 'seasons', onDelete: 'CASCADE', });
|
Entry.hasMany(Season, {
|
||||||
Season.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
foreignKey: "entry_id",
|
||||||
|
as: "seasons",
|
||||||
|
onDelete: "CASCADE",
|
||||||
|
});
|
||||||
|
Season.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
|
|
||||||
// * SEASON & EPISODE - ONE TO MANY
|
// * SEASON & EPISODE - ONE TO MANY
|
||||||
Season.hasMany(Episode, { foreignKey: 'season_id', onDelete: 'CASCADE', });
|
Season.hasMany(Episode, { foreignKey: "season_id", onDelete: "CASCADE" });
|
||||||
Episode.belongsTo(Season, { foreignKey: 'season_id' });
|
Episode.belongsTo(Season, { foreignKey: "season_id" });
|
||||||
|
|
||||||
// * EPISODE & EPISODE_SEEN - ONE TO MANY
|
// * EPISODE & EPISODE_SEEN - ONE TO MANY
|
||||||
Episode.hasMany(EpisodeSeen, { foreignKey: 'episode_id', onDelete: 'CASCADE', });
|
Episode.hasMany(EpisodeSeen, { foreignKey: "episode_id", onDelete: "CASCADE" });
|
||||||
EpisodeSeen.belongsTo(Episode, { foreignKey: 'episode_id' });
|
EpisodeSeen.belongsTo(Episode, { foreignKey: "episode_id" });
|
||||||
|
|
||||||
// * ENTRY & EPISODE_SEEN - ONE TO MANY
|
// * ENTRY & EPISODE_SEEN - ONE TO MANY
|
||||||
Entry.hasMany(EpisodeSeen, { foreignKey: 'entry_id', onDelete: 'CASCADE', });
|
Entry.hasMany(EpisodeSeen, { foreignKey: "entry_id", onDelete: "CASCADE" });
|
||||||
EpisodeSeen.belongsTo(Entry, { foreignKey: 'entry_id' });
|
EpisodeSeen.belongsTo(Entry, { foreignKey: "entry_id" });
|
||||||
|
|
||||||
// * ----
|
// * ----
|
||||||
Franchise.hasMany(Entry, { foreignKey: 'franchise_id' });
|
Franchise.hasMany(Entry, { foreignKey: "franchise_id" });
|
||||||
Entry.belongsTo(Franchise, { foreignKey: 'franchise_id' });
|
Entry.belongsTo(Franchise, { foreignKey: "franchise_id" });
|
||||||
|
|
||||||
// * ENTRY & Credit - ONE TO MANY
|
// * ENTRY & Credit - ONE TO MANY
|
||||||
Entry.hasMany(Credit, { foreignKey: 'entry_id', as: 'credits', onDelete: 'CASCADE', });
|
Entry.hasMany(Credit, {
|
||||||
Credit.belongsTo(Entry, { foreignKey: 'entry_id', as: 'entry' });
|
foreignKey: "entry_id",
|
||||||
|
as: "credits",
|
||||||
|
onDelete: "CASCADE",
|
||||||
|
});
|
||||||
|
Credit.belongsTo(Entry, { foreignKey: "entry_id", as: "entry" });
|
||||||
|
|
||||||
// * PEOPLE & CAST - ONE TO MANY
|
// * PEOPLE & CAST - ONE TO MANY
|
||||||
People.hasMany(Credit, { foreignKey: 'people_id', as: 'roles', onDelete: 'CASCADE', });
|
People.hasMany(Credit, {
|
||||||
Credit.belongsTo(People, { foreignKey: 'people_id', as: 'person' });
|
foreignKey: "people_id",
|
||||||
|
as: "roles",
|
||||||
|
onDelete: "CASCADE",
|
||||||
|
});
|
||||||
|
Credit.belongsTo(People, { foreignKey: "people_id", as: "person" });
|
||||||
@@ -1,17 +1,17 @@
|
|||||||
// Import models
|
// Import models
|
||||||
const Franchise = require('../models/Franchise');
|
const Franchise = require("../models/Franchise");
|
||||||
const Entry = require('../models/Entry')
|
const Entry = require("../models/Entry");
|
||||||
const EntryId = require('../models/EntryId')
|
const EntryId = require("../models/EntryId");
|
||||||
const EntryRating = require('../models/EntryRating')
|
const EntryRating = require("../models/EntryRating");
|
||||||
const EntrySeen = require('../models/EntrySeen');
|
const EntrySeen = require("../models/EntrySeen");
|
||||||
const UserCollection = require('../models/Collection');
|
const UserCollection = require("../models/Collection");
|
||||||
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
const UserCollectionEntry = require("../models/UserCollectionEntry");
|
||||||
const Season = require('../models/Season');
|
const Season = require("../models/Season");
|
||||||
const Episode = require('../models/Episode');
|
const Episode = require("../models/Episode");
|
||||||
const EpisodeSeen = require('../models/EpisodeSeen');
|
const EpisodeSeen = require("../models/EpisodeSeen");
|
||||||
const Genre = require('../models/Genre');
|
const Genre = require("../models/Genre");
|
||||||
const EntryGenre = require('../models/EntryGenre');
|
const EntryGenre = require("../models/EntryGenre");
|
||||||
const sequelize = require('./database');
|
const sequelize = require("./database");
|
||||||
|
|
||||||
// ! Hooks
|
// ! Hooks
|
||||||
// ? user collections
|
// ? user collections
|
||||||
@@ -19,22 +19,27 @@ const sequelize = require('./database');
|
|||||||
UserCollectionEntry.afterCreate(async (instance, options) => {
|
UserCollectionEntry.afterCreate(async (instance, options) => {
|
||||||
try {
|
try {
|
||||||
// ? mimicking a change in UserCollection to trigger updatedAt property update for the UserCollection
|
// ? mimicking a change in UserCollection to trigger updatedAt property update for the UserCollection
|
||||||
const userCollections = await UserCollection.findByPk(instance.user_collection_id);
|
const userCollections = await UserCollection.findByPk(
|
||||||
|
instance.user_collection_id,
|
||||||
|
);
|
||||||
await userCollections.update({
|
await userCollections.update({
|
||||||
name: sequelize.literal('name')
|
name: sequelize.literal("name"),
|
||||||
});
|
});
|
||||||
const userCollectionEntriesCount = await UserCollectionEntry.count({
|
const userCollectionEntriesCount = await UserCollectionEntry.count({
|
||||||
where: {
|
where: {
|
||||||
user_collection_id: instance.user_collection_id
|
user_collection_id: instance.user_collection_id,
|
||||||
}
|
},
|
||||||
})
|
});
|
||||||
|
|
||||||
// ? updating newly create UserCollectionEntry order
|
// ? updating newly create UserCollectionEntry order
|
||||||
await instance.update({
|
await instance.update({
|
||||||
order: userCollectionEntriesCount
|
order: userCollectionEntriesCount,
|
||||||
})
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: UserCollectionEntry.afterCreate: `, error)
|
console.log(
|
||||||
|
`Sequelize Hook Error: UserCollectionEntry.afterCreate: `,
|
||||||
|
error,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -42,53 +47,64 @@ UserCollectionEntry.afterCreate(async (instance, options) => {
|
|||||||
UserCollectionEntry.afterUpdate(async (instance, options) => {
|
UserCollectionEntry.afterUpdate(async (instance, options) => {
|
||||||
try {
|
try {
|
||||||
// ? mimicking a change in UserCollection to trigger updatedAt property update for the UserCollection
|
// ? mimicking a change in UserCollection to trigger updatedAt property update for the UserCollection
|
||||||
const userCollections = await UserCollection.findByPk(instance.user_collection_id);
|
const userCollections = await UserCollection.findByPk(
|
||||||
|
instance.user_collection_id,
|
||||||
|
);
|
||||||
await userCollections.update({
|
await userCollections.update({
|
||||||
name: sequelize.literal('name')
|
name: sequelize.literal("name"),
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? updating other entries order
|
// ? updating other entries order
|
||||||
const collectionEntries = await UserCollectionEntry.findAll({
|
const collectionEntries = await UserCollectionEntry.findAll({
|
||||||
where: {
|
where: {
|
||||||
user_collection_id: instance.user_collection_id
|
user_collection_id: instance.user_collection_id,
|
||||||
},
|
},
|
||||||
order: [['order', 'ASC']]
|
order: [["order", "ASC"]],
|
||||||
})
|
});
|
||||||
|
|
||||||
// * changing the order of all entries that are now after the updated entry
|
// * changing the order of all entries that are now after the updated entry
|
||||||
let startOrder = instance.order + 1;
|
let startOrder = instance.order + 1;
|
||||||
for (let i = 0; i < collectionEntries.length; i++) {
|
for (let i = 0; i < collectionEntries.length; i++) {
|
||||||
if (collectionEntries[i].order >= instance.order && collectionEntries[i].entry_id != instance.entry_id) {
|
if (
|
||||||
await collectionEntries[i].update({ order: startOrder }, { hooks: false })
|
collectionEntries[i].order >= instance.order &&
|
||||||
|
collectionEntries[i].entry_id != instance.entry_id
|
||||||
|
) {
|
||||||
|
await collectionEntries[i].update(
|
||||||
|
{ order: startOrder },
|
||||||
|
{ hooks: false },
|
||||||
|
);
|
||||||
startOrder++;
|
startOrder++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: UserCollectionEntry.afterUpdate: `, error)
|
console.log(
|
||||||
|
`Sequelize Hook Error: UserCollectionEntry.afterUpdate: `,
|
||||||
|
error,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// * entry remove
|
// * entry remove
|
||||||
UserCollectionEntry.afterDestroy(async (instance, options) => {
|
UserCollectionEntry.afterDestroy(async (instance, options) => {
|
||||||
try {
|
try {
|
||||||
const userCollection = await UserCollection.findByPk(instance.user_collection_id);
|
const userCollection = await UserCollection.findByPk(
|
||||||
|
instance.user_collection_id,
|
||||||
|
);
|
||||||
const entry = await Entry.findByPk(instance.entry_id);
|
const entry = await Entry.findByPk(instance.entry_id);
|
||||||
|
|
||||||
if (!entry || !userCollection) return;
|
if (!entry || !userCollection) return;
|
||||||
|
|
||||||
// ? mimicking a change to trigger updatedAt property update
|
// ? mimicking a change to trigger updatedAt property update
|
||||||
let updates = {
|
let updates = {
|
||||||
name: sequelize.literal('name')
|
name: sequelize.literal("name"),
|
||||||
}
|
};
|
||||||
|
|
||||||
const collectionsEntries = await UserCollectionEntry.findAll({
|
const collectionsEntries = await UserCollectionEntry.findAll({
|
||||||
where: {
|
where: {
|
||||||
user_collection_id: instance.user_collection_id
|
user_collection_id: instance.user_collection_id,
|
||||||
},
|
},
|
||||||
include: [
|
include: [{ model: Entry, as: "entry" }],
|
||||||
{ model: Entry, as: 'entry' },
|
});
|
||||||
]
|
|
||||||
})
|
|
||||||
|
|
||||||
// ? updating collection poster
|
// ? updating collection poster
|
||||||
// ? remove the poster if the collection is empty now
|
// ? remove the poster if the collection is empty now
|
||||||
@@ -106,16 +122,19 @@ UserCollectionEntry.afterDestroy(async (instance, options) => {
|
|||||||
if (instance.order != collectionsEntries.length) {
|
if (instance.order != collectionsEntries.length) {
|
||||||
for (let i = 0; i < collectionsEntries.length; i++) {
|
for (let i = 0; i < collectionsEntries.length; i++) {
|
||||||
if (collectionsEntries[i].order > instance.order) {
|
if (collectionsEntries[i].order > instance.order) {
|
||||||
collectionsEntries[i].update({ order: order }, { hooks: false })
|
collectionsEntries[i].update({ order: order }, { hooks: false });
|
||||||
order++;
|
order++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? updating the collection updatedAt and poster maybe
|
// ? updating the collection updatedAt and poster maybe
|
||||||
await userCollection.update(updates)
|
await userCollection.update(updates);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: UserCollectionEntry.afterDestroy: `, error)
|
console.log(
|
||||||
|
`Sequelize Hook Error: UserCollectionEntry.afterDestroy: `,
|
||||||
|
error,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -128,22 +147,28 @@ EntrySeen.afterCreate(async (instance, options) => {
|
|||||||
|
|
||||||
// this will ensure that the entry is updated anyways to trigger the updatedAt property
|
// this will ensure that the entry is updated anyways to trigger the updatedAt property
|
||||||
let update = {
|
let update = {
|
||||||
watchlist: false
|
watchlist: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ? comparing the instance.date_seen with the entry date_first_seen &
|
// ? comparing the instance.date_seen with the entry date_first_seen &
|
||||||
// ? date_last_seen to check if they should be replaced
|
// ? date_last_seen to check if they should be replaced
|
||||||
if (!entry.date_first_seen || instance.date_seen < new Date(entry.date_first_seen)) {
|
if (
|
||||||
|
!entry.date_first_seen ||
|
||||||
|
instance.date_seen < new Date(entry.date_first_seen)
|
||||||
|
) {
|
||||||
update.date_first_seen = instance.date_seen;
|
update.date_first_seen = instance.date_seen;
|
||||||
}
|
}
|
||||||
if (!entry.date_last_seen || instance.date_seen > new Date(entry.date_last_seen)) {
|
if (
|
||||||
|
!entry.date_last_seen ||
|
||||||
|
instance.date_seen > new Date(entry.date_last_seen)
|
||||||
|
) {
|
||||||
update.date_last_seen = instance.date_seen;
|
update.date_last_seen = instance.date_seen;
|
||||||
}
|
}
|
||||||
|
|
||||||
// * updating the entry
|
// * updating the entry
|
||||||
await entry.update(update);
|
await entry.update(update);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: EntrySeen.afterCreate: `, error)
|
console.log(`Sequelize Hook Error: EntrySeen.afterCreate: `, error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -158,11 +183,9 @@ EntrySeen.afterUpdate(async (instance, options) => {
|
|||||||
// ? and the last one to: date_last_seen
|
// ? and the last one to: date_last_seen
|
||||||
const entrySeens = await EntrySeen.findAll({
|
const entrySeens = await EntrySeen.findAll({
|
||||||
where: {
|
where: {
|
||||||
entry_id: instance.entry_id
|
entry_id: instance.entry_id,
|
||||||
},
|
},
|
||||||
order: [
|
order: [["date_seen", "ASC"]],
|
||||||
['date_seen', 'ASC']
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let update = {};
|
let update = {};
|
||||||
@@ -172,7 +195,7 @@ EntrySeen.afterUpdate(async (instance, options) => {
|
|||||||
// * updating the entry
|
// * updating the entry
|
||||||
await entry.update(update);
|
await entry.update(update);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error)
|
console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -187,11 +210,9 @@ EntrySeen.afterDestroy(async (instance, options) => {
|
|||||||
// ? and the last one to: date_last_seen
|
// ? and the last one to: date_last_seen
|
||||||
const entrySeens = await EntrySeen.findAll({
|
const entrySeens = await EntrySeen.findAll({
|
||||||
where: {
|
where: {
|
||||||
entry_id: instance.entry_id
|
entry_id: instance.entry_id,
|
||||||
},
|
},
|
||||||
order: [
|
order: [["date_seen", "ASC"]],
|
||||||
['date_seen', 'ASC']
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let update = {};
|
let update = {};
|
||||||
@@ -209,7 +230,7 @@ EntrySeen.afterDestroy(async (instance, options) => {
|
|||||||
// * updating the entry
|
// * updating the entry
|
||||||
await entry.update(update);
|
await entry.update(update);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error)
|
console.log(`Sequelize Hook Error: EntrySeen.afterUpdate: `, error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -224,15 +245,21 @@ EpisodeSeen.afterCreate(async (instance, options) => {
|
|||||||
// this will ensure that the entry is updated anyways to trigger the updatedAt property
|
// this will ensure that the entry is updated anyways to trigger the updatedAt property
|
||||||
let update = {
|
let update = {
|
||||||
// title: sequelize.literal('title')
|
// title: sequelize.literal('title')
|
||||||
watchlist: false
|
watchlist: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
// ? comparing the instance.date_seen with the entry date_first_seen &
|
// ? comparing the instance.date_seen with the entry date_first_seen &
|
||||||
// ? date_last_seen to check if they should be replaced
|
// ? date_last_seen to check if they should be replaced
|
||||||
if (!entry.date_first_seen || instance.date_seen < new Date(entry.date_first_seen)) {
|
if (
|
||||||
|
!entry.date_first_seen ||
|
||||||
|
instance.date_seen < new Date(entry.date_first_seen)
|
||||||
|
) {
|
||||||
update.date_first_seen = instance.date_seen;
|
update.date_first_seen = instance.date_seen;
|
||||||
}
|
}
|
||||||
if (!entry.date_last_seen || instance.date_seen > new Date(entry.date_last_seen)) {
|
if (
|
||||||
|
!entry.date_last_seen ||
|
||||||
|
instance.date_seen > new Date(entry.date_last_seen)
|
||||||
|
) {
|
||||||
update.date_last_seen = instance.date_seen;
|
update.date_last_seen = instance.date_seen;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,22 +272,28 @@ EpisodeSeen.afterCreate(async (instance, options) => {
|
|||||||
|
|
||||||
// this will ensure that the episode is updated anyways to trigger the updatedAt property
|
// this will ensure that the episode is updated anyways to trigger the updatedAt property
|
||||||
let episodeUpdate = {
|
let episodeUpdate = {
|
||||||
name: sequelize.literal('name')
|
name: sequelize.literal("name"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// ? comparing the instance.date_seen with the entry date_first_seen &
|
// ? comparing the instance.date_seen with the entry date_first_seen &
|
||||||
// ? date_last_seen to check if they should be replaced
|
// ? date_last_seen to check if they should be replaced
|
||||||
if (!episode.date_first_seen || instance.date_seen < new Date(episode.date_first_seen)) {
|
if (
|
||||||
|
!episode.date_first_seen ||
|
||||||
|
instance.date_seen < new Date(episode.date_first_seen)
|
||||||
|
) {
|
||||||
episodeUpdate.date_first_seen = instance.date_seen;
|
episodeUpdate.date_first_seen = instance.date_seen;
|
||||||
}
|
}
|
||||||
if (!episode.date_last_seen || instance.date_seen > new Date(episode.date_last_seen)) {
|
if (
|
||||||
|
!episode.date_last_seen ||
|
||||||
|
instance.date_seen > new Date(episode.date_last_seen)
|
||||||
|
) {
|
||||||
episodeUpdate.date_last_seen = instance.date_seen;
|
episodeUpdate.date_last_seen = instance.date_seen;
|
||||||
}
|
}
|
||||||
|
|
||||||
// * updating the episode
|
// * updating the episode
|
||||||
await episode.update(episodeUpdate);
|
await episode.update(episodeUpdate);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: EpisodeSeen.afterCreate: `, error)
|
console.log(`Sequelize Hook Error: EpisodeSeen.afterCreate: `, error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -275,21 +308,23 @@ EpisodeSeen.afterUpdate(async (instance, options) => {
|
|||||||
// ? for the current entry
|
// ? for the current entry
|
||||||
EpisodeSeen.findAll({
|
EpisodeSeen.findAll({
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('min', sequelize.col('date_seen')), 'minValue'],
|
[sequelize.fn("min", sequelize.col("date_seen")), "minValue"],
|
||||||
[sequelize.fn('max', sequelize.col('date_seen')), 'maxValue']
|
[sequelize.fn("max", sequelize.col("date_seen")), "maxValue"],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
entry_id: instance.entry_id
|
entry_id: instance.entry_id,
|
||||||
}
|
},
|
||||||
}).then(result => {
|
})
|
||||||
|
.then((result) => {
|
||||||
let update = {};
|
let update = {};
|
||||||
|
|
||||||
update.date_first_seen = result[0].dataValues.minValue;
|
update.date_first_seen = result[0].dataValues.minValue;
|
||||||
update.date_last_seen = result[0].dataValues.maxValue;
|
update.date_last_seen = result[0].dataValues.maxValue;
|
||||||
|
|
||||||
entry.update(update);
|
entry.update(update);
|
||||||
}).catch(err => {
|
})
|
||||||
console.error('Error:', err);
|
.catch((err) => {
|
||||||
|
console.error("Error:", err);
|
||||||
});
|
});
|
||||||
|
|
||||||
// ! updating the episode
|
// ! updating the episode
|
||||||
@@ -300,22 +335,24 @@ EpisodeSeen.afterUpdate(async (instance, options) => {
|
|||||||
// ? for the current episode
|
// ? for the current episode
|
||||||
EpisodeSeen.findAll({
|
EpisodeSeen.findAll({
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('min', sequelize.col('date_seen')), 'minValue'],
|
[sequelize.fn("min", sequelize.col("date_seen")), "minValue"],
|
||||||
[sequelize.fn('max', sequelize.col('date_seen')), 'maxValue']
|
[sequelize.fn("max", sequelize.col("date_seen")), "maxValue"],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
episode_id: instance.episode_id
|
episode_id: instance.episode_id,
|
||||||
}
|
},
|
||||||
}).then(result => {
|
})
|
||||||
|
.then((result) => {
|
||||||
let update = {};
|
let update = {};
|
||||||
update.date_first_seen = result[0].dataValues.minValue;
|
update.date_first_seen = result[0].dataValues.minValue;
|
||||||
update.date_last_seen = result[0].dataValues.maxValue;
|
update.date_last_seen = result[0].dataValues.maxValue;
|
||||||
episode.update(update);
|
episode.update(update);
|
||||||
}).catch(err => {
|
})
|
||||||
console.error('Error:', err);
|
.catch((err) => {
|
||||||
|
console.error("Error:", err);
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error)
|
console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -331,11 +368,9 @@ EpisodeSeen.afterDestroy(async (instance, options) => {
|
|||||||
// ? and the last one to: date_last_seen
|
// ? and the last one to: date_last_seen
|
||||||
const episodeSeens = await EpisodeSeen.findAll({
|
const episodeSeens = await EpisodeSeen.findAll({
|
||||||
where: {
|
where: {
|
||||||
entry_id: instance.entry_id
|
entry_id: instance.entry_id,
|
||||||
},
|
},
|
||||||
order: [
|
order: [["date_seen", "ASC"]],
|
||||||
['date_seen', 'ASC']
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let update = {};
|
let update = {};
|
||||||
@@ -362,11 +397,9 @@ EpisodeSeen.afterDestroy(async (instance, options) => {
|
|||||||
// ? and the last one to: date_last_seen
|
// ? and the last one to: date_last_seen
|
||||||
const episodeSeens2 = await EpisodeSeen.findAll({
|
const episodeSeens2 = await EpisodeSeen.findAll({
|
||||||
where: {
|
where: {
|
||||||
episode_id: instance.episode_id
|
episode_id: instance.episode_id,
|
||||||
},
|
},
|
||||||
order: [
|
order: [["date_seen", "ASC"]],
|
||||||
['date_seen', 'ASC']
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let episodeUpdate = {};
|
let episodeUpdate = {};
|
||||||
@@ -378,12 +411,13 @@ EpisodeSeen.afterDestroy(async (instance, options) => {
|
|||||||
episodeUpdate.date_last_seen = null;
|
episodeUpdate.date_last_seen = null;
|
||||||
} else {
|
} else {
|
||||||
episodeUpdate.date_first_seen = episodeSeens2[0].date_seen;
|
episodeUpdate.date_first_seen = episodeSeens2[0].date_seen;
|
||||||
episodeUpdate.date_last_seen = episodeSeens2[episodeSeens2.length - 1].date_seen;
|
episodeUpdate.date_last_seen =
|
||||||
|
episodeSeens2[episodeSeens2.length - 1].date_seen;
|
||||||
}
|
}
|
||||||
|
|
||||||
// * updating the episode
|
// * updating the episode
|
||||||
await episode.update(episodeUpdate);
|
await episode.update(episodeUpdate);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error)
|
console.log(`Sequelize Hook Error: EpisodeSeen.afterUpdate: `, error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,24 +1,23 @@
|
|||||||
const { Sequelize } = require('sequelize');
|
const { Sequelize } = require("sequelize");
|
||||||
const Collection = require('../models/Collection');
|
const Collection = require("../models/Collection");
|
||||||
const UserCollectionEntry = require('../models/UserCollectionEntry');
|
const UserCollectionEntry = require("../models/UserCollectionEntry");
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require("../models/Entry");
|
||||||
const EntryId = require('../models/EntryId');
|
const EntryId = require("../models/EntryId");
|
||||||
const EntryRating = require('../models/EntryRating');
|
const EntryRating = require("../models/EntryRating");
|
||||||
const Season = require('../models/Season');
|
const Season = require("../models/Season");
|
||||||
const Genre = require('../models/Genre');
|
const Genre = require("../models/Genre");
|
||||||
const Media = require('../models/Media');
|
const Media = require("../models/Media");
|
||||||
|
|
||||||
const { logToFile } = require('../services/logService');
|
const { logToFile } = require("../services/logService");
|
||||||
const collectionManager = require('../services/collectionManager');
|
const collectionManager = require("../services/collectionManager");
|
||||||
const mediaOptimizerService = require('../services/mediaOptimizerService');
|
const mediaOptimizerService = require("../services/mediaOptimizerService");
|
||||||
const collectionService = require('../services/collectionService');
|
const collectionService = require("../services/collectionService");
|
||||||
|
|
||||||
const _mediaOptimizerService = mediaOptimizerService;
|
const _mediaOptimizerService = mediaOptimizerService;
|
||||||
const _collectionManager = collectionManager;
|
const _collectionManager = collectionManager;
|
||||||
const _collectionService = collectionService;
|
const _collectionService = collectionService;
|
||||||
|
|
||||||
class CollectionController {
|
class CollectionController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!CollectionController.instance) {
|
if (!CollectionController.instance) {
|
||||||
CollectionController.instance = this;
|
CollectionController.instance = this;
|
||||||
@@ -41,37 +40,41 @@ class CollectionController {
|
|||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: 'entries',
|
as: "entries",
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
{ model: EntryRating, as: "entryRating" },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: "seasons" },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: "medias" },
|
||||||
{ model: Genre, as: 'genres' },
|
{ model: Genre, as: "genres" },
|
||||||
],
|
],
|
||||||
through: {
|
through: {
|
||||||
model: UserCollectionEntry,
|
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) {
|
if (collection) {
|
||||||
const collectionData = collection.get({ plain: true });
|
const collectionData = collection.get({ plain: true });
|
||||||
for (let i = 0; i < collectionData.entries.length; i++) {
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
||||||
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
const genres = collectionData.entries[i].genres.map(
|
||||||
collectionData.entries[i].genres = genres
|
(genre) => genre.name,
|
||||||
|
);
|
||||||
|
collectionData.entries[i].genres = genres;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json(collectionData);
|
res.status(200).json(collectionData);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'UserCollection not found' });
|
res.status(404).json({ message: "UserCollection not found" });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Error getting collection info: `, error)
|
console.log(`Error getting collection info: `, error);
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,7 +84,13 @@ class CollectionController {
|
|||||||
try {
|
try {
|
||||||
const { name, description, userRating, posterPath } = req.body;
|
const { name, description, userRating, posterPath } = req.body;
|
||||||
const isUserCollection = true;
|
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);
|
res.status(201).json(newUserCollection);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
@@ -95,7 +104,9 @@ class CollectionController {
|
|||||||
const { name, description, userRating } = req.body;
|
const { name, description, userRating } = req.body;
|
||||||
|
|
||||||
const posterFile = req.files.poster ? req.files.poster[0] : undefined;
|
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 posterPath = posterFile ? posterFile.filename : undefined;
|
||||||
let backdropPath = backdropFile ? backdropFile.filename : undefined;
|
let backdropPath = backdropFile ? backdropFile.filename : undefined;
|
||||||
@@ -109,10 +120,13 @@ class CollectionController {
|
|||||||
|
|
||||||
if (posterPath) {
|
if (posterPath) {
|
||||||
// ? generating preview
|
// ? generating preview
|
||||||
_mediaOptimizerService.doGeneratePreview("collections", 'posters', posterPath).then((result) => {
|
_mediaOptimizerService
|
||||||
|
.doGeneratePreview("collections", "posters", posterPath)
|
||||||
|
.then((result) => {
|
||||||
const msg = `Collection Service | Generated Collection Preview`;
|
const msg = `Collection Service | Generated Collection Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
}).catch((err) => {
|
})
|
||||||
|
.catch((err) => {
|
||||||
const msg = `Collection Service | Error Generating Collection Preview`;
|
const msg = `Collection Service | Error Generating Collection Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
logToFile(err);
|
logToFile(err);
|
||||||
@@ -121,26 +135,36 @@ class CollectionController {
|
|||||||
// Deselect existing posters for this collection
|
// Deselect existing posters for this collection
|
||||||
await Media.update(
|
await Media.update(
|
||||||
{ isSelected: false },
|
{ isSelected: false },
|
||||||
{ where: { mediaable: 'collection', mediaableId: collectionId, type: 'poster', isSelected: true } }
|
{
|
||||||
|
where: {
|
||||||
|
mediaable: "collection",
|
||||||
|
mediaableId: collectionId,
|
||||||
|
type: "poster",
|
||||||
|
isSelected: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'collection',
|
mediaable: "collection",
|
||||||
mediaableId: collectionId,
|
mediaableId: collectionId,
|
||||||
type: 'poster',
|
type: "poster",
|
||||||
path: posterPath,
|
path: posterPath,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true,
|
isSelected: true,
|
||||||
isCustom: true
|
isCustom: true,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (backdropPath) {
|
if (backdropPath) {
|
||||||
// ? generating preview
|
// ? generating preview
|
||||||
_mediaOptimizerService.doGeneratePreview("collections", 'backdrops', backdropPath).then((result) => {
|
_mediaOptimizerService
|
||||||
|
.doGeneratePreview("collections", "backdrops", backdropPath)
|
||||||
|
.then((result) => {
|
||||||
const msg = `Collection Routes | Generated Collection Preview`;
|
const msg = `Collection Routes | Generated Collection Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
}).catch((err) => {
|
})
|
||||||
|
.catch((err) => {
|
||||||
const msg = `Collection Routes | Error Generating Collection Preview`;
|
const msg = `Collection Routes | Error Generating Collection Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
logToFile(err);
|
logToFile(err);
|
||||||
@@ -149,50 +173,60 @@ class CollectionController {
|
|||||||
// Deselect existing backdrops for this collection
|
// Deselect existing backdrops for this collection
|
||||||
await Media.update(
|
await Media.update(
|
||||||
{ isSelected: false },
|
{ isSelected: false },
|
||||||
{ where: { mediaable: 'collection', mediaableId: collectionId, type: 'backdrop', isSelected: true } }
|
{
|
||||||
|
where: {
|
||||||
|
mediaable: "collection",
|
||||||
|
mediaableId: collectionId,
|
||||||
|
type: "backdrop",
|
||||||
|
isSelected: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// ? inserting data
|
// ? inserting data
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'collection',
|
mediaable: "collection",
|
||||||
mediaableId: collectionId,
|
mediaableId: collectionId,
|
||||||
type: 'backdrop',
|
type: "backdrop",
|
||||||
path: backdropPath,
|
path: backdropPath,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true,
|
isSelected: true,
|
||||||
isCustom: true
|
isCustom: true,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const oldCollection = await Collection.findByPk(collectionId, {
|
const oldCollection = await Collection.findByPk(collectionId, {
|
||||||
include: [{
|
|
||||||
model: Entry,
|
|
||||||
as: 'entries',
|
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
model: Entry,
|
||||||
{ model: Season, as: 'seasons' },
|
as: "entries",
|
||||||
{ model: Media, as: 'medias' },
|
include: [
|
||||||
{ 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: {
|
through: {
|
||||||
model: UserCollectionEntry,
|
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 (!oldCollection)
|
if (!oldCollection)
|
||||||
res.status(404).json({ message: 'Collection not found' });
|
res.status(404).json({ message: "Collection not found" });
|
||||||
|
|
||||||
await oldCollection.update(updateData);
|
await oldCollection.update(updateData);
|
||||||
|
|
||||||
res.status(200).json(oldCollection);
|
res.status(200).json(oldCollection);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`UserCollection update (put) error: `, error)
|
console.log(`UserCollection update (put) error: `, error);
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -202,21 +236,25 @@ class CollectionController {
|
|||||||
const collectionId = req.params.id;
|
const collectionId = req.params.id;
|
||||||
const oldCollection = await Collection.findByPk(collectionId);
|
const oldCollection = await Collection.findByPk(collectionId);
|
||||||
|
|
||||||
const collection = await _collectionManager.fetchAndSaveCollection(oldCollection.tmdbId);
|
const collection = await _collectionManager.fetchAndSaveCollection(
|
||||||
|
oldCollection.tmdbId,
|
||||||
|
);
|
||||||
|
|
||||||
if (collection) {
|
if (collection) {
|
||||||
const collectionData = collection.get({ plain: true });
|
const collectionData = collection.get({ plain: true });
|
||||||
for (let i = 0; i < collectionData.entries.length; i++) {
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
||||||
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
const genres = collectionData.entries[i].genres.map(
|
||||||
collectionData.entries[i].genres = genres
|
(genre) => genre.name,
|
||||||
|
);
|
||||||
|
collectionData.entries[i].genres = genres;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json(collectionData);
|
res.status(200).json(collectionData);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'Collection not found' });
|
res.status(404).json({ message: "Collection not found" });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`UserCollection update (put) error: `, error)
|
console.log(`UserCollection update (put) error: `, error);
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,37 +269,41 @@ class CollectionController {
|
|||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: 'entries',
|
as: "entries",
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
{ model: EntryRating, as: "entryRating" },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: "seasons" },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: "medias" },
|
||||||
{ model: Genre, as: 'genres' },
|
{ model: Genre, as: "genres" },
|
||||||
],
|
],
|
||||||
through: {
|
through: {
|
||||||
model: UserCollectionEntry,
|
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) {
|
if (collection) {
|
||||||
const collectionData = collection.get({ plain: true });
|
const collectionData = collection.get({ plain: true });
|
||||||
for (let i = 0; i < collectionData.entries.length; i++) {
|
for (let i = 0; i < collectionData.entries.length; i++) {
|
||||||
const genres = collectionData.entries[i].genres.map(genre => genre.name);
|
const genres = collectionData.entries[i].genres.map(
|
||||||
collectionData.entries[i].genres = genres
|
(genre) => genre.name,
|
||||||
|
);
|
||||||
|
collectionData.entries[i].genres = genres;
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json(collectionData);
|
res.status(200).json(collectionData);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'Collection not found' });
|
res.status(404).json({ message: "Collection not found" });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`UserCollection update (put) error: `, error)
|
console.log(`UserCollection update (put) error: `, error);
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -269,11 +311,13 @@ class CollectionController {
|
|||||||
// todo: move to collection service
|
// todo: move to collection service
|
||||||
async deleteCollection(req, res) {
|
async deleteCollection(req, res) {
|
||||||
try {
|
try {
|
||||||
const deleted = await Collection.destroy({ where: { id: req.params.id } });
|
const deleted = await Collection.destroy({
|
||||||
|
where: { id: req.params.id },
|
||||||
|
});
|
||||||
if (deleted) {
|
if (deleted) {
|
||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'UserCollection not found' });
|
res.status(404).json({ message: "UserCollection not found" });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
@@ -287,12 +331,15 @@ class CollectionController {
|
|||||||
|
|
||||||
const newUserCollectionEntry = await UserCollectionEntry.create({
|
const newUserCollectionEntry = await UserCollectionEntry.create({
|
||||||
user_collection_id: collectionId,
|
user_collection_id: collectionId,
|
||||||
entry_id: entryId
|
entry_id: entryId,
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? set a default poster if none exists
|
// ? set a default poster if none exists
|
||||||
const userCollection = await Collection.findByPk(collectionId);
|
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);
|
const entry = await Entry.findByPk(entryId);
|
||||||
userCollection.poster_path = entry.poster_path;
|
userCollection.poster_path = entry.poster_path;
|
||||||
await userCollection.save();
|
await userCollection.save();
|
||||||
@@ -300,7 +347,7 @@ class CollectionController {
|
|||||||
|
|
||||||
res.status(201).json(newUserCollectionEntry);
|
res.status(201).json(newUserCollectionEntry);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error)
|
console.log(error);
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -315,18 +362,20 @@ class CollectionController {
|
|||||||
const collectionEntry = await UserCollectionEntry.findOne({
|
const collectionEntry = await UserCollectionEntry.findOne({
|
||||||
where: {
|
where: {
|
||||||
user_collection_id: collectionId,
|
user_collection_id: collectionId,
|
||||||
entry_id: entryId
|
entry_id: entryId,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!collectionEntry) {
|
if (!collectionEntry) {
|
||||||
res.status(404).json({ message: 'UserCollectionEntry not found.' });
|
res.status(404).json({ message: "UserCollectionEntry not found." });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? updating
|
// ? updating
|
||||||
await collectionEntry.update({ order: newOrder });
|
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) {
|
} catch (error) {
|
||||||
console.log(`Error Updating UserCollectionEntry order: `, error);
|
console.log(`Error Updating UserCollectionEntry order: `, error);
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
@@ -340,15 +389,15 @@ class CollectionController {
|
|||||||
const deleted = await UserCollectionEntry.findOne({
|
const deleted = await UserCollectionEntry.findOne({
|
||||||
where: {
|
where: {
|
||||||
user_collection_id: collectionId,
|
user_collection_id: collectionId,
|
||||||
entry_id: entryId
|
entry_id: entryId,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (deleted) {
|
if (deleted) {
|
||||||
await deleted.destroy();
|
await deleted.destroy();
|
||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'CollectionEntry not found.' });
|
res.status(404).json({ message: "CollectionEntry not found." });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
@@ -362,14 +411,19 @@ class CollectionController {
|
|||||||
try {
|
try {
|
||||||
const result = await sequelize.transaction(async (t) => {
|
const result = await sequelize.transaction(async (t) => {
|
||||||
// Step 1: Create the userCollection
|
// 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
|
// Step 2: Add an entry to the newly created userCollection
|
||||||
const newUserCollectionEntry = await UserCollectionEntry.create({
|
const newUserCollectionEntry = await UserCollectionEntry.create(
|
||||||
|
{
|
||||||
userCollectionId: newUserCollection.id,
|
userCollectionId: newUserCollection.id,
|
||||||
entryId: entryId,
|
entryId: entryId,
|
||||||
entryOrder: entryOrder
|
entryOrder: entryOrder,
|
||||||
}, { transaction: t });
|
},
|
||||||
|
{ transaction: t },
|
||||||
|
);
|
||||||
|
|
||||||
return { newUserCollection, newUserCollectionEntry };
|
return { newUserCollection, newUserCollectionEntry };
|
||||||
});
|
});
|
||||||
@@ -377,11 +431,15 @@ class CollectionController {
|
|||||||
// If the transaction is successful, send back the created userCollection and entry relationship
|
// If the transaction is successful, send back the created userCollection and entry relationship
|
||||||
res.status(201).json(result);
|
res.status(201).json(result);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to create userCollection and add entry:', 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 });
|
res
|
||||||
|
.status(500)
|
||||||
|
.json({
|
||||||
|
message: "Failed to create userCollection and add entry",
|
||||||
|
error: error.message,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new CollectionController();
|
module.exports = new CollectionController();
|
||||||
@@ -1,16 +1,15 @@
|
|||||||
const EntryRating = require('../models/EntryRating');
|
const EntryRating = require("../models/EntryRating");
|
||||||
const collectionManager = require('../services/collectionManager');
|
const collectionManager = require("../services/collectionManager");
|
||||||
const entryManager = require('../services/entryManager');
|
const entryManager = require("../services/entryManager");
|
||||||
const entryService = require("../services/entryService");
|
const entryService = require("../services/entryService");
|
||||||
const tmdbService = require('../services/tmdbService');
|
const tmdbService = require("../services/tmdbService");
|
||||||
const asyncWrapper = require('../utils/asyncWrapper');
|
const asyncWrapper = require("../utils/asyncWrapper");
|
||||||
|
|
||||||
const _collectionManager = collectionManager;
|
const _collectionManager = collectionManager;
|
||||||
const _entryManager = entryManager;
|
const _entryManager = entryManager;
|
||||||
const _entryService = entryService;
|
const _entryService = entryService;
|
||||||
|
|
||||||
class EntryController {
|
class EntryController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EntryController.instance) {
|
if (!EntryController.instance) {
|
||||||
EntryController.instance = this;
|
EntryController.instance = this;
|
||||||
@@ -37,7 +36,10 @@ class EntryController {
|
|||||||
fetchAndSaveNewEntry = asyncWrapper(async (req, res) => {
|
fetchAndSaveNewEntry = asyncWrapper(async (req, res) => {
|
||||||
const { tmdb_id, is_tvserie } = req.body;
|
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);
|
res.status(201).json(createdEntry);
|
||||||
});
|
});
|
||||||
@@ -46,7 +48,11 @@ class EntryController {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { entryData } = req.body;
|
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);
|
res.status(201).json(updatedEntry);
|
||||||
});
|
});
|
||||||
@@ -56,7 +62,10 @@ class EntryController {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { entryRatings } = req.body;
|
const { entryRatings } = req.body;
|
||||||
|
|
||||||
const updatedEntryRatings = await _entryService.updateEntryRatings(id, entryRatings);
|
const updatedEntryRatings = await _entryService.updateEntryRatings(
|
||||||
|
id,
|
||||||
|
entryRatings,
|
||||||
|
);
|
||||||
|
|
||||||
res.status(200).json(updatedEntryRatings);
|
res.status(200).json(updatedEntryRatings);
|
||||||
});
|
});
|
||||||
@@ -66,7 +75,10 @@ class EntryController {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { entryIds } = req.body;
|
const { entryIds } = req.body;
|
||||||
|
|
||||||
const updatedEntryIds = await _entryService.updateEntryRatings(id, entryIds);
|
const updatedEntryIds = await _entryService.updateEntryRatings(
|
||||||
|
id,
|
||||||
|
entryIds,
|
||||||
|
);
|
||||||
|
|
||||||
res.status(200).json(updatedEntryIds);
|
res.status(200).json(updatedEntryIds);
|
||||||
});
|
});
|
||||||
@@ -90,10 +102,10 @@ class EntryController {
|
|||||||
getEntrySeasons = asyncWrapper(async (req, res) => {
|
getEntrySeasons = asyncWrapper(async (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
const seasons = await _entryService.getEntrySeasons(id)
|
const seasons = await _entryService.getEntrySeasons(id);
|
||||||
|
|
||||||
if (seasons.length == 0) {
|
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);
|
res.status(200).json(seasons);
|
||||||
@@ -110,7 +122,7 @@ class EntryController {
|
|||||||
refrechEntry = asyncWrapper(async (req, res, next) => {
|
refrechEntry = asyncWrapper(async (req, res, next) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
const entry = await _entryManager.refrechEntryById(id)
|
const entry = await _entryManager.refrechEntryById(id);
|
||||||
res.status(201).json(entry);
|
res.status(201).json(entry);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -132,7 +144,8 @@ class EntryController {
|
|||||||
const { type } = req.params;
|
const { type } = req.params;
|
||||||
const { page } = req.query;
|
const { page } = req.query;
|
||||||
const data = await tmdbService.fetchTrending(type, page || 1);
|
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);
|
res.status(200).json(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -141,16 +154,19 @@ class EntryController {
|
|||||||
const { type } = req.params;
|
const { type } = req.params;
|
||||||
const { page } = req.query;
|
const { page } = req.query;
|
||||||
const data = await tmdbService.fetchPopular(type, page || 1);
|
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);
|
res.status(200).json(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
// * GET - TMDB SEARCH
|
// * GET - TMDB SEARCH
|
||||||
getTmdbSearch = asyncWrapper(async (req, res) => {
|
getTmdbSearch = asyncWrapper(async (req, res) => {
|
||||||
const { query, page } = req.query;
|
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);
|
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);
|
res.status(200).json(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -159,7 +175,10 @@ class EntryController {
|
|||||||
const { type } = req.params;
|
const { type } = req.params;
|
||||||
const { page } = req.query;
|
const { page } = req.query;
|
||||||
const data = await tmdbService.fetchTopRated(type, page || 1);
|
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);
|
res.status(200).json(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -167,16 +186,18 @@ class EntryController {
|
|||||||
getTmdbUpcoming = asyncWrapper(async (req, res) => {
|
getTmdbUpcoming = asyncWrapper(async (req, res) => {
|
||||||
const { page } = req.query;
|
const { page } = req.query;
|
||||||
const data = await tmdbService.fetchUpcoming(page || 1);
|
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);
|
res.status(200).json(data);
|
||||||
});
|
});
|
||||||
|
|
||||||
// * GET - TMDB PREVIEW (fetch details without saving to library)
|
// * GET - TMDB PREVIEW (fetch details without saving to library)
|
||||||
getTmdbPreview = asyncWrapper(async (req, res) => {
|
getTmdbPreview = asyncWrapper(async (req, res) => {
|
||||||
const { type, tmdbId } = req.params;
|
const { type, tmdbId } = req.params;
|
||||||
const is_tvserie = type === 'tv';
|
const is_tvserie = type === "tv";
|
||||||
const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie);
|
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
|
// Fetch credits in parallel
|
||||||
const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie);
|
const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie);
|
||||||
@@ -187,10 +208,10 @@ class EntryController {
|
|||||||
for (const c of creditsData.cast) {
|
for (const c of creditsData.cast) {
|
||||||
credits.push({
|
credits.push({
|
||||||
id: c.credit_id || c.id,
|
id: c.credit_id || c.id,
|
||||||
cast_type: 'cast',
|
cast_type: "cast",
|
||||||
character: is_tvserie
|
character: is_tvserie
|
||||||
? (c.roles?.[0]?.character || c.character || null)
|
? c.roles?.[0]?.character || c.character || null
|
||||||
: (c.character || null),
|
: c.character || null,
|
||||||
people_id: c.id,
|
people_id: c.id,
|
||||||
people: {
|
people: {
|
||||||
id: c.id,
|
id: c.id,
|
||||||
@@ -208,9 +229,12 @@ class EntryController {
|
|||||||
title: data.title || data.name,
|
title: data.title || data.name,
|
||||||
original_title: data.original_title || data.original_name || null,
|
original_title: data.original_title || data.original_name || null,
|
||||||
release_date: data.release_date || data.first_air_date || 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,
|
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,
|
is_tvseries: is_tvserie,
|
||||||
status: data.status || null,
|
status: data.status || null,
|
||||||
poster_path: data.poster_path || null,
|
poster_path: data.poster_path || null,
|
||||||
|
|||||||
@@ -1,8 +1,7 @@
|
|||||||
const Entry = require("../models/Entry");
|
const Entry = require("../models/Entry");
|
||||||
const EntrySeen = require('../models/EntrySeen');
|
const EntrySeen = require("../models/EntrySeen");
|
||||||
|
|
||||||
class EntrySeenController {
|
class EntrySeenController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EntrySeenController.instance) {
|
if (!EntrySeenController.instance) {
|
||||||
EntrySeenController.instance = this;
|
EntrySeenController.instance = this;
|
||||||
@@ -19,7 +18,7 @@ class EntrySeenController {
|
|||||||
const entrySeen = await EntrySeen.findByPk(req.params.id);
|
const entrySeen = await EntrySeen.findByPk(req.params.id);
|
||||||
|
|
||||||
if (!entrySeen) {
|
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);
|
res.status(200).json(entrySeen);
|
||||||
@@ -35,7 +34,11 @@ class EntrySeenController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create a new EntrySeen record
|
// 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);
|
res.status(201).json(newEntrySeen);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,26 +46,30 @@ class EntrySeenController {
|
|||||||
const { entryId } = req.params;
|
const { entryId } = req.params;
|
||||||
const entrySeens = await EntrySeen.findAll({
|
const entrySeens = await EntrySeen.findAll({
|
||||||
where: { entry_id: entryId },
|
where: { entry_id: entryId },
|
||||||
order: [['date_seen', 'DESC']]
|
order: [["date_seen", "DESC"]],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (entrySeens.length > 0) {
|
if (entrySeens.length > 0) {
|
||||||
res.status(200).json(entrySeens);
|
res.status(200).json(entrySeens);
|
||||||
} else {
|
} 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) {
|
async updateEntrySeen(req, res) {
|
||||||
const { date_seen, seen_with } = req.body;
|
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) {
|
if (updated[0] > 0) {
|
||||||
const updatedEntrySeen = await EntrySeen.findByPk(req.params.id);
|
const updatedEntrySeen = await EntrySeen.findByPk(req.params.id);
|
||||||
res.status(200).json(updatedEntrySeen);
|
res.status(200).json(updatedEntrySeen);
|
||||||
} else {
|
} 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);
|
const entrySeen = await EntrySeen.findByPk(req.params.id);
|
||||||
|
|
||||||
if (!entrySeen)
|
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();
|
const deleted = await entrySeen.destroy();
|
||||||
|
|
||||||
@@ -78,7 +85,6 @@ class EntrySeenController {
|
|||||||
res.status(204).send();
|
res.status(204).send();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new EntrySeenController();
|
module.exports = new EntrySeenController();
|
||||||
@@ -3,7 +3,6 @@ const episodeService = require("../services/episodeService");
|
|||||||
const _episodeService = episodeService;
|
const _episodeService = episodeService;
|
||||||
|
|
||||||
class EpisodeController {
|
class EpisodeController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EpisodeController.instance) {
|
if (!EpisodeController.instance) {
|
||||||
EpisodeController.instance = this;
|
EpisodeController.instance = this;
|
||||||
@@ -14,13 +13,15 @@ class EpisodeController {
|
|||||||
async getEpisodesBetweenDates(req, res) {
|
async getEpisodesBetweenDates(req, res) {
|
||||||
const { startDate, endDate } = req.params;
|
const { startDate, endDate } = req.params;
|
||||||
try {
|
try {
|
||||||
const episodes = await _episodeService.getEpisodesBetweenDates(startDate, endDate)
|
const episodes = await _episodeService.getEpisodesBetweenDates(
|
||||||
|
startDate,
|
||||||
|
endDate,
|
||||||
|
);
|
||||||
res.status(200).json(episodes);
|
res.status(200).json(episodes);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new EpisodeController();
|
module.exports = new EpisodeController();
|
||||||
@@ -4,7 +4,6 @@ const EpisodeSeen = require("../models/EpisodeSeen");
|
|||||||
const Season = require("../models/Season");
|
const Season = require("../models/Season");
|
||||||
|
|
||||||
class EpisodeSeenController {
|
class EpisodeSeenController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EpisodeSeenController.instance) {
|
if (!EpisodeSeenController.instance) {
|
||||||
EpisodeSeenController.instance = this;
|
EpisodeSeenController.instance = this;
|
||||||
@@ -26,7 +25,7 @@ class EpisodeSeenController {
|
|||||||
const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
|
const episodeSeen = await EpisodeSeen.findByPk(req.params.id);
|
||||||
|
|
||||||
if (!episodeSeen) {
|
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);
|
res.status(200).json(episodeSeen);
|
||||||
@@ -40,15 +39,18 @@ class EpisodeSeenController {
|
|||||||
const { entry_id, episode_id, date_seen, seen_with } = req.body;
|
const { entry_id, episode_id, date_seen, seen_with } = req.body;
|
||||||
|
|
||||||
const entry = await Entry.findByPk(entry_id);
|
const entry = await Entry.findByPk(entry_id);
|
||||||
if (!entry)
|
if (!entry) return res.status(404).json({ error: "Entry not found" });
|
||||||
return res.status(404).json({ error: "Entry not found" });
|
|
||||||
|
|
||||||
const episode = await Episode.findByPk(episode_id);
|
const episode = await Episode.findByPk(episode_id);
|
||||||
if (!episode)
|
if (!episode) return res.status(404).json({ error: "Episode not found" });
|
||||||
return res.status(404).json({ error: "Episode not found" });
|
|
||||||
|
|
||||||
// Create a new EpisodeSeen record
|
// 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);
|
res.status(201).json(newEpisodeSeen);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(400).json({ error: error.message });
|
res.status(400).json({ error: error.message });
|
||||||
@@ -61,13 +63,15 @@ class EpisodeSeenController {
|
|||||||
const { episodeId } = req.params;
|
const { episodeId } = req.params;
|
||||||
const episodeSeens = await EpisodeSeen.findAll({
|
const episodeSeens = await EpisodeSeen.findAll({
|
||||||
where: { episode_id: episodeId },
|
where: { episode_id: episodeId },
|
||||||
order: [['date_seen', 'DESC']]
|
order: [["date_seen", "DESC"]],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (episodeSeens.length > 0) {
|
if (episodeSeens.length > 0) {
|
||||||
res.status(200).json(episodeSeens);
|
res.status(200).json(episodeSeens);
|
||||||
} else {
|
} 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) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
@@ -79,24 +83,29 @@ class EpisodeSeenController {
|
|||||||
const { entryId } = req.params;
|
const { entryId } = req.params;
|
||||||
const episodeSeens = await EpisodeSeen.findAll({
|
const episodeSeens = await EpisodeSeen.findAll({
|
||||||
where: { entry_id: entryId },
|
where: { entry_id: entryId },
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: Episode,
|
model: Episode,
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: Season,
|
model: Season,
|
||||||
attributes: ['season_number'],
|
attributes: ["season_number"],
|
||||||
}],
|
},
|
||||||
attributes: ['episode_number'],
|
],
|
||||||
}],
|
attributes: ["episode_number"],
|
||||||
|
},
|
||||||
|
],
|
||||||
order: [
|
order: [
|
||||||
['date_seen', 'DESC'],
|
["date_seen", "DESC"],
|
||||||
[{ model: Episode }, { model: Season }, 'season_number', 'DESC'],
|
[{ model: Episode }, { model: Season }, "season_number", "DESC"],
|
||||||
// [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this
|
// [Sequelize.literal('"Episode->Season"."season_number"'), 'DESC'], // ! or this
|
||||||
[Episode, 'episode_number', 'DESC']]
|
[Episode, "episode_number", "DESC"],
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
res.status(200).json(episodeSeens);
|
res.status(200).json(episodeSeens);
|
||||||
} catch (error) {
|
} 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 });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,16 +114,18 @@ class EpisodeSeenController {
|
|||||||
try {
|
try {
|
||||||
const { date_seen, seen_with, episode_id } = req.body;
|
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)
|
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 });
|
const updated = await episodeSeen.update({ date_seen, seen_with });
|
||||||
|
|
||||||
if (updated) {
|
if (updated) {
|
||||||
res.status(200).json(updated);
|
res.status(200).json(updated);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: 'Episode seen record not found.' });
|
res.status(404).json({ message: "Episode seen record not found." });
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
@@ -126,19 +137,17 @@ class EpisodeSeenController {
|
|||||||
// ? getting the episode seen object
|
// ? getting the episode seen object
|
||||||
const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id);
|
const oldEpisodeSeen = await EpisodeSeen.findByPk(req.params.id);
|
||||||
if (!oldEpisodeSeen)
|
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
|
// ?deleting the episode seen
|
||||||
const deleted = await oldEpisodeSeen.destroy();
|
const deleted = await oldEpisodeSeen.destroy();
|
||||||
|
|
||||||
if (deleted)
|
if (deleted) res.status(204).send();
|
||||||
res.status(204).send();
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
console.log(error)
|
console.log(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new EpisodeSeenController();
|
module.exports = new EpisodeSeenController();
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
const { bulkImportMovies, bulkImportTmdb, bulkImportEpisodes } = require("../services/importerService");
|
const {
|
||||||
|
bulkImportMovies,
|
||||||
|
bulkImportTmdb,
|
||||||
|
bulkImportEpisodes,
|
||||||
|
} = require("../services/importerService");
|
||||||
|
|
||||||
class ImportController {
|
class ImportController {
|
||||||
constructor() {
|
constructor() {
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
class KillerController {
|
class KillerController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!KillerController.instance) {
|
if (!KillerController.instance) {
|
||||||
KillerController.instance = this;
|
KillerController.instance = this;
|
||||||
@@ -8,11 +7,10 @@ class KillerController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async killBackend(req, res) {
|
async killBackend(req, res) {
|
||||||
console.log("Killing backend.")
|
console.log("Killing backend.");
|
||||||
res.status(200).json({ message: "Backend killed." });
|
res.status(200).json({ message: "Backend killed." });
|
||||||
console.log(kill);
|
console.log(kill);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new KillerController();
|
module.exports = new KillerController();
|
||||||
@@ -1,19 +1,18 @@
|
|||||||
const path = require('path');
|
const path = require("path");
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
|
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require("../models/Entry");
|
||||||
const Media = require('../models/Media');
|
const Media = require("../models/Media");
|
||||||
const Collection = require('../models/Collection');
|
const Collection = require("../models/Collection");
|
||||||
|
|
||||||
const configService = require('../services/configService.js');
|
const configService = require("../services/configService.js");
|
||||||
const { logToFile } = require('../services/logService');
|
const { logToFile } = require("../services/logService");
|
||||||
const mediaOptimizerService = require('../services/mediaOptimizerService.js');
|
const mediaOptimizerService = require("../services/mediaOptimizerService.js");
|
||||||
const asyncWrapper = require('../utils/asyncWrapper');
|
const asyncWrapper = require("../utils/asyncWrapper");
|
||||||
|
|
||||||
const _mediaOptimizerService = mediaOptimizerService;
|
const _mediaOptimizerService = mediaOptimizerService;
|
||||||
|
|
||||||
class MediaController {
|
class MediaController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!MediaController.instance) {
|
if (!MediaController.instance) {
|
||||||
MediaController.instance = this;
|
MediaController.instance = this;
|
||||||
@@ -21,7 +20,6 @@ class MediaController {
|
|||||||
return MediaController.instance;
|
return MediaController.instance;
|
||||||
}
|
}
|
||||||
getMedias = asyncWrapper(async (req, res) => {
|
getMedias = asyncWrapper(async (req, res) => {
|
||||||
|
|
||||||
const allCustomMedia = await Media.findAll({
|
const allCustomMedia = await Media.findAll({
|
||||||
where: {
|
where: {
|
||||||
isCustom: true,
|
isCustom: true,
|
||||||
@@ -29,15 +27,15 @@ class MediaController {
|
|||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: 'entry',
|
as: "entry",
|
||||||
required: false // This ensures a LEFT OUTER JOIN
|
required: false, // This ensures a LEFT OUTER JOIN
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: Collection,
|
model: Collection,
|
||||||
as: 'collection',
|
as: "collection",
|
||||||
required: false // This ensures a LEFT OUTER JOIN
|
required: false, // This ensures a LEFT OUTER JOIN
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
res.status(200).json(allCustomMedia);
|
res.status(200).json(allCustomMedia);
|
||||||
@@ -46,26 +44,46 @@ class MediaController {
|
|||||||
getMedia(req, res, next) {
|
getMedia(req, res, next) {
|
||||||
const { category, type, size, fileName } = req.params;
|
const { category, type, size, fileName } = req.params;
|
||||||
|
|
||||||
if (!['entries', 'collections', 'franchises', 'seasons', 'episodes', 'peoples'].includes(category)) {
|
if (
|
||||||
return res.status(404).send('Category Not Found');
|
![
|
||||||
|
"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)) {
|
if (
|
||||||
return res.status(404).send('Type Not Found');
|
![
|
||||||
|
"backdrops",
|
||||||
|
"posters",
|
||||||
|
"logos",
|
||||||
|
"stills",
|
||||||
|
"profiles",
|
||||||
|
"others",
|
||||||
|
].includes(type)
|
||||||
|
) {
|
||||||
|
return res.status(404).send("Type Not Found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const settings = configService.getSettings();
|
const settings = configService.getSettings();
|
||||||
const dataPath = settings.userDataPath;
|
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}`);
|
// const mediaPath = path.join(__dirname, '..', `data/images/${category}/${type}`);
|
||||||
|
|
||||||
// * preparing to serve the preview
|
// * preparing to serve the preview
|
||||||
// ? basicaly im checking if the file requested is a preview file
|
// ? 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)
|
// ? if so I make sure to change the extention to '_preview.jpg' (bcs all previews are jpg)
|
||||||
let filePath = path.join(mediaPath, fileName);
|
let filePath = path.join(mediaPath, fileName);
|
||||||
if (size == 'preview') {
|
if (size == "preview") {
|
||||||
const previewFileName = fileName.split('.')[0] + (type == 'logos' ? '_preview.png' : '_preview.jpg')
|
const previewFileName =
|
||||||
|
fileName.split(".")[0] +
|
||||||
|
(type == "logos" ? "_preview.png" : "_preview.jpg");
|
||||||
filePath = path.join(mediaPath, previewFileName);
|
filePath = path.join(mediaPath, previewFileName);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,7 +94,7 @@ class MediaController {
|
|||||||
// ? the original file name, and starting from that I join it to the media path
|
// ? 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
|
// ? and generate a preview file, but still return 202 http code since the file
|
||||||
// ? is still generating
|
// ? is still generating
|
||||||
if (err && size == 'preview') {
|
if (err && size == "preview") {
|
||||||
// const originalPath = path.join(mediaPath, fileName);
|
// const originalPath = path.join(mediaPath, fileName);
|
||||||
// const previewFileName = fileName.split('.')[0] + '_preview.jpg'
|
// const previewFileName = fileName.split('.')[0] + '_preview.jpg'
|
||||||
// const previewPath = path.join(mediaPath, previewFileName);
|
// const previewPath = path.join(mediaPath, previewFileName);
|
||||||
@@ -85,11 +103,14 @@ class MediaController {
|
|||||||
// if (type == 'backdrops') previewWidth = 780;
|
// if (type == 'backdrops') previewWidth = 780;
|
||||||
// if (type == 'logos') previewWidth = 300;
|
// if (type == 'logos') previewWidth = 300;
|
||||||
|
|
||||||
_mediaOptimizerService.doGeneratePreview(category, type, fileName).then((result) => {
|
_mediaOptimizerService
|
||||||
|
.doGeneratePreview(category, type, fileName)
|
||||||
|
.then((result) => {
|
||||||
const stream = fs.createReadStream(filePath);
|
const stream = fs.createReadStream(filePath);
|
||||||
stream.pipe(res);
|
stream.pipe(res);
|
||||||
logToFile(`Media Route | Generated Preview`);
|
logToFile(`Media Route | Generated Preview`);
|
||||||
}).catch((err) => {
|
})
|
||||||
|
.catch((err) => {
|
||||||
logToFile(`Media Route | Error Generating Preview`);
|
logToFile(`Media Route | Error Generating Preview`);
|
||||||
logToFile(err);
|
logToFile(err);
|
||||||
});
|
});
|
||||||
@@ -108,7 +129,6 @@ class MediaController {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new MediaController();
|
module.exports = new MediaController();
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
const peopleService = require("../services/peopleService");
|
const peopleService = require("../services/peopleService");
|
||||||
const peopleManager = require("../services/peopleManager");
|
const peopleManager = require("../services/peopleManager");
|
||||||
const tmdbService = require('../services/tmdbService');
|
const tmdbService = require("../services/tmdbService");
|
||||||
|
|
||||||
const _peopleService = peopleService;
|
const _peopleService = peopleService;
|
||||||
const _peopleManager = peopleManager;
|
const _peopleManager = peopleManager;
|
||||||
@@ -60,7 +60,9 @@ class PeopleController {
|
|||||||
|
|
||||||
async fetchAndSavePersonByTmdbId(req, res) {
|
async fetchAndSavePersonByTmdbId(req, res) {
|
||||||
const { tmdb_id, pinned } = req.body;
|
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);
|
res.status(201).json(person);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +75,7 @@ class PeopleController {
|
|||||||
async getPersonCredits(req, res) {
|
async getPersonCredits(req, res) {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const person = await _peopleService.getPersonById(id);
|
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 ?? []);
|
res.status(200).json(person.roles ?? []);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,10 +83,15 @@ class PeopleController {
|
|||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const person = await _peopleService.getPersonById(id);
|
const person = await _peopleService.getPersonById(id);
|
||||||
if (!person || !person.tmdb_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);
|
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);
|
res.status(200).json(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +100,9 @@ class PeopleController {
|
|||||||
const person = await _peopleService.getPersonById(id);
|
const person = await _peopleService.getPersonById(id);
|
||||||
|
|
||||||
if (person && person.tmdb_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);
|
res.status(200).json(updatedPerson);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).json({ message: "Person not found or missing TMDB ID" });
|
res.status(404).json({ message: "Person not found or missing TMDB ID" });
|
||||||
@@ -103,31 +112,41 @@ class PeopleController {
|
|||||||
async getTmdbPopularPeople(req, res) {
|
async getTmdbPopularPeople(req, res) {
|
||||||
const { page } = req.query;
|
const { page } = req.query;
|
||||||
const data = await tmdbService.fetchPopularPeople(page || 1);
|
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);
|
res.status(200).json(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
async searchTmdbPeople(req, res) {
|
async searchTmdbPeople(req, res) {
|
||||||
const { query, page } = req.query;
|
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);
|
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);
|
res.status(200).json(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTmdbPersonPreview(req, res) {
|
async getTmdbPersonPreview(req, res) {
|
||||||
const { tmdbId } = req.params;
|
const { tmdbId } = req.params;
|
||||||
const personData = await tmdbService.fetchPersonDetails(tmdbId);
|
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);
|
const filmography = await tmdbService.fetchPersonCombinedCredits(tmdbId);
|
||||||
|
|
||||||
// Check if person already exists in local DB
|
// Check if person already exists in local DB
|
||||||
let localId = null;
|
let localId = null;
|
||||||
try {
|
try {
|
||||||
const localPerson = await _peopleService.getPersonByTmdbId(parseInt(tmdbId));
|
const localPerson = await _peopleService.getPersonByTmdbId(
|
||||||
|
parseInt(tmdbId),
|
||||||
|
);
|
||||||
if (localPerson) localId = localPerson.id;
|
if (localPerson) localId = localPerson.id;
|
||||||
} catch (_) { /* not found */ }
|
} catch (_) {
|
||||||
|
/* not found */
|
||||||
|
}
|
||||||
|
|
||||||
const preview = {
|
const preview = {
|
||||||
tmdb_id: personData.id,
|
tmdb_id: personData.id,
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
class PingController {
|
class PingController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!PingController.instance) {
|
if (!PingController.instance) {
|
||||||
PingController.instance = this;
|
PingController.instance = this;
|
||||||
@@ -8,11 +7,10 @@ class PingController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
ping(req, res) {
|
ping(req, res) {
|
||||||
console.log("Ping Pong...")
|
console.log("Ping Pong...");
|
||||||
|
|
||||||
res.status(200).json({ message: 'pong' });
|
res.status(200).json({ message: "pong" });
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new PingController();
|
module.exports = new PingController();
|
||||||
@@ -2,9 +2,7 @@ const Episode = require("../models/Episode");
|
|||||||
const EpisodeSeen = require("../models/EpisodeSeen");
|
const EpisodeSeen = require("../models/EpisodeSeen");
|
||||||
const Season = require("../models/Season");
|
const Season = require("../models/Season");
|
||||||
|
|
||||||
|
|
||||||
class SeasonController {
|
class SeasonController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!SeasonController.instance) {
|
if (!SeasonController.instance) {
|
||||||
SeasonController.instance = this;
|
SeasonController.instance = this;
|
||||||
@@ -33,16 +31,18 @@ class SeasonController {
|
|||||||
async getSeaonById(req, res) {
|
async getSeaonById(req, res) {
|
||||||
try {
|
try {
|
||||||
const season = await Season.findByPk(req.params.id, {
|
const season = await Season.findByPk(req.params.id, {
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: Episode,
|
model: Episode,
|
||||||
as: 'episodes'
|
as: "episodes",
|
||||||
}]
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (season) {
|
if (season) {
|
||||||
res.send(season);
|
res.send(season);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).send('Season not found');
|
res.status(404).send("Season not found");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).send(error.message);
|
res.status(500).send(error.message);
|
||||||
@@ -53,19 +53,19 @@ class SeasonController {
|
|||||||
try {
|
try {
|
||||||
const episodes = await Episode.findAll({
|
const episodes = await Episode.findAll({
|
||||||
where: {
|
where: {
|
||||||
season_id: req.params.id
|
season_id: req.params.id,
|
||||||
},
|
},
|
||||||
include: [{ model: EpisodeSeen }],
|
include: [{ model: EpisodeSeen }],
|
||||||
order: [
|
order: [
|
||||||
['episode_number', 'ASC'],
|
["episode_number", "ASC"],
|
||||||
[EpisodeSeen, 'date_seen', 'ASC'],
|
[EpisodeSeen, "date_seen", "ASC"],
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (episodes) {
|
if (episodes) {
|
||||||
res.send(episodes);
|
res.send(episodes);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).send('Episodes not found');
|
res.status(404).send("Episodes not found");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).send(error.message);
|
res.status(500).send(error.message);
|
||||||
@@ -75,13 +75,13 @@ class SeasonController {
|
|||||||
async updateSeason(req, res) {
|
async updateSeason(req, res) {
|
||||||
try {
|
try {
|
||||||
const [updated] = await Season.update(req.body, {
|
const [updated] = await Season.update(req.body, {
|
||||||
where: { id: req.params.id }
|
where: { id: req.params.id },
|
||||||
});
|
});
|
||||||
if (updated) {
|
if (updated) {
|
||||||
const updatedSeason = await Season.findByPk(req.params.id);
|
const updatedSeason = await Season.findByPk(req.params.id);
|
||||||
res.send(updatedSeason);
|
res.send(updatedSeason);
|
||||||
} else {
|
} else {
|
||||||
res.status(404).send('Season not found');
|
res.status(404).send("Season not found");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).send(error.message);
|
res.status(500).send(error.message);
|
||||||
@@ -91,18 +91,17 @@ class SeasonController {
|
|||||||
async deleteSeason(req, res) {
|
async deleteSeason(req, res) {
|
||||||
try {
|
try {
|
||||||
const deleted = await Season.destroy({
|
const deleted = await Season.destroy({
|
||||||
where: { id: req.params.id }
|
where: { id: req.params.id },
|
||||||
});
|
});
|
||||||
if (deleted) {
|
if (deleted) {
|
||||||
res.status(204).send('Season deleted');
|
res.status(204).send("Season deleted");
|
||||||
} else {
|
} else {
|
||||||
res.status(404).send('Season not found');
|
res.status(404).send("Season not found");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).send(error.message);
|
res.status(500).send(error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new SeasonController();
|
module.exports = new SeasonController();
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
const configService = require('../services/configService');
|
const configService = require("../services/configService");
|
||||||
|
|
||||||
const _configService = configService;
|
const _configService = configService;
|
||||||
|
|
||||||
class SettingsController {
|
class SettingsController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!SettingsController.instance) {
|
if (!SettingsController.instance) {
|
||||||
SettingsController.instance = this;
|
SettingsController.instance = this;
|
||||||
@@ -17,7 +16,7 @@ class SettingsController {
|
|||||||
|
|
||||||
res.status(200).json(settings);
|
res.status(200).json(settings);
|
||||||
} catch (err) {
|
} 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());
|
res.status(200).send(configService.getSettings());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new SettingsController();
|
module.exports = new SettingsController();
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
const { Op } = require('sequelize');
|
const { Op } = require("sequelize");
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require("../models/Entry");
|
||||||
const EntrySeen = require('../models/EntrySeen');
|
const EntrySeen = require("../models/EntrySeen");
|
||||||
const Episode = require('../models/Episode');
|
const Episode = require("../models/Episode");
|
||||||
const EpisodeSeen = require('../models/EpisodeSeen');
|
const EpisodeSeen = require("../models/EpisodeSeen");
|
||||||
|
|
||||||
class StatisticsController {
|
class StatisticsController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!StatisticsController.instance) {
|
if (!StatisticsController.instance) {
|
||||||
StatisticsController.instance = this;
|
StatisticsController.instance = this;
|
||||||
@@ -16,27 +15,23 @@ class StatisticsController {
|
|||||||
|
|
||||||
async getAllTimeWatchTime(req, res) {
|
async getAllTimeWatchTime(req, res) {
|
||||||
const totalWatchTimeSeries = await EpisodeSeen.findOne({
|
const totalWatchTimeSeries = await EpisodeSeen.findOne({
|
||||||
include: [
|
include: [{ model: Episode, as: "episode", attributes: [] }],
|
||||||
{ model: Episode, as: 'episode', attributes: [] }
|
|
||||||
],
|
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
|
[sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"],
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const totalWatchTimeMovies = await EntrySeen.findOne({
|
const totalWatchTimeMovies = await EntrySeen.findOne({
|
||||||
include: [
|
include: [{ model: Entry, as: "entry", attributes: [] }],
|
||||||
{ model: Entry, as: 'entry', attributes: [] }
|
|
||||||
],
|
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
|
[sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"],
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const totalWatchTime = {
|
const totalWatchTime = {
|
||||||
series: totalWatchTimeSeries.dataValues.watchTime,
|
series: totalWatchTimeSeries.dataValues.watchTime,
|
||||||
movies: totalWatchTimeMovies.dataValues.watchTime
|
movies: totalWatchTimeMovies.dataValues.watchTime,
|
||||||
}
|
};
|
||||||
|
|
||||||
return res.status(200).json(totalWatchTime);
|
return res.status(200).json(totalWatchTime);
|
||||||
}
|
}
|
||||||
@@ -45,41 +40,37 @@ class StatisticsController {
|
|||||||
const { year } = req.params;
|
const { year } = req.params;
|
||||||
|
|
||||||
const totalWatchTimeSeries = await EpisodeSeen.findAll({
|
const totalWatchTimeSeries = await EpisodeSeen.findAll({
|
||||||
include: [
|
include: [{ model: Episode, as: "episode", attributes: [] }],
|
||||||
{ model: Episode, as: 'episode', attributes: [] }
|
|
||||||
],
|
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
|
[sequelize.fn("MONTH", sequelize.col("date_seen")), "month"],
|
||||||
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
|
[sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
date_seen: {
|
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({
|
const totalWatchTimeMovies = await EntrySeen.findAll({
|
||||||
include: [
|
include: [{ model: Entry, as: "entry", attributes: [] }],
|
||||||
{ model: Entry, as: 'entry', attributes: [] }
|
|
||||||
],
|
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
|
[sequelize.fn("MONTH", sequelize.col("date_seen")), "month"],
|
||||||
[sequelize.fn('SUM', sequelize.col('runtime')), 'watchTime']
|
[sequelize.fn("SUM", sequelize.col("runtime")), "watchTime"],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
date_seen: {
|
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 = {
|
const totalWatchTime = {
|
||||||
series: totalWatchTimeSeries,
|
series: totalWatchTimeSeries,
|
||||||
movies: totalWatchTimeMovies
|
movies: totalWatchTimeMovies,
|
||||||
}
|
};
|
||||||
|
|
||||||
return res.status(200).json(totalWatchTime);
|
return res.status(200).json(totalWatchTime);
|
||||||
}
|
}
|
||||||
@@ -89,33 +80,33 @@ class StatisticsController {
|
|||||||
const { year } = req.params;
|
const { year } = req.params;
|
||||||
const seriesCount = await EpisodeSeen.findAll({
|
const seriesCount = await EpisodeSeen.findAll({
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
|
[sequelize.fn("MONTH", sequelize.col("date_seen")), "month"],
|
||||||
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
|
[sequelize.fn("COUNT", sequelize.col("*")), "count"],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
date_seen: {
|
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({
|
const moviesCount = await EntrySeen.findAll({
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('MONTH', sequelize.col('date_seen')), 'month'],
|
[sequelize.fn("MONTH", sequelize.col("date_seen")), "month"],
|
||||||
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
|
[sequelize.fn("COUNT", sequelize.col("*")), "count"],
|
||||||
],
|
],
|
||||||
where: {
|
where: {
|
||||||
date_seen: {
|
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 });
|
res.status(200).json({ series: seriesCount, movies: moviesCount });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error)
|
console.log(error);
|
||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -126,20 +117,20 @@ class StatisticsController {
|
|||||||
// Only count records with EXACT accuracy
|
// Only count records with EXACT accuracy
|
||||||
const episodeDays = await EpisodeSeen.findAll({
|
const episodeDays = await EpisodeSeen.findAll({
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('DAYOFWEEK', sequelize.col('date_seen')), 'day'],
|
[sequelize.fn("DAYOFWEEK", sequelize.col("date_seen")), "day"],
|
||||||
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
|
[sequelize.fn("COUNT", sequelize.col("*")), "count"],
|
||||||
],
|
],
|
||||||
where: { accuracy: 'EXACT' },
|
where: { accuracy: "EXACT" },
|
||||||
group: [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen'))]
|
group: [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen"))],
|
||||||
});
|
});
|
||||||
|
|
||||||
const movieDays = await EntrySeen.findAll({
|
const movieDays = await EntrySeen.findAll({
|
||||||
attributes: [
|
attributes: [
|
||||||
[sequelize.fn('DAYOFWEEK', sequelize.col('date_seen')), 'day'],
|
[sequelize.fn("DAYOFWEEK", sequelize.col("date_seen")), "day"],
|
||||||
[sequelize.fn('COUNT', sequelize.col('*')), 'count']
|
[sequelize.fn("COUNT", sequelize.col("*")), "count"],
|
||||||
],
|
],
|
||||||
where: { accuracy: 'EXACT' },
|
where: { accuracy: "EXACT" },
|
||||||
group: [sequelize.fn('DAYOFWEEK', sequelize.col('date_seen'))]
|
group: [sequelize.fn("DAYOFWEEK", sequelize.col("date_seen"))],
|
||||||
});
|
});
|
||||||
|
|
||||||
res.status(200).json({ episodes: episodeDays, movies: movieDays });
|
res.status(200).json({ episodes: episodeDays, movies: movieDays });
|
||||||
@@ -148,7 +139,6 @@ class StatisticsController {
|
|||||||
res.status(500).json({ error: error.message });
|
res.status(500).json({ error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new StatisticsController();
|
module.exports = new StatisticsController();
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 400 Bad Request.
|
* Represents an error for HTTP 400 Bad Request.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 409 Conflict.
|
* Represents an error for HTTP 409 Conflict.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 403 Forbidden.
|
* Represents an error for HTTP 403 Forbidden.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 500 Internal Server Error.
|
* Represents an error for HTTP 500 Internal Server Error.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 404 Not Found.
|
* Represents an error for HTTP 404 Not Found.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 401 Unauthorized.
|
* Represents an error for HTTP 401 Unauthorized.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
const CustomError = require('./CustomError');
|
const CustomError = require("./CustomError");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents an error for HTTP 422 Unprocessable Entity.
|
* Represents an error for HTTP 422 Unprocessable Entity.
|
||||||
|
|||||||
@@ -1,46 +1,52 @@
|
|||||||
const CustomError = require('../errors/CustomError');
|
const CustomError = require("../errors/CustomError");
|
||||||
const { logToFile } = require('../services/logService');
|
const { logToFile } = require("../services/logService");
|
||||||
|
|
||||||
module.exports = (err, req, res, next) => {
|
module.exports = (err, req, res, next) => {
|
||||||
// Log the error for debugging purposes
|
// Log the error for debugging purposes
|
||||||
console.log(`📌 Error caught in middleware:`, err);
|
console.log(`📌 Error caught in middleware:`, err);
|
||||||
|
|
||||||
if (err instanceof CustomError) {
|
if (err instanceof CustomError) {
|
||||||
logToFile(`Custom Error (${err.statusCode()}) - ${req.method} ${req.path}: ${err.message}`);
|
logToFile(
|
||||||
|
`Custom Error (${err.statusCode()}) - ${req.method} ${req.path}: ${err.message}`,
|
||||||
|
);
|
||||||
res.status(err.statusCode()).json({
|
res.status(err.statusCode()).json({
|
||||||
message: err.message,
|
message: err.message,
|
||||||
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
|
error: process.env.NODE_ENV === "development" ? err.stack : undefined,
|
||||||
});
|
});
|
||||||
} else if (err.name === 'ValidationError') {
|
} else if (err.name === "ValidationError") {
|
||||||
// Handle Sequelize validation errors
|
// Handle Sequelize validation errors
|
||||||
logToFile(`Validation Error - ${req.method} ${req.path}: ${err.message}`);
|
logToFile(`Validation Error - ${req.method} ${req.path}: ${err.message}`);
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: 'Validation Error',
|
message: "Validation Error",
|
||||||
details: err.errors || err.message,
|
details: err.errors || err.message,
|
||||||
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
|
error: process.env.NODE_ENV === "development" ? err.stack : undefined,
|
||||||
});
|
});
|
||||||
} else if (err.name === 'SequelizeUniqueConstraintError') {
|
} else if (err.name === "SequelizeUniqueConstraintError") {
|
||||||
// Handle Sequelize unique constraint errors
|
// Handle Sequelize unique constraint errors
|
||||||
logToFile(`Unique Constraint Error - ${req.method} ${req.path}: ${err.message}`);
|
logToFile(
|
||||||
|
`Unique Constraint Error - ${req.method} ${req.path}: ${err.message}`,
|
||||||
|
);
|
||||||
res.status(409).json({
|
res.status(409).json({
|
||||||
message: 'Duplicate entry detected',
|
message: "Duplicate entry detected",
|
||||||
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
|
error: process.env.NODE_ENV === "development" ? err.stack : undefined,
|
||||||
});
|
});
|
||||||
} else if (err.name === 'SequelizeForeignKeyConstraintError') {
|
} else if (err.name === "SequelizeForeignKeyConstraintError") {
|
||||||
// Handle foreign key constraint errors
|
// Handle foreign key constraint errors
|
||||||
logToFile(`Foreign Key Error - ${req.method} ${req.path}: ${err.message}`);
|
logToFile(`Foreign Key Error - ${req.method} ${req.path}: ${err.message}`);
|
||||||
res.status(400).json({
|
res.status(400).json({
|
||||||
message: 'Invalid reference to related data',
|
message: "Invalid reference to related data",
|
||||||
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
|
error: process.env.NODE_ENV === "development" ? err.stack : undefined,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Handle all other errors
|
// Handle all other errors
|
||||||
const errorMessage = err.message || 'Internal server error';
|
const errorMessage = err.message || "Internal server error";
|
||||||
logToFile(`Unexpected Error - ${req.method} ${req.path}: ${errorMessage}\nStack: ${err.stack}`);
|
logToFile(
|
||||||
|
`Unexpected Error - ${req.method} ${req.path}: ${errorMessage}\nStack: ${err.stack}`,
|
||||||
|
);
|
||||||
|
|
||||||
res.status(500).json({
|
res.status(500).json({
|
||||||
message: 'Internal server error',
|
message: "Internal server error",
|
||||||
error: process.env.NODE_ENV === 'development' ? err.stack : undefined
|
error: process.env.NODE_ENV === "development" ? err.stack : undefined,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,22 +1,24 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Collection = sequelize.define("userCollection",
|
const Collection = sequelize.define("userCollection", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
tmdbId: { type: DataTypes.STRING(30), field: 'tmdb_id' },
|
tmdbId: { type: DataTypes.STRING(30), field: "tmdb_id" },
|
||||||
imdbId: { type: DataTypes.STRING(30), field: 'imdb_id' },
|
imdbId: { type: DataTypes.STRING(30), field: "imdb_id" },
|
||||||
tvdbId: { type: DataTypes.STRING(30), field: 'tvdb_id' },
|
tvdbId: { type: DataTypes.STRING(30), field: "tvdb_id" },
|
||||||
|
|
||||||
name: { type: DataTypes.STRING(150) },
|
name: { type: DataTypes.STRING(150) },
|
||||||
description: { type: DataTypes.STRING(3000) },
|
description: { type: DataTypes.STRING(3000) },
|
||||||
isUserCollection: { type: DataTypes.BOOLEAN, defaultValue: false, field: 'is_user_collection' },
|
isUserCollection: {
|
||||||
userRating: { type: DataTypes.FLOAT, field: 'user_rating' },
|
type: DataTypes.BOOLEAN,
|
||||||
|
defaultValue: false,
|
||||||
|
field: "is_user_collection",
|
||||||
|
},
|
||||||
|
userRating: { type: DataTypes.FLOAT, field: "user_rating" },
|
||||||
|
|
||||||
posterPath: { type: DataTypes.STRING(200), field: 'poster_path' },
|
posterPath: { type: DataTypes.STRING(200), field: "poster_path" },
|
||||||
backdropPath: { type: DataTypes.STRING(200), field: 'backdrop_path' },
|
backdropPath: { type: DataTypes.STRING(200), field: "backdrop_path" },
|
||||||
isLocal: { type: DataTypes.BOOLEAN, defaultValue: false, field: 'is_local' }
|
isLocal: { type: DataTypes.BOOLEAN, defaultValue: false, field: "is_local" },
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = Collection;
|
module.exports = Collection;
|
||||||
+12
-10
@@ -1,26 +1,28 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Credit = sequelize.define("credits",
|
const Credit = sequelize.define("credits", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
tmdb_credit_id: { type: DataTypes.STRING(100) },
|
tmdb_credit_id: { type: DataTypes.STRING(100) },
|
||||||
|
|
||||||
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
|
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
profile_path: { type: DataTypes.STRING(200), field: 'profile_path' },
|
profile_path: { type: DataTypes.STRING(200), field: "profile_path" },
|
||||||
|
|
||||||
character: { type: DataTypes.STRING(500) },
|
character: { type: DataTypes.STRING(500) },
|
||||||
order: { type: DataTypes.INTEGER },
|
order: { type: DataTypes.INTEGER },
|
||||||
episode_count: { type: DataTypes.INTEGER, defaultValue: null },
|
episode_count: { type: DataTypes.INTEGER, defaultValue: null },
|
||||||
|
|
||||||
cast_type: { type: DataTypes.ENUM('cast', 'crew'), field: 'cast_type', defaultValue: 'cast' },
|
cast_type: {
|
||||||
|
type: DataTypes.ENUM("cast", "crew"),
|
||||||
|
field: "cast_type",
|
||||||
|
defaultValue: "cast",
|
||||||
|
},
|
||||||
department: { type: DataTypes.STRING(100) },
|
department: { type: DataTypes.STRING(100) },
|
||||||
job: { type: DataTypes.STRING(500) },
|
job: { type: DataTypes.STRING(500) },
|
||||||
|
|
||||||
entry_id: { type: DataTypes.INTEGER, field: 'entry_id' },
|
entry_id: { type: DataTypes.INTEGER, field: "entry_id" },
|
||||||
people_id: { type: DataTypes.INTEGER, field: 'people_id' },
|
people_id: { type: DataTypes.INTEGER, field: "people_id" },
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = Credit;
|
module.exports = Credit;
|
||||||
@@ -1,29 +1,32 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const EntryGenre = sequelize.define('entryGenre',
|
const EntryGenre = sequelize.define(
|
||||||
|
"entryGenre",
|
||||||
{
|
{
|
||||||
genre_id: {
|
genre_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
references: {
|
references: {
|
||||||
model: 'Genres',
|
model: "Genres",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
primaryKey: ["genre_id", "entry_id"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
primaryKey: ['genre_id', 'entry_id'],
|
|
||||||
}, {
|
|
||||||
timestamps: false,
|
timestamps: false,
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = EntryGenre;
|
module.exports = EntryGenre;
|
||||||
@@ -1,22 +1,24 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const EntryId = sequelize.define("entryId",
|
const EntryId = sequelize.define(
|
||||||
|
"entryId",
|
||||||
{
|
{
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
tmdb_id: { type: DataTypes.STRING(30) },
|
tmdb_id: { type: DataTypes.STRING(30) },
|
||||||
imdb_id: { type: DataTypes.STRING(30) },
|
imdb_id: { type: DataTypes.STRING(30) },
|
||||||
tvdb_id: { type: DataTypes.STRING(30) },
|
tvdb_id: { type: DataTypes.STRING(30) },
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
timestamps: false,
|
timestamps: false,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
module.exports = EntryId;
|
module.exports = EntryId;
|
||||||
@@ -1,31 +1,32 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const EntryNetwork = sequelize.define('entryNetwork',
|
const EntryNetwork = sequelize.define(
|
||||||
|
"entryNetwork",
|
||||||
{
|
{
|
||||||
network_id: {
|
network_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
references: {
|
references: {
|
||||||
model: 'Networks',
|
model: "Networks",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
order: {
|
order: {
|
||||||
type: DataTypes.INTEGER
|
type: DataTypes.INTEGER,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
primaryKey: ['network_id', 'entry_id'],
|
primaryKey: ["network_id", "entry_id"],
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
module.exports = EntryNetwork;
|
module.exports = EntryNetwork;
|
||||||
@@ -1,24 +1,25 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
|
const EntryRating = sequelize.define(
|
||||||
const EntryRating = sequelize.define("entryRating",
|
"entryRating",
|
||||||
{
|
{
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
user_rating: { type: DataTypes.FLOAT },
|
user_rating: { type: DataTypes.FLOAT },
|
||||||
tmdb_rating: { type: DataTypes.FLOAT },
|
tmdb_rating: { type: DataTypes.FLOAT },
|
||||||
imdb_rating: { type: DataTypes.FLOAT },
|
imdb_rating: { type: DataTypes.FLOAT },
|
||||||
rotten_tomatoes_rating: { type: DataTypes.FLOAT },
|
rotten_tomatoes_rating: { type: DataTypes.FLOAT },
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
timestamps: false,
|
timestamps: false,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
module.exports = EntryRating;
|
module.exports = EntryRating;
|
||||||
+12
-12
@@ -1,29 +1,29 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
|
const EntrySeen = sequelize.define(
|
||||||
const EntrySeen = sequelize.define("entrySeen",
|
"entrySeen",
|
||||||
{
|
{
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
date_seen: { type: DataTypes.DATE },
|
date_seen: { type: DataTypes.DATE },
|
||||||
seen_with: { type: DataTypes.STRING(50) },
|
seen_with: { type: DataTypes.STRING(50) },
|
||||||
accuracy: {
|
accuracy: {
|
||||||
type: DataTypes.ENUM('EXACT', 'ESTIMATED', 'UNKNOWN'),
|
type: DataTypes.ENUM("EXACT", "ESTIMATED", "UNKNOWN"),
|
||||||
defaultValue: 'EXACT',
|
defaultValue: "EXACT",
|
||||||
},
|
},
|
||||||
|
},
|
||||||
}, {
|
{
|
||||||
timestamps: false,
|
timestamps: false,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
module.exports = EntrySeen;
|
module.exports = EntrySeen;
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Episode = sequelize.define("episode",
|
const Episode = sequelize.define("episode", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
tmdb_id: { type: DataTypes.STRING(30) },
|
tmdb_id: { type: DataTypes.STRING(30) },
|
||||||
@@ -12,9 +11,9 @@ const Episode = sequelize.define("episode",
|
|||||||
season_id: {
|
season_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Seasons',
|
model: "Seasons",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
name: { type: DataTypes.STRING(500) },
|
name: { type: DataTypes.STRING(500) },
|
||||||
@@ -30,9 +29,7 @@ const Episode = sequelize.define("episode",
|
|||||||
still_path: { type: DataTypes.STRING(200) },
|
still_path: { type: DataTypes.STRING(200) },
|
||||||
|
|
||||||
date_first_seen: { type: DataTypes.DATEONLY },
|
date_first_seen: { type: DataTypes.DATEONLY },
|
||||||
date_last_seen: { type: DataTypes.DATEONLY }
|
date_last_seen: { type: DataTypes.DATEONLY },
|
||||||
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = Episode;
|
module.exports = Episode;
|
||||||
@@ -1,34 +1,30 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
|
const EpisodeSeen = sequelize.define("episodeSeen", {
|
||||||
const EpisodeSeen = sequelize.define("episodeSeen",
|
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
episode_id: {
|
episode_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Episodes',
|
model: "Episodes",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
date_seen: { type: DataTypes.DATE },
|
date_seen: { type: DataTypes.DATE },
|
||||||
seen_with: { type: DataTypes.STRING(50) },
|
seen_with: { type: DataTypes.STRING(50) },
|
||||||
accuracy: {
|
accuracy: {
|
||||||
type: DataTypes.ENUM('EXACT', 'ESTIMATED', 'UNKNOWN'),
|
type: DataTypes.ENUM("EXACT", "ESTIMATED", "UNKNOWN"),
|
||||||
defaultValue: 'EXACT',
|
defaultValue: "EXACT",
|
||||||
},
|
},
|
||||||
|
});
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = EpisodeSeen;
|
module.exports = EpisodeSeen;
|
||||||
@@ -1,15 +1,17 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Franchise = sequelize.define("franchise",
|
const Franchise = sequelize.define(
|
||||||
|
"franchise",
|
||||||
{
|
{
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
title: { type: DataTypes.STRING(50) },
|
title: { type: DataTypes.STRING(50) },
|
||||||
overview: { type: DataTypes.STRING(300) },
|
overview: { type: DataTypes.STRING(300) },
|
||||||
user_rating: { type: DataTypes.FLOAT }
|
user_rating: { type: DataTypes.FLOAT },
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
timestamps: false,
|
timestamps: false,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
module.exports = Franchise;
|
module.exports = Franchise;
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Genre = sequelize.define("genre",
|
const Genre = sequelize.define(
|
||||||
|
"genre",
|
||||||
{
|
{
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true },
|
||||||
|
|
||||||
name: { type: DataTypes.STRING(30) },
|
name: { type: DataTypes.STRING(30) },
|
||||||
}, {
|
},
|
||||||
|
{
|
||||||
timestamps: false,
|
timestamps: false,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
module.exports = Genre;
|
module.exports = Genre;
|
||||||
+21
-11
@@ -1,21 +1,31 @@
|
|||||||
const { DataTypes, Sequelize } = require('sequelize');
|
const { DataTypes, Sequelize } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Media = sequelize.define("media",
|
const Media = sequelize.define("media", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
mediaable: { type: Sequelize.STRING },
|
mediaable: { type: Sequelize.STRING },
|
||||||
mediaableId: { type: Sequelize.INTEGER, field: 'mediaable_id' },
|
mediaableId: { type: Sequelize.INTEGER, field: "mediaable_id" },
|
||||||
|
|
||||||
type: { type: DataTypes.STRING(50) },
|
type: { type: DataTypes.STRING(50) },
|
||||||
path: { type: DataTypes.STRING(200) },
|
path: { type: DataTypes.STRING(200) },
|
||||||
|
|
||||||
isLocal: { type: DataTypes.BOOLEAN, field: 'is_local' },
|
isLocal: { type: DataTypes.BOOLEAN, field: "is_local" },
|
||||||
isSelected: { type: DataTypes.BOOLEAN, field: 'is_selected', defaultValue: false },
|
isSelected: {
|
||||||
isCustom: { type: DataTypes.BOOLEAN, field: 'is_custom', defaultValue: false },
|
type: DataTypes.BOOLEAN,
|
||||||
isFavorit: { type: DataTypes.BOOLEAN, field: 'is_favorit', defaultValue: false },
|
field: "is_selected",
|
||||||
}
|
defaultValue: false,
|
||||||
);
|
},
|
||||||
|
isCustom: {
|
||||||
|
type: DataTypes.BOOLEAN,
|
||||||
|
field: "is_custom",
|
||||||
|
defaultValue: false,
|
||||||
|
},
|
||||||
|
isFavorit: {
|
||||||
|
type: DataTypes.BOOLEAN,
|
||||||
|
field: "is_favorit",
|
||||||
|
defaultValue: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
module.exports = Media;
|
module.exports = Media;
|
||||||
@@ -1,18 +1,16 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Network = sequelize.define("network",
|
const Network = sequelize.define("network", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true },
|
||||||
|
|
||||||
name: { type: DataTypes.STRING(30) },
|
name: { type: DataTypes.STRING(30) },
|
||||||
originCountry: { type: DataTypes.STRING(100), field: 'origin_country' },
|
originCountry: { type: DataTypes.STRING(100), field: "origin_country" },
|
||||||
homepage: { type: DataTypes.STRING(100), field: 'homepage' },
|
homepage: { type: DataTypes.STRING(100), field: "homepage" },
|
||||||
|
|
||||||
logoPath: { type: DataTypes.STRING(200), field: 'logo_path' },
|
logoPath: { type: DataTypes.STRING(200), field: "logo_path" },
|
||||||
posterPath: { type: DataTypes.STRING(200), field: 'poster_path' },
|
posterPath: { type: DataTypes.STRING(200), field: "poster_path" },
|
||||||
backdropPath: { type: DataTypes.STRING(200), field: 'backdrop_path' },
|
backdropPath: { type: DataTypes.STRING(200), field: "backdrop_path" },
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = Network;
|
module.exports = Network;
|
||||||
+13
-12
@@ -1,8 +1,7 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const People = sequelize.define("peoples",
|
const People = sequelize.define("peoples", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
tmdb_id: { type: DataTypes.STRING(100) },
|
tmdb_id: { type: DataTypes.STRING(100) },
|
||||||
@@ -13,23 +12,25 @@ const People = sequelize.define("peoples",
|
|||||||
gender: { type: DataTypes.INTEGER },
|
gender: { type: DataTypes.INTEGER },
|
||||||
|
|
||||||
biography: { type: DataTypes.TEXT },
|
biography: { type: DataTypes.TEXT },
|
||||||
place_of_birth: { type: DataTypes.STRING(100), field: 'place_of_birth' },
|
place_of_birth: { type: DataTypes.STRING(100), field: "place_of_birth" },
|
||||||
|
|
||||||
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
|
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
popularity: { type: DataTypes.FLOAT },
|
popularity: { type: DataTypes.FLOAT },
|
||||||
|
|
||||||
known_for_department: { type: DataTypes.STRING(50), field: 'known_for_department' },
|
known_for_department: {
|
||||||
|
type: DataTypes.STRING(50),
|
||||||
|
field: "known_for_department",
|
||||||
|
},
|
||||||
homepage: { type: DataTypes.STRING(200), allowNull: true },
|
homepage: { type: DataTypes.STRING(200), allowNull: true },
|
||||||
|
|
||||||
imdb_id: { type: DataTypes.STRING(20), field: 'imdb_id' },
|
imdb_id: { type: DataTypes.STRING(20), field: "imdb_id" },
|
||||||
profile_path: { type: DataTypes.STRING(200), field: 'profile_path' },
|
profile_path: { type: DataTypes.STRING(200), field: "profile_path" },
|
||||||
|
|
||||||
last_fetch: { type: DataTypes.DATEONLY, field: 'last_fetch' },
|
last_fetch: { type: DataTypes.DATEONLY, field: "last_fetch" },
|
||||||
profile_update: { type: DataTypes.DATEONLY, field: 'profile_update' },
|
profile_update: { type: DataTypes.DATEONLY, field: "profile_update" },
|
||||||
fully_fetched: { type: DataTypes.BOOLEAN, defaultValue: false },
|
fully_fetched: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
favorite: { type: DataTypes.BOOLEAN, defaultValue: false },
|
favorite: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
pinned: { type: DataTypes.BOOLEAN, defaultValue: false },
|
pinned: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = People;
|
module.exports = People;
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Season = sequelize.define("season",
|
const Season = sequelize.define("season", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
tmdb_id: { type: DataTypes.STRING(30) },
|
tmdb_id: { type: DataTypes.STRING(30) },
|
||||||
@@ -11,9 +10,9 @@ const Season = sequelize.define("season",
|
|||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
name: { type: DataTypes.STRING(500) },
|
name: { type: DataTypes.STRING(500) },
|
||||||
@@ -28,7 +27,6 @@ const Season = sequelize.define("season",
|
|||||||
|
|
||||||
poster_path: { type: DataTypes.STRING(200) },
|
poster_path: { type: DataTypes.STRING(200) },
|
||||||
banner_path: { type: DataTypes.STRING(200) },
|
banner_path: { type: DataTypes.STRING(200) },
|
||||||
}
|
});
|
||||||
);
|
|
||||||
|
|
||||||
module.exports = Season;
|
module.exports = Season;
|
||||||
@@ -1,30 +1,32 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const UserCollectionEntry = sequelize.define('userCollectionEntry',
|
const UserCollectionEntry = sequelize.define(
|
||||||
|
"userCollectionEntry",
|
||||||
{
|
{
|
||||||
user_collection_id: {
|
user_collection_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
references: {
|
references: {
|
||||||
model: 'UserCollections',
|
model: "UserCollections",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
entry_id: {
|
entry_id: {
|
||||||
type: DataTypes.INTEGER,
|
type: DataTypes.INTEGER,
|
||||||
primaryKey: true,
|
primaryKey: true,
|
||||||
references: {
|
references: {
|
||||||
model: 'Entries',
|
model: "Entries",
|
||||||
key: 'id'
|
key: "id",
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
order: {
|
order: {
|
||||||
type: DataTypes.INTEGER
|
type: DataTypes.INTEGER,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
primaryKey: ['user_collection_id', 'entry_id'],
|
primaryKey: ["user_collection_id", "entry_id"],
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = UserCollectionEntry;
|
module.exports = UserCollectionEntry;
|
||||||
@@ -1,42 +1,51 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const aiQueryRouter = express.Router();
|
const aiQueryRouter = express.Router();
|
||||||
|
|
||||||
const aiQueryController = require('../controllers/aiQueryController');
|
const aiQueryController = require("../controllers/aiQueryController");
|
||||||
|
|
||||||
// ! /ai-query
|
// ! /ai-query
|
||||||
|
|
||||||
// * Watch history
|
// * Watch history
|
||||||
aiQueryRouter.get('/recently-watched/movies', aiQueryController.getRecentlyWatchedMovies);
|
aiQueryRouter.get(
|
||||||
aiQueryRouter.get('/recently-watched/episodes', aiQueryController.getRecentlyWatchedEpisodes);
|
"/recently-watched/movies",
|
||||||
|
aiQueryController.getRecentlyWatchedMovies,
|
||||||
|
);
|
||||||
|
aiQueryRouter.get(
|
||||||
|
"/recently-watched/episodes",
|
||||||
|
aiQueryController.getRecentlyWatchedEpisodes,
|
||||||
|
);
|
||||||
|
|
||||||
// * Library lists
|
// * Library lists
|
||||||
aiQueryRouter.get('/watchlist', aiQueryController.getWatchlist);
|
aiQueryRouter.get("/watchlist", aiQueryController.getWatchlist);
|
||||||
aiQueryRouter.get('/favorites', aiQueryController.getFavorites);
|
aiQueryRouter.get("/favorites", aiQueryController.getFavorites);
|
||||||
|
|
||||||
// * Library overview & search
|
// * Library overview & search
|
||||||
aiQueryRouter.get('/library/overview', aiQueryController.getLibraryOverview);
|
aiQueryRouter.get("/library/overview", aiQueryController.getLibraryOverview);
|
||||||
aiQueryRouter.get('/library/search', aiQueryController.searchLibrary);
|
aiQueryRouter.get("/library/search", aiQueryController.searchLibrary);
|
||||||
|
|
||||||
// * Upcoming
|
// * Upcoming
|
||||||
aiQueryRouter.get('/upcoming', aiQueryController.getUpcoming);
|
aiQueryRouter.get("/upcoming", aiQueryController.getUpcoming);
|
||||||
|
|
||||||
// * Entry detail
|
// * Entry detail
|
||||||
aiQueryRouter.get('/entry/:id', aiQueryController.getEntryDetail);
|
aiQueryRouter.get("/entry/:id", aiQueryController.getEntryDetail);
|
||||||
|
|
||||||
// * Genres
|
// * Genres
|
||||||
aiQueryRouter.get('/genres/breakdown', aiQueryController.getGenreBreakdown);
|
aiQueryRouter.get("/genres/breakdown", aiQueryController.getGenreBreakdown);
|
||||||
|
|
||||||
// * Collections
|
// * Collections
|
||||||
aiQueryRouter.get('/collections', aiQueryController.getAllCollections);
|
aiQueryRouter.get("/collections", aiQueryController.getAllCollections);
|
||||||
aiQueryRouter.get('/collections/:id', aiQueryController.getCollectionDetail);
|
aiQueryRouter.get("/collections/:id", aiQueryController.getCollectionDetail);
|
||||||
|
|
||||||
// * TV series
|
// * TV series
|
||||||
aiQueryRouter.get('/tv-series/in-progress', aiQueryController.getInProgressSeries);
|
aiQueryRouter.get(
|
||||||
|
"/tv-series/in-progress",
|
||||||
|
aiQueryController.getInProgressSeries,
|
||||||
|
);
|
||||||
|
|
||||||
// * Stats
|
// * Stats
|
||||||
aiQueryRouter.get('/stats/watching-time', aiQueryController.getWatchTimeStats);
|
aiQueryRouter.get("/stats/watching-time", aiQueryController.getWatchTimeStats);
|
||||||
|
|
||||||
// * People
|
// * People
|
||||||
aiQueryRouter.get('/person/:id', aiQueryController.getPersonDetail);
|
aiQueryRouter.get("/person/:id", aiQueryController.getPersonDetail);
|
||||||
|
|
||||||
module.exports = aiQueryRouter;
|
module.exports = aiQueryRouter;
|
||||||
@@ -1,45 +1,59 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const collectionRouter = express.Router();
|
const collectionRouter = express.Router();
|
||||||
|
|
||||||
const collectionController = require('../controllers/collectionController');
|
const collectionController = require("../controllers/collectionController");
|
||||||
const { collectionPicturesUpload } = require('../services/mutlerStorageLocations');
|
const {
|
||||||
|
collectionPicturesUpload,
|
||||||
|
} = require("../services/mutlerStorageLocations");
|
||||||
|
|
||||||
// ! /collections
|
// ! /collections
|
||||||
// * GET - ALL COLLECTIONS
|
// * GET - ALL COLLECTIONS
|
||||||
collectionRouter.get('/', collectionController.getCollections);
|
collectionRouter.get("/", collectionController.getCollections);
|
||||||
|
|
||||||
// * GET - COLLECTION BY ID
|
// * GET - COLLECTION BY ID
|
||||||
collectionRouter.get('/:id', collectionController.getCollectionById);
|
collectionRouter.get("/:id", collectionController.getCollectionById);
|
||||||
|
|
||||||
// * POST - CREATE COLLECTION
|
// * POST - CREATE COLLECTION
|
||||||
collectionRouter.post('/', collectionController.createCollection);
|
collectionRouter.post("/", collectionController.createCollection);
|
||||||
|
|
||||||
// * PUT - UPDATE COLLECTION
|
// * PUT - UPDATE COLLECTION
|
||||||
const upload = collectionPicturesUpload.fields([
|
const upload = collectionPicturesUpload.fields([
|
||||||
{ name: 'poster', maxCount: 1 },
|
{ name: "poster", maxCount: 1 },
|
||||||
{ name: 'backdrop', maxCount: 1 }
|
{ name: "backdrop", maxCount: 1 },
|
||||||
]);
|
]);
|
||||||
collectionRouter.put('/:id', upload, collectionController.updateCollection);
|
collectionRouter.put("/:id", upload, collectionController.updateCollection);
|
||||||
|
|
||||||
// * PUT - REFRESH COLLECTION
|
// * PUT - REFRESH COLLECTION
|
||||||
collectionRouter.put('/:id/refresh', collectionController.refrechCollection);
|
collectionRouter.put("/:id/refresh", collectionController.refrechCollection);
|
||||||
|
|
||||||
// * PUT - GET COLLECTION PARTS
|
// * PUT - GET COLLECTION PARTS
|
||||||
collectionRouter.put('/:id/parts', collectionController.getCollectionParts);
|
collectionRouter.put("/:id/parts", collectionController.getCollectionParts);
|
||||||
|
|
||||||
// * DELETE - DELETE COLLECTION
|
// * DELETE - DELETE COLLECTION
|
||||||
collectionRouter.delete('/:id', collectionController.deleteCollection);
|
collectionRouter.delete("/:id", collectionController.deleteCollection);
|
||||||
|
|
||||||
// * POST - ADD ENTRY TO A COLLECTION
|
// * POST - ADD ENTRY TO A COLLECTION
|
||||||
collectionRouter.post('/:collectionId/entries/:entryId', collectionController.addEntryToCollection);
|
collectionRouter.post(
|
||||||
|
"/:collectionId/entries/:entryId",
|
||||||
|
collectionController.addEntryToCollection,
|
||||||
|
);
|
||||||
|
|
||||||
// * PATCH - UPDATE ENTRY ORDER IN COLLECTION
|
// * PATCH - UPDATE ENTRY ORDER IN COLLECTION
|
||||||
collectionRouter.patch('/:collectionId/entries/:entryId', collectionController.updateCollectionEntryOrder);
|
collectionRouter.patch(
|
||||||
|
"/:collectionId/entries/:entryId",
|
||||||
|
collectionController.updateCollectionEntryOrder,
|
||||||
|
);
|
||||||
|
|
||||||
// * DELETE - REMOVE AN ENTRY FROM A COLLECTION
|
// * DELETE - REMOVE AN ENTRY FROM A COLLECTION
|
||||||
collectionRouter.delete('/:collectionId/entries/:entryId', collectionController.removeEntryFromCollection);
|
collectionRouter.delete(
|
||||||
|
"/:collectionId/entries/:entryId",
|
||||||
|
collectionController.removeEntryFromCollection,
|
||||||
|
);
|
||||||
|
|
||||||
// * POST - CREATE COLLECTION WITH ENTRY
|
// * POST - CREATE COLLECTION WITH ENTRY
|
||||||
collectionRouter.post('/collection-with-entry', collectionController.createCollectionWithEntry);
|
collectionRouter.post(
|
||||||
|
"/collection-with-entry",
|
||||||
|
collectionController.createCollectionWithEntry,
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = collectionRouter;
|
module.exports = collectionRouter;
|
||||||
@@ -1,25 +1,28 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const entrySeenRouter = express.Router();
|
const entrySeenRouter = express.Router();
|
||||||
|
|
||||||
const entrySeenController = require('../controllers/entrySeenController');
|
const entrySeenController = require("../controllers/entrySeenController");
|
||||||
|
|
||||||
// ! /entry-seen
|
// ! /entry-seen
|
||||||
// * GET - ALL ENTRY SEEN
|
// * GET - ALL ENTRY SEEN
|
||||||
entrySeenRouter.get('/', entrySeenController.getEntrySeens);
|
entrySeenRouter.get("/", entrySeenController.getEntrySeens);
|
||||||
|
|
||||||
// * GET - ENTRY SEEN BY ENTRY ID (must be before /:id to avoid conflict)
|
// * GET - ENTRY SEEN BY ENTRY ID (must be before /:id to avoid conflict)
|
||||||
entrySeenRouter.get('/by-entry/:entryId', entrySeenController.getEntrySeensByEntryId);
|
entrySeenRouter.get(
|
||||||
|
"/by-entry/:entryId",
|
||||||
|
entrySeenController.getEntrySeensByEntryId,
|
||||||
|
);
|
||||||
|
|
||||||
// * GET - ENTRY SEEN BY ID
|
// * GET - ENTRY SEEN BY ID
|
||||||
entrySeenRouter.get('/:id', entrySeenController.getEntrySeenById);
|
entrySeenRouter.get("/:id", entrySeenController.getEntrySeenById);
|
||||||
|
|
||||||
// * POST - CREATE ENTRY SEEN
|
// * POST - CREATE ENTRY SEEN
|
||||||
entrySeenRouter.post('/', entrySeenController.createEntrySeen);
|
entrySeenRouter.post("/", entrySeenController.createEntrySeen);
|
||||||
|
|
||||||
// * PUT - UPDATE ENTRY SEEN
|
// * PUT - UPDATE ENTRY SEEN
|
||||||
entrySeenRouter.put('/:id', entrySeenController.updateEntrySeen);
|
entrySeenRouter.put("/:id", entrySeenController.updateEntrySeen);
|
||||||
|
|
||||||
// * DELETE - ENTRY SEEN
|
// * DELETE - ENTRY SEEN
|
||||||
entrySeenRouter.delete('/:id', entrySeenController.deleteEntrySeen);
|
entrySeenRouter.delete("/:id", entrySeenController.deleteEntrySeen);
|
||||||
|
|
||||||
module.exports = entrySeenRouter;
|
module.exports = entrySeenRouter;
|
||||||
@@ -1,104 +1,108 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const entryRouter = express.Router();
|
const entryRouter = express.Router();
|
||||||
|
|
||||||
const { entryPicturesUpload } = require('../services/mutlerStorageLocations');
|
const { entryPicturesUpload } = require("../services/mutlerStorageLocations");
|
||||||
const Entry = require('../models/Entry');
|
const Entry = require("../models/Entry");
|
||||||
const Media = require('../models/Media');
|
const Media = require("../models/Media");
|
||||||
const { logToFile } = require('../services/logService');
|
const { logToFile } = require("../services/logService");
|
||||||
|
|
||||||
const entryController = require('../controllers/entryController');
|
const entryController = require("../controllers/entryController");
|
||||||
const mediaOptimizerService = require('../services/mediaOptimizerService');
|
const mediaOptimizerService = require("../services/mediaOptimizerService");
|
||||||
|
|
||||||
// ! /entries
|
// ! /entries
|
||||||
|
|
||||||
// ! TMDB PROXY ROUTES (must be before /:id to avoid matching)
|
// ! TMDB PROXY ROUTES (must be before /:id to avoid matching)
|
||||||
entryRouter.get('/tmdb/trending/:type', entryController.getTmdbTrending);
|
entryRouter.get("/tmdb/trending/:type", entryController.getTmdbTrending);
|
||||||
entryRouter.get('/tmdb/popular/:type', entryController.getTmdbPopular);
|
entryRouter.get("/tmdb/popular/:type", entryController.getTmdbPopular);
|
||||||
entryRouter.get('/tmdb/top-rated/:type', entryController.getTmdbTopRated);
|
entryRouter.get("/tmdb/top-rated/:type", entryController.getTmdbTopRated);
|
||||||
entryRouter.get('/tmdb/upcoming/movie', entryController.getTmdbUpcoming);
|
entryRouter.get("/tmdb/upcoming/movie", entryController.getTmdbUpcoming);
|
||||||
entryRouter.get('/tmdb/search', entryController.getTmdbSearch);
|
entryRouter.get("/tmdb/search", entryController.getTmdbSearch);
|
||||||
entryRouter.get('/tmdb/preview/:type/:tmdbId', entryController.getTmdbPreview);
|
entryRouter.get("/tmdb/preview/:type/:tmdbId", entryController.getTmdbPreview);
|
||||||
|
|
||||||
entryRouter.get('/sync-series', entryController.syncSeries);
|
entryRouter.get("/sync-series", entryController.syncSeries);
|
||||||
|
|
||||||
entryRouter.get('/', entryController.getAllEntries);
|
entryRouter.get("/", entryController.getAllEntries);
|
||||||
entryRouter.get('/:id', entryController.getEntryById);
|
entryRouter.get("/:id", entryController.getEntryById);
|
||||||
entryRouter.post('/', entryController.fetchAndSaveNewEntry);
|
entryRouter.post("/", entryController.fetchAndSaveNewEntry);
|
||||||
entryRouter.put('/:id', entryController.updateEntry);
|
entryRouter.put("/:id", entryController.updateEntry);
|
||||||
entryRouter.put('/:id/ratings', entryController.updateEntryRatings);
|
entryRouter.put("/:id/ratings", entryController.updateEntryRatings);
|
||||||
entryRouter.put('/:id/ids', entryController.updateEntryIds);
|
entryRouter.put("/:id/ids", entryController.updateEntryIds);
|
||||||
entryRouter.delete('/:id', entryController.deleteEntry);
|
entryRouter.delete("/:id", entryController.deleteEntry);
|
||||||
|
|
||||||
entryRouter.get('/:id/seasons', entryController.getEntrySeasons);
|
entryRouter.get("/:id/seasons", entryController.getEntrySeasons);
|
||||||
entryRouter.get('/:id/credits', entryController.getEntryCredits);
|
entryRouter.get("/:id/credits", entryController.getEntryCredits);
|
||||||
entryRouter.put('/:id/refresh', entryController.refrechEntry);
|
entryRouter.put("/:id/refresh", entryController.refrechEntry);
|
||||||
entryRouter.put('/:id/fetch-collection', entryController.fetchEntryCollection);
|
entryRouter.put("/:id/fetch-collection", entryController.fetchEntryCollection);
|
||||||
|
|
||||||
// ! ENTRY MEDIA
|
// ! ENTRY MEDIA
|
||||||
// * POST - ADD NEW ENTRY MEDIA (poster/backdrop/logo)
|
// * POST - ADD NEW ENTRY MEDIA (poster/backdrop/logo)
|
||||||
const upload = entryPicturesUpload.fields([
|
const upload = entryPicturesUpload.fields([
|
||||||
{ name: 'poster', maxCount: 1 },
|
{ name: "poster", maxCount: 1 },
|
||||||
{ name: 'backdrop', maxCount: 1 },
|
{ name: "backdrop", maxCount: 1 },
|
||||||
{ name: 'logo', maxCount: 1 }
|
{ name: "logo", maxCount: 1 },
|
||||||
]);
|
]);
|
||||||
entryRouter.post('/:id/media', upload, async (req, res) => {
|
entryRouter.post("/:id/media", upload, async (req, res) => {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
|
||||||
if (!req.files) {
|
if (!req.files) {
|
||||||
return res.status(400).json({ message: 'No files uploaded' });
|
return res.status(400).json({ message: "No files uploaded" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const entry = await Entry.findByPk(id);
|
const entry = await Entry.findByPk(id);
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
return res.status(404).json({ message: 'Entry not found' });
|
return res.status(404).json({ message: "Entry not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to handle media creation based on uploaded file type
|
// Function to handle media creation based on uploaded file type
|
||||||
const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]);
|
const fileType = ["poster", "backdrop", "logo"].find(
|
||||||
|
(type) => req.files[type],
|
||||||
|
);
|
||||||
if (!fileType) {
|
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 file = req.files[fileType][0];
|
||||||
const createdMedia = await Media.create({
|
const createdMedia = await Media.create({
|
||||||
mediaable: 'entry',
|
mediaable: "entry",
|
||||||
mediaableId: id,
|
mediaableId: id,
|
||||||
type: fileType,
|
type: fileType,
|
||||||
path: file.filename,
|
path: file.filename,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: false,
|
isSelected: false,
|
||||||
isCustom: true
|
isCustom: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? generating low resolution preview
|
// ? generating low resolution preview
|
||||||
mediaOptimizerService.doGeneratePreview('entries', fileType + 's', file.filename).then((result) => {
|
mediaOptimizerService
|
||||||
|
.doGeneratePreview("entries", fileType + "s", file.filename)
|
||||||
|
.then((result) => {
|
||||||
const stream = fs.createReadStream(filePath);
|
const stream = fs.createReadStream(filePath);
|
||||||
stream.pipe(res);
|
stream.pipe(res);
|
||||||
|
|
||||||
const msg = `Media Route | Generated Entry Preview`
|
const msg = `Media Route | Generated Entry Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
}).catch((err) => {
|
})
|
||||||
const msg = `Media Route | Error Generating Entry Preview`
|
.catch((err) => {
|
||||||
|
const msg = `Media Route | Error Generating Entry Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
});
|
});
|
||||||
|
|
||||||
return res.status(200).json(createdMedia);
|
return res.status(200).json(createdMedia);
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// * PUT - SET ENTRY MEDIA AS SELECTED
|
// * PUT - SET ENTRY MEDIA AS SELECTED
|
||||||
entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => {
|
entryRouter.put("/:entryId/media/:mediaId", upload, async (req, res) => {
|
||||||
const entryId = req.params.entryId;
|
const entryId = req.params.entryId;
|
||||||
const mediaId = req.params.mediaId;
|
const mediaId = req.params.mediaId;
|
||||||
|
|
||||||
const entry = await Entry.findByPk(entryId);
|
const entry = await Entry.findByPk(entryId);
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
return res.status(404).json({ message: 'Entry not found' });
|
return res.status(404).json({ message: "Entry not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const media = await Media.findByPk(mediaId);
|
const media = await Media.findByPk(mediaId);
|
||||||
if (!media) {
|
if (!media) {
|
||||||
return res.status(404).json({ message: 'Media not found' });
|
return res.status(404).json({ message: "Media not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? setting all other media to not selected
|
// ? setting all other media to not selected
|
||||||
@@ -107,11 +111,11 @@ entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => {
|
|||||||
{ isSelected: false },
|
{ isSelected: false },
|
||||||
{
|
{
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'entry',
|
mediaable: "entry",
|
||||||
mediaableId: entryId,
|
mediaableId: entryId,
|
||||||
type: media.type
|
type: media.type,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const updatedMedia = await media.update({ isSelected: true });
|
const updatedMedia = await media.update({ isSelected: true });
|
||||||
@@ -119,7 +123,7 @@ entryRouter.put('/:entryId/media/:mediaId', upload, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// * DELETE - DELETE AND ENTRY MEDIA
|
// * DELETE - DELETE AND ENTRY MEDIA
|
||||||
entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => {
|
entryRouter.delete("/:entryId/media/:mediaId", async (req, res) => {
|
||||||
const mediaId = req.params.mediaId;
|
const mediaId = req.params.mediaId;
|
||||||
|
|
||||||
// ? just before deleting we need to check if the deleted media was the one selected
|
// ? just before deleting we need to check if the deleted media was the one selected
|
||||||
@@ -128,11 +132,11 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => {
|
|||||||
if (media && media.isSelected) {
|
if (media && media.isSelected) {
|
||||||
let otherMedia = await Media.findOne({
|
let otherMedia = await Media.findOne({
|
||||||
where: {
|
where: {
|
||||||
mediaable: 'entry',
|
mediaable: "entry",
|
||||||
mediaableId: media.mediaableId,
|
mediaableId: media.mediaableId,
|
||||||
type: media.type,
|
type: media.type,
|
||||||
isSelected: false
|
isSelected: false,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? if found select the first one
|
// ? if found select the first one
|
||||||
@@ -141,10 +145,9 @@ entryRouter.delete('/:entryId/media/:mediaId', async (req, res) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await Media.destroy({ where: { id: mediaId } })
|
await Media.destroy({ where: { id: mediaId } });
|
||||||
|
|
||||||
res.status(200).json();
|
res.status(200).json();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
module.exports = entryRouter;
|
module.exports = entryRouter;
|
||||||
@@ -1,28 +1,34 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const episodeSeenRouter = express.Router();
|
const episodeSeenRouter = express.Router();
|
||||||
|
|
||||||
const episodeSeenController = require('../controllers/episodeSeenController');
|
const episodeSeenController = require("../controllers/episodeSeenController");
|
||||||
|
|
||||||
// ! /episode-seen
|
// ! /episode-seen
|
||||||
// * POST - CREATE ENTRY SEEN
|
// * POST - CREATE ENTRY SEEN
|
||||||
episodeSeenRouter.post('/', episodeSeenController.createEpisodeSeen);
|
episodeSeenRouter.post("/", episodeSeenController.createEpisodeSeen);
|
||||||
|
|
||||||
// * GET - ALL EPISODE SEEN
|
// * GET - ALL EPISODE SEEN
|
||||||
episodeSeenRouter.get('/', episodeSeenController.getEpisodesSeen);
|
episodeSeenRouter.get("/", episodeSeenController.getEpisodesSeen);
|
||||||
|
|
||||||
// * GET - EPISODE SEEN BY EPISODE ID (must come before /:id)
|
// * GET - EPISODE SEEN BY EPISODE ID (must come before /:id)
|
||||||
episodeSeenRouter.get('/by-episode/:episodeId', episodeSeenController.getEpisodeSeensByEpisodeId);
|
episodeSeenRouter.get(
|
||||||
|
"/by-episode/:episodeId",
|
||||||
|
episodeSeenController.getEpisodeSeensByEpisodeId,
|
||||||
|
);
|
||||||
|
|
||||||
// * GET - EPISODE SEEN BY ENTRY ID (must come before /:id)
|
// * GET - EPISODE SEEN BY ENTRY ID (must come before /:id)
|
||||||
episodeSeenRouter.get('/by-entry/:entryId', episodeSeenController.getEpisodeSeensByEntryId);
|
episodeSeenRouter.get(
|
||||||
|
"/by-entry/:entryId",
|
||||||
|
episodeSeenController.getEpisodeSeensByEntryId,
|
||||||
|
);
|
||||||
|
|
||||||
// * GET - EPISODE SEEN BY ID
|
// * GET - EPISODE SEEN BY ID
|
||||||
episodeSeenRouter.get('/:id', episodeSeenController.getEpisodeSeenById);
|
episodeSeenRouter.get("/:id", episodeSeenController.getEpisodeSeenById);
|
||||||
|
|
||||||
// * PUT - UPDATE EPISODE SEEN
|
// * PUT - UPDATE EPISODE SEEN
|
||||||
episodeSeenRouter.put('/:id', episodeSeenController.updateEpisodeSeen);
|
episodeSeenRouter.put("/:id", episodeSeenController.updateEpisodeSeen);
|
||||||
|
|
||||||
// * DELETE - EPISODE SEEN
|
// * DELETE - EPISODE SEEN
|
||||||
episodeSeenRouter.delete('/:id', episodeSeenController.deleteEpisodeSeen);
|
episodeSeenRouter.delete("/:id", episodeSeenController.deleteEpisodeSeen);
|
||||||
|
|
||||||
module.exports = episodeSeenRouter;
|
module.exports = episodeSeenRouter;
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const episodeController = require('../controllers/episodeController');
|
const episodeController = require("../controllers/episodeController");
|
||||||
const episodeRouter = express.Router();
|
const episodeRouter = express.Router();
|
||||||
|
|
||||||
// ! /episodes
|
// ! /episodes
|
||||||
episodeRouter.get('/month/:startDate/:endDate', episodeController.getEpisodesBetweenDates);
|
episodeRouter.get(
|
||||||
|
"/month/:startDate/:endDate",
|
||||||
|
episodeController.getEpisodesBetweenDates,
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = episodeRouter;
|
module.exports = episodeRouter;
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const importRouter = express.Router();
|
const importRouter = express.Router();
|
||||||
|
|
||||||
const importController = require('../controllers/importController');
|
const importController = require("../controllers/importController");
|
||||||
|
|
||||||
// ! /import
|
// ! /import
|
||||||
importRouter.post('/movies', importController.importMovies);
|
importRouter.post("/movies", importController.importMovies);
|
||||||
importRouter.post('/tmdb', importController.importTMBD);
|
importRouter.post("/tmdb", importController.importTMBD);
|
||||||
importRouter.post('/episodes-watch-history', importController.importEpisodeWatchHistory);
|
importRouter.post(
|
||||||
|
"/episodes-watch-history",
|
||||||
|
importController.importEpisodeWatchHistory,
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = importRouter;
|
module.exports = importRouter;
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const killerController = require('../controllers/killerController');
|
const killerController = require("../controllers/killerController");
|
||||||
const killerRouter = express.Router();
|
const killerRouter = express.Router();
|
||||||
|
|
||||||
// ! /killer
|
// ! /killer
|
||||||
// * POST
|
// * POST
|
||||||
killerRouter.post('/', killerController.killBackend);
|
killerRouter.post("/", killerController.killBackend);
|
||||||
// * GET
|
// * GET
|
||||||
killerRouter.get('/', killerController.killBackend);
|
killerRouter.get("/", killerController.killBackend);
|
||||||
|
|
||||||
module.exports = killerRouter;
|
module.exports = killerRouter;
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const mediaRouter = express.Router();
|
const mediaRouter = express.Router();
|
||||||
|
|
||||||
const mediaController = require('../controllers/mediaController.js');
|
const mediaController = require("../controllers/mediaController.js");
|
||||||
|
|
||||||
// ! /media
|
// ! /media
|
||||||
mediaRouter.get('/', mediaController.getMedias);
|
mediaRouter.get("/", mediaController.getMedias);
|
||||||
|
|
||||||
// ? Routes : media access routes
|
// ? Routes : media access routes
|
||||||
mediaRouter.get('/:category/:type/:size/:fileName', mediaController.getMedia);
|
mediaRouter.get("/:category/:type/:size/:fileName", mediaController.getMedia);
|
||||||
|
|
||||||
module.exports = mediaRouter;
|
module.exports = mediaRouter;
|
||||||
@@ -1,56 +1,60 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const peopleRouter = express.Router();
|
const peopleRouter = express.Router();
|
||||||
const { peoplePicturesUpload } = require('../services/mutlerStorageLocations');
|
const { peoplePicturesUpload } = require("../services/mutlerStorageLocations");
|
||||||
const mediaOptimizerService = require('../services/mediaOptimizerService');
|
const mediaOptimizerService = require("../services/mediaOptimizerService");
|
||||||
const peopleController = require('../controllers/peopleController');
|
const peopleController = require("../controllers/peopleController");
|
||||||
|
|
||||||
// ! /people
|
// ! /people
|
||||||
|
|
||||||
// ! TMDB PROXY ROUTES (must be before /:id to avoid matching)
|
// ! TMDB PROXY ROUTES (must be before /:id to avoid matching)
|
||||||
peopleRouter.get('/tmdb/popular', peopleController.getTmdbPopularPeople);
|
peopleRouter.get("/tmdb/popular", peopleController.getTmdbPopularPeople);
|
||||||
peopleRouter.get('/tmdb/search', peopleController.searchTmdbPeople);
|
peopleRouter.get("/tmdb/search", peopleController.searchTmdbPeople);
|
||||||
peopleRouter.get('/tmdb/preview/:tmdbId', peopleController.getTmdbPersonPreview);
|
peopleRouter.get(
|
||||||
|
"/tmdb/preview/:tmdbId",
|
||||||
|
peopleController.getTmdbPersonPreview,
|
||||||
|
);
|
||||||
|
|
||||||
// Get all people
|
// Get all people
|
||||||
peopleRouter.get('/', peopleController.getAllPeople);
|
peopleRouter.get("/", peopleController.getAllPeople);
|
||||||
|
|
||||||
// Get popular people
|
// Get popular people
|
||||||
peopleRouter.get('/popular', peopleController.getPopularPeople);
|
peopleRouter.get("/popular", peopleController.getPopularPeople);
|
||||||
|
|
||||||
// Search people
|
// Search people
|
||||||
peopleRouter.get('/search', peopleController.searchPeople);
|
peopleRouter.get("/search", peopleController.searchPeople);
|
||||||
|
|
||||||
// Get person by ID
|
// Get person by ID
|
||||||
peopleRouter.get('/:id', peopleController.getPersonById);
|
peopleRouter.get("/:id", peopleController.getPersonById);
|
||||||
|
|
||||||
// Get person credits (from DB)
|
// Get person credits (from DB)
|
||||||
peopleRouter.get('/:id/credits', peopleController.getPersonCredits);
|
peopleRouter.get("/:id/credits", peopleController.getPersonCredits);
|
||||||
|
|
||||||
// Get person TMDB filmography (all TMDB credits including non-library entries)
|
// Get person TMDB filmography (all TMDB credits including non-library entries)
|
||||||
peopleRouter.get('/:id/tmdb-filmography', peopleController.getPersonTmdbFilmography);
|
peopleRouter.get(
|
||||||
|
"/:id/tmdb-filmography",
|
||||||
|
peopleController.getPersonTmdbFilmography,
|
||||||
|
);
|
||||||
|
|
||||||
// Create a new person
|
// Create a new person
|
||||||
peopleRouter.post('/', peopleController.createPerson);
|
peopleRouter.post("/", peopleController.createPerson);
|
||||||
|
|
||||||
// Fetch and save person from TMDB
|
// Fetch and save person from TMDB
|
||||||
peopleRouter.post('/fetch', peopleController.fetchAndSavePersonByTmdbId);
|
peopleRouter.post("/fetch", peopleController.fetchAndSavePersonByTmdbId);
|
||||||
|
|
||||||
// Update a person
|
// Update a person
|
||||||
peopleRouter.put('/:id', peopleController.updatePerson);
|
peopleRouter.put("/:id", peopleController.updatePerson);
|
||||||
|
|
||||||
// Refresh person data from TMDB
|
// Refresh person data from TMDB
|
||||||
peopleRouter.put('/:id/refresh', peopleController.refreshPerson);
|
peopleRouter.put("/:id/refresh", peopleController.refreshPerson);
|
||||||
|
|
||||||
// Delete a person
|
// Delete a person
|
||||||
peopleRouter.delete('/:id', peopleController.deletePerson);
|
peopleRouter.delete("/:id", peopleController.deletePerson);
|
||||||
|
|
||||||
// Person media upload handler
|
// Person media upload handler
|
||||||
const upload = peoplePicturesUpload.fields([
|
const upload = peoplePicturesUpload.fields([{ name: "profile", maxCount: 1 }]);
|
||||||
{ name: 'profile', maxCount: 1 }
|
|
||||||
]);
|
|
||||||
|
|
||||||
// Upload person profile picture
|
// Upload person profile picture
|
||||||
peopleRouter.post('/:id/media', upload, async (req, res) => {
|
peopleRouter.post("/:id/media", upload, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const personId = req.params.id;
|
const personId = req.params.id;
|
||||||
let result = { success: true, files: [] };
|
let result = { success: true, files: [] };
|
||||||
@@ -62,12 +66,16 @@ peopleRouter.post('/:id/media', upload, async (req, res) => {
|
|||||||
const fileName = profileFile.filename;
|
const fileName = profileFile.filename;
|
||||||
|
|
||||||
// Generate preview for profile picture
|
// Generate preview for profile picture
|
||||||
const previewPath = await mediaOptimizerService.doGeneratePreview('people', 'profiles', fileName);
|
const previewPath = await mediaOptimizerService.doGeneratePreview(
|
||||||
|
"people",
|
||||||
|
"profiles",
|
||||||
|
fileName,
|
||||||
|
);
|
||||||
|
|
||||||
result.files.push({
|
result.files.push({
|
||||||
type: 'profile',
|
type: "profile",
|
||||||
original: fileName,
|
original: fileName,
|
||||||
preview: previewPath ? path.basename(previewPath) : null
|
preview: previewPath ? path.basename(previewPath) : null,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const PingController = require('../controllers/PingController');
|
const PingController = require("../controllers/PingController");
|
||||||
const pingRouter = express.Router();
|
const pingRouter = express.Router();
|
||||||
|
|
||||||
// ! /ping
|
// ! /ping
|
||||||
pingRouter.get('/', PingController.ping);
|
pingRouter.get("/", PingController.ping);
|
||||||
|
|
||||||
module.exports = pingRouter;
|
module.exports = pingRouter;
|
||||||
+29
-30
@@ -1,36 +1,35 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const collectionRouter = require('./collection.routes');
|
const collectionRouter = require("./collection.routes");
|
||||||
const entrySeenRouter = require('./entry-seen.routes');
|
const entrySeenRouter = require("./entry-seen.routes");
|
||||||
const entryRouter = require('./entry.routes');
|
const entryRouter = require("./entry.routes");
|
||||||
const seasonRouter = require('./season.routes');
|
const seasonRouter = require("./season.routes");
|
||||||
const episodeSeenRouter = require('./episode-seen.routes');
|
const episodeSeenRouter = require("./episode-seen.routes");
|
||||||
const settingsRouter = require('./settings.routes');
|
const settingsRouter = require("./settings.routes");
|
||||||
const maintenanceRouter = require('./maintenance.routes');
|
const maintenanceRouter = require("./maintenance.routes");
|
||||||
const statisticsRouter = require('./statistics.routes');
|
const statisticsRouter = require("./statistics.routes");
|
||||||
const mediaRouter = require('./media.routes');
|
const mediaRouter = require("./media.routes");
|
||||||
const episodeRouter = require('./episode.routes');
|
const episodeRouter = require("./episode.routes");
|
||||||
const pingRouter = require('./ping.routes');
|
const pingRouter = require("./ping.routes");
|
||||||
const importRouter = require('./import.routes');
|
const importRouter = require("./import.routes");
|
||||||
const peopleRouter = require('./people.routes');
|
const peopleRouter = require("./people.routes");
|
||||||
const aiQueryRouter = require('./ai-query.routes');
|
const aiQueryRouter = require("./ai-query.routes");
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
router.use('/media', mediaRouter);
|
router.use("/media", mediaRouter);
|
||||||
router.use('/entries', entryRouter);
|
router.use("/entries", entryRouter);
|
||||||
router.use('/collections', collectionRouter);
|
router.use("/collections", collectionRouter);
|
||||||
router.use('/entry-seen', entrySeenRouter);
|
router.use("/entry-seen", entrySeenRouter);
|
||||||
|
|
||||||
router.use('/seasons', seasonRouter);
|
router.use("/seasons", seasonRouter);
|
||||||
router.use('/episodes', episodeRouter);
|
router.use("/episodes", episodeRouter);
|
||||||
router.use('/episode-seen', episodeSeenRouter);
|
router.use("/episode-seen", episodeSeenRouter);
|
||||||
|
|
||||||
|
router.use("/import", importRouter);
|
||||||
router.use('/import', importRouter);
|
router.use("/statistics", statisticsRouter);
|
||||||
router.use('/statistics', statisticsRouter);
|
router.use("/settings", settingsRouter);
|
||||||
router.use('/settings', settingsRouter);
|
router.use("/maintenance", maintenanceRouter);
|
||||||
router.use('/maintenance', maintenanceRouter);
|
router.use("/ping", pingRouter);
|
||||||
router.use('/ping', pingRouter);
|
router.use("/people", peopleRouter);
|
||||||
router.use('/people', peopleRouter);
|
router.use("/ai-query", aiQueryRouter);
|
||||||
router.use('/ai-query', aiQueryRouter);
|
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
@@ -1,25 +1,25 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const seasonRouter = express.Router();
|
const seasonRouter = express.Router();
|
||||||
|
|
||||||
const seasonController = require('../controllers/seasonController');
|
const seasonController = require("../controllers/seasonController");
|
||||||
|
|
||||||
// ! /seasons
|
// ! /seasons
|
||||||
// * POST - Create a new season
|
// * POST - Create a new season
|
||||||
seasonRouter.post('/', seasonController.createSeason);
|
seasonRouter.post("/", seasonController.createSeason);
|
||||||
|
|
||||||
// * GET - Retrieve all seasons
|
// * GET - Retrieve all seasons
|
||||||
seasonRouter.get('/', seasonController.getSeasons);
|
seasonRouter.get("/", seasonController.getSeasons);
|
||||||
|
|
||||||
// * GET - Retrieve a specific season by id
|
// * GET - Retrieve a specific season by id
|
||||||
seasonRouter.get('/:id', seasonController.getSeaonById);
|
seasonRouter.get("/:id", seasonController.getSeaonById);
|
||||||
|
|
||||||
// * GET - Retrieve episodes of a season
|
// * GET - Retrieve episodes of a season
|
||||||
seasonRouter.get('/:id/episodes', seasonController.getSeasonEpisodes);
|
seasonRouter.get("/:id/episodes", seasonController.getSeasonEpisodes);
|
||||||
|
|
||||||
// * PUT - Update a season
|
// * PUT - Update a season
|
||||||
seasonRouter.put('/:id', seasonController.updateSeason);
|
seasonRouter.put("/:id", seasonController.updateSeason);
|
||||||
|
|
||||||
// * DELETE - Delete a season
|
// * DELETE - Delete a season
|
||||||
seasonRouter.delete('/:id', seasonController.deleteSeason);
|
seasonRouter.delete("/:id", seasonController.deleteSeason);
|
||||||
|
|
||||||
module.exports = seasonRouter;
|
module.exports = seasonRouter;
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const settingsRouter = express.Router();
|
const settingsRouter = express.Router();
|
||||||
|
|
||||||
const settingsController = require('../controllers/settingsController');
|
const settingsController = require("../controllers/settingsController");
|
||||||
|
|
||||||
// ! /settings
|
// ! /settings
|
||||||
settingsRouter.get('/', settingsController.getSettings);
|
settingsRouter.get("/", settingsController.getSettings);
|
||||||
settingsRouter.put('/', settingsController.updateSettings);
|
settingsRouter.put("/", settingsController.updateSettings);
|
||||||
|
|
||||||
module.exports = settingsRouter;
|
module.exports = settingsRouter;
|
||||||
@@ -1,19 +1,28 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const statisticsRouter = express.Router();
|
const statisticsRouter = express.Router();
|
||||||
|
|
||||||
const statisticsController = require('../controllers/statisticsController');
|
const statisticsController = require("../controllers/statisticsController");
|
||||||
|
|
||||||
// ! /statistics
|
// ! /statistics
|
||||||
// * GET - All Time, Watch Time
|
// * GET - All Time, Watch Time
|
||||||
statisticsRouter.get('/watch-time', statisticsController.getAllTimeWatchTime);
|
statisticsRouter.get("/watch-time", statisticsController.getAllTimeWatchTime);
|
||||||
|
|
||||||
// * GET - Yearly Watch Time
|
// * GET - Yearly Watch Time
|
||||||
statisticsRouter.get('/watch-time/year/:year', statisticsController.getYearlyWatchTime);
|
statisticsRouter.get(
|
||||||
|
"/watch-time/year/:year",
|
||||||
|
statisticsController.getYearlyWatchTime,
|
||||||
|
);
|
||||||
|
|
||||||
// * GET - Yearly Watch Count Grouped By Month
|
// * GET - Yearly Watch Count Grouped By Month
|
||||||
statisticsRouter.get('/watch-count/year/:year', statisticsController.getYearlyWatchCountGroupByMonth);
|
statisticsRouter.get(
|
||||||
|
"/watch-count/year/:year",
|
||||||
|
statisticsController.getYearlyWatchCountGroupByMonth,
|
||||||
|
);
|
||||||
|
|
||||||
// * GET - Watch Day Distribution (DAYOFWEEK)
|
// * GET - Watch Day Distribution (DAYOFWEEK)
|
||||||
statisticsRouter.get('/watch-weekday', statisticsController.getWatchdayDistribution);
|
statisticsRouter.get(
|
||||||
|
"/watch-weekday",
|
||||||
|
statisticsController.getWatchdayDistribution,
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = statisticsRouter;
|
module.exports = statisticsRouter;
|
||||||
+29
-29
@@ -1,36 +1,36 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const bodyParser = require('body-parser');
|
const bodyParser = require("body-parser");
|
||||||
const routes = require('./routes/routes.js');
|
const routes = require("./routes/routes.js");
|
||||||
const sequelize = require('./config/database.js');
|
const sequelize = require("./config/database.js");
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
// Global error handling for unhandled promise rejections
|
// Global error handling for unhandled promise rejections
|
||||||
process.on('unhandledRejection', (reason, promise) => {
|
process.on("unhandledRejection", (reason, promise) => {
|
||||||
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
|
console.log("Unhandled Rejection at:", promise, "reason:", reason);
|
||||||
// Application specific logging, throwing an error, or other logic here
|
// Application specific logging, throwing an error, or other logic here
|
||||||
});
|
});
|
||||||
|
|
||||||
// Global error handling for uncaught exceptions
|
// Global error handling for uncaught exceptions
|
||||||
process.on('uncaughtException', (error) => {
|
process.on("uncaughtException", (error) => {
|
||||||
console.log('Uncaught Exception:', error);
|
console.log("Uncaught Exception:", error);
|
||||||
// Application specific logging, throwing an error, or other logic here
|
// Application specific logging, throwing an error, or other logic here
|
||||||
process.exit(1); // Exit the process to avoid undefined state
|
process.exit(1); // Exit the process to avoid undefined state
|
||||||
});
|
});
|
||||||
|
|
||||||
const relations = require('./config/relations.js');
|
const relations = require("./config/relations.js");
|
||||||
const sequelizeHooks = require('./config/sequelizeHooks.js');
|
const sequelizeHooks = require("./config/sequelizeHooks.js");
|
||||||
const { initializeData } = require('./config/dataInitializer.js');
|
const { initializeData } = require("./config/dataInitializer.js");
|
||||||
const killerRouter = require('./routes/killer.routes.js');
|
const killerRouter = require("./routes/killer.routes.js");
|
||||||
const errorHandler = require('./middleware/errorHandler');
|
const errorHandler = require("./middleware/errorHandler");
|
||||||
const configService = require('./services/configService.js');
|
const configService = require("./services/configService.js");
|
||||||
const { logToFile } = require('./services/logService.js');
|
const { logToFile } = require("./services/logService.js");
|
||||||
const { generatePreview } = require('./services/mediaService.js');
|
const { generatePreview } = require("./services/mediaService.js");
|
||||||
|
|
||||||
// ? variables
|
// ? variables
|
||||||
let settings = configService.getSettings()
|
let settings = configService.getSettings();
|
||||||
const PORT = settings["backPort"] || 4000;
|
const PORT = settings["backPort"] || 4000;
|
||||||
const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || '{}');
|
const parrentProcess = JSON.parse(process.env.PARENT_PROCESS || "{}");
|
||||||
|
|
||||||
// ? Middleware
|
// ? Middleware
|
||||||
app.use(bodyParser.json()); // for parsing application/json
|
app.use(bodyParser.json()); // for parsing application/json
|
||||||
@@ -38,31 +38,31 @@ app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x
|
|||||||
|
|
||||||
// * CORS Middleware to allow requests from any origin
|
// * CORS Middleware to allow requests from any origin
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
res.header('Access-Control-Allow-Origin', '*');
|
res.header("Access-Control-Allow-Origin", "*");
|
||||||
res.header(
|
res.header(
|
||||||
'Access-Control-Allow-Headers',
|
"Access-Control-Allow-Headers",
|
||||||
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
|
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
|
||||||
);
|
);
|
||||||
if (req.method === 'OPTIONS') {
|
if (req.method === "OPTIONS") {
|
||||||
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
|
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
|
||||||
return res.status(200).json({});
|
return res.status(200).json({});
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? other api routes
|
// ? other api routes
|
||||||
app.use('/api/v1', routes);
|
app.use("/api/v1", routes);
|
||||||
|
|
||||||
// ? Error handling middleware
|
// ? Error handling middleware
|
||||||
app.use(errorHandler);
|
app.use(errorHandler);
|
||||||
|
|
||||||
// ? KILLER ROUTE: used to crash the backend
|
// ? KILLER ROUTE: used to crash the backend
|
||||||
app.use('/killer', killerRouter);
|
app.use("/killer", killerRouter);
|
||||||
|
|
||||||
// * Start the server
|
// * Start the server
|
||||||
const doUpdate = false;
|
const doUpdate = false;
|
||||||
const doForce = false;
|
const doForce = false;
|
||||||
console.log('Server started');
|
console.log("Server started");
|
||||||
console.log(`Syncing database schema...`);
|
console.log(`Syncing database schema...`);
|
||||||
sequelize
|
sequelize
|
||||||
// .sync({force: true}) // will drop all tables and recreate them.
|
// .sync({force: true}) // will drop all tables and recreate them.
|
||||||
@@ -75,7 +75,7 @@ sequelize
|
|||||||
console.log(`Backend server running on http://localhost:${PORT}/`);
|
console.log(`Backend server running on http://localhost:${PORT}/`);
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch((err) => {
|
||||||
console.log("____________SEQUELIZE SYNC ERROR____________")
|
console.log("____________SEQUELIZE SYNC ERROR____________");
|
||||||
console.log(err)
|
console.log(err);
|
||||||
});
|
});
|
||||||
@@ -19,7 +19,6 @@ const _mediaDownloaderService = mediaDownloaderService;
|
|||||||
const _mediaOptimizerService = mediaOptimizerService;
|
const _mediaOptimizerService = mediaOptimizerService;
|
||||||
|
|
||||||
class CollectionManager {
|
class CollectionManager {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!CollectionManager.instance) {
|
if (!CollectionManager.instance) {
|
||||||
CollectionManager.instance = this;
|
CollectionManager.instance = this;
|
||||||
@@ -43,7 +42,8 @@ class CollectionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// * 2 - insert/update collection
|
// * 2 - insert/update collection
|
||||||
const [oldCollection, createdCollection] = await _collectionService.createOrUpdateCollection(collectionData);
|
const [oldCollection, createdCollection] =
|
||||||
|
await _collectionService.createOrUpdateCollection(collectionData);
|
||||||
|
|
||||||
// * 3 - link related entries to the collection
|
// * 3 - link related entries to the collection
|
||||||
let collection = oldCollection || createdCollection;
|
let collection = oldCollection || createdCollection;
|
||||||
@@ -51,34 +51,40 @@ class CollectionManager {
|
|||||||
throw new NotFoundError("Collection not found");
|
throw new NotFoundError("Collection not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const partIds = collectionData.parts.map(part => part.id);
|
const partIds = collectionData.parts.map((part) => part.id);
|
||||||
|
|
||||||
const entries = await Entry.findAll({
|
const entries = await Entry.findAll({
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: EntryId,
|
model: EntryId,
|
||||||
as: 'entryId',
|
as: "entryId",
|
||||||
where: {
|
where: {
|
||||||
tmdb_id: {
|
tmdb_id: {
|
||||||
[Sequelize.Op.in]: partIds
|
[Sequelize.Op.in]: partIds,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}]
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
await collection.setEntries(entries);
|
await collection.setEntries(entries);
|
||||||
|
|
||||||
// * 4 - download collection media
|
// * 4 - download collection media
|
||||||
// ? downloading
|
// ? downloading
|
||||||
const downloadedImages = await _mediaDownloaderService.downloadCollectionMedia(collection);
|
const downloadedImages =
|
||||||
|
await _mediaDownloaderService.downloadCollectionMedia(collection);
|
||||||
|
|
||||||
// ? generating preview & inserting data
|
// ? generating preview & inserting data
|
||||||
for (const image of downloadedImages) {
|
for (const image of downloadedImages) {
|
||||||
// ? generating preview
|
// ? generating preview
|
||||||
_mediaOptimizerService.doGeneratePreview('collections', image.type + 's', image.path).then((result) => {
|
_mediaOptimizerService
|
||||||
|
.doGeneratePreview("collections", image.type + "s", image.path)
|
||||||
|
.then((result) => {
|
||||||
const msg = `Collection Service | Generated Collection Preview`;
|
const msg = `Collection Service | Generated Collection Preview`;
|
||||||
console.log(msg);
|
console.log(msg);
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
}).catch((err) => {
|
})
|
||||||
|
.catch((err) => {
|
||||||
const msg = `Collection Service | Error Generating Collection Preview`;
|
const msg = `Collection Service | Error Generating Collection Preview`;
|
||||||
console.log(msg);
|
console.log(msg);
|
||||||
console.log(err);
|
console.log(err);
|
||||||
@@ -88,20 +94,19 @@ class CollectionManager {
|
|||||||
|
|
||||||
// ? inserting data
|
// ? inserting data
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'collection',
|
mediaable: "collection",
|
||||||
mediaableId: collection.id,
|
mediaableId: collection.id,
|
||||||
type: image.type,
|
type: image.type,
|
||||||
path: image.path,
|
path: image.path,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// * 5 - return the collection
|
// * 5 - return the collection
|
||||||
return await _collectionService.getCollectionById(collection.id);
|
return await _collectionService.getCollectionById(collection.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetches the corresponding collection for a given entry (movie) if it is missing.
|
* Fetches the corresponding collection for a given entry (movie) if it is missing.
|
||||||
* If the entry belongs to a collection, the collection is fetched and saved.
|
* If the entry belongs to a collection, the collection is fetched and saved.
|
||||||
@@ -118,15 +123,16 @@ class CollectionManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const oldEntry = await Entry.findByPk(id, {
|
const oldEntry = await Entry.findByPk(id, {
|
||||||
include: [
|
include: [{ model: EntryId, as: "entryId" }],
|
||||||
{ model: EntryId, as: 'entryId' }
|
});
|
||||||
]
|
|
||||||
})
|
|
||||||
if (!oldEntry) {
|
if (!oldEntry) {
|
||||||
throw new NotFoundError("Entry not found");
|
throw new NotFoundError("Entry not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
const entryData = await fetchEntryData(
|
||||||
|
oldEntry.entryId.tmdb_id,
|
||||||
|
oldEntry.is_tvseries,
|
||||||
|
);
|
||||||
if (!entryData) {
|
if (!entryData) {
|
||||||
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
||||||
}
|
}
|
||||||
@@ -172,19 +178,21 @@ class CollectionManager {
|
|||||||
|
|
||||||
// * 3 - fetch missing entries and save them and linked already
|
// * 3 - fetch missing entries and save them and linked already
|
||||||
// * existing ones to the collection
|
// * existing ones to the collection
|
||||||
const partIds = collectionData.parts.map(part => part.id);
|
const partIds = collectionData.parts.map((part) => part.id);
|
||||||
|
|
||||||
// ? get all the related entries that are already in the library
|
// ? get all the related entries that are already in the library
|
||||||
const entries = await Entry.findAll({
|
const entries = await Entry.findAll({
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: EntryId,
|
model: EntryId,
|
||||||
as: 'entryId',
|
as: "entryId",
|
||||||
where: {
|
where: {
|
||||||
tmdb_id: {
|
tmdb_id: {
|
||||||
[Sequelize.Op.in]: partIds
|
[Sequelize.Op.in]: partIds,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
}]
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? link entries already existing in the library
|
// ? link entries already existing in the library
|
||||||
@@ -194,8 +202,12 @@ class CollectionManager {
|
|||||||
collectionData.parts.forEach(async (part) => {
|
collectionData.parts.forEach(async (part) => {
|
||||||
if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) {
|
if (entries.filter((e) => e.entryId.tmdb_id == part.id).length == 0) {
|
||||||
const isTvSeries = false;
|
const isTvSeries = false;
|
||||||
const _entryManager = require('./entryManager.js');
|
const _entryManager = require("./entryManager.js");
|
||||||
const entry = await _entryManager.fetchAndSaveNewEntry(part.id, isTvSeries, false)
|
const entry = await _entryManager.fetchAndSaveNewEntry(
|
||||||
|
part.id,
|
||||||
|
isTvSeries,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
await collection.addEntries([entry.id]);
|
await collection.addEntries([entry.id]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,7 @@ const Media = require("../models/Media");
|
|||||||
const Season = require("../models/Season");
|
const Season = require("../models/Season");
|
||||||
const UserCollectionEntry = require("../models/UserCollectionEntry");
|
const UserCollectionEntry = require("../models/UserCollectionEntry");
|
||||||
|
|
||||||
|
|
||||||
class CollectionService {
|
class CollectionService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!CollectionService.instance) {
|
if (!CollectionService.instance) {
|
||||||
CollectionService.instance = this;
|
CollectionService.instance = this;
|
||||||
@@ -22,12 +20,13 @@ class CollectionService {
|
|||||||
const collections = await Collection.findAll({
|
const collections = await Collection.findAll({
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Entry, as: 'entries',
|
model: Entry,
|
||||||
include: { model: Media, as: 'medias' }
|
as: "entries",
|
||||||
|
include: { model: Media, as: "medias" },
|
||||||
},
|
},
|
||||||
{ model: Media, as: 'medias' }
|
{ model: Media, as: "medias" },
|
||||||
],
|
],
|
||||||
order: [['name', 'ASC']]
|
order: [["name", "ASC"]],
|
||||||
});
|
});
|
||||||
|
|
||||||
return collections;
|
return collections;
|
||||||
@@ -35,22 +34,26 @@ class CollectionService {
|
|||||||
|
|
||||||
async getCollectionById(id) {
|
async getCollectionById(id) {
|
||||||
const collection = await Collection.findByPk(id, {
|
const collection = await Collection.findByPk(id, {
|
||||||
include: [{
|
|
||||||
model: Entry,
|
|
||||||
as: 'entries',
|
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
model: Entry,
|
||||||
{ model: Season, as: 'seasons' },
|
as: "entries",
|
||||||
{ model: Media, as: 'medias' },
|
include: [
|
||||||
{ 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: {
|
through: {
|
||||||
model: UserCollectionEntry,
|
model: UserCollectionEntry,
|
||||||
attributes: ['order'], // attributes (to include) from the join model
|
attributes: ["order"], // attributes (to include) from the join model
|
||||||
},
|
},
|
||||||
}],
|
},
|
||||||
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
|
||||||
});
|
});
|
||||||
|
|
||||||
return collection;
|
return collection;
|
||||||
@@ -63,12 +66,11 @@ class CollectionService {
|
|||||||
name: collectionData.name,
|
name: collectionData.name,
|
||||||
posterPath: collectionData.poster_path,
|
posterPath: collectionData.poster_path,
|
||||||
backdropPath: collectionData.backdrop_path,
|
backdropPath: collectionData.backdrop_path,
|
||||||
description: collectionData.overview
|
description: collectionData.overview,
|
||||||
},
|
},
|
||||||
include: [{ model: Media, as: 'medias' }]
|
include: [{ model: Media, as: "medias" }],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new CollectionService();
|
module.exports = new CollectionService();
|
||||||
@@ -1,20 +1,20 @@
|
|||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
const path = require('path');
|
const path = require("path");
|
||||||
|
|
||||||
const defaultSettings = {
|
const defaultSettings = {
|
||||||
userDataPath: '',
|
userDataPath: "",
|
||||||
tmdbApiUrl: '',
|
tmdbApiUrl: "",
|
||||||
tmdbApiKey: '',
|
tmdbApiKey: "",
|
||||||
frontPort: '',
|
frontPort: "",
|
||||||
backPort: '',
|
backPort: "",
|
||||||
portableMode: '',
|
portableMode: "",
|
||||||
|
|
||||||
libraryViewMode: 'grid',
|
libraryViewMode: "grid",
|
||||||
favoritViewMode: 'grid',
|
favoritViewMode: "grid",
|
||||||
watchlistViewMode: 'grid',
|
watchlistViewMode: "grid",
|
||||||
CollectionsViewMode: 'grid',
|
CollectionsViewMode: "grid",
|
||||||
CollectionItemsViewMode: 'grid',
|
CollectionItemsViewMode: "grid",
|
||||||
episodesViewMode: 'grid'
|
episodesViewMode: "grid",
|
||||||
};
|
};
|
||||||
|
|
||||||
class ConfigService {
|
class ConfigService {
|
||||||
@@ -31,7 +31,7 @@ class ConfigService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getSettingsFilePath() {
|
getSettingsFilePath() {
|
||||||
return path.join(this.getUserDataPath(), 'settings.json');
|
return path.join(this.getUserDataPath(), "settings.json");
|
||||||
}
|
}
|
||||||
|
|
||||||
getSettings() {
|
getSettings() {
|
||||||
@@ -43,19 +43,22 @@ class ConfigService {
|
|||||||
const parsedSettings = JSON.parse(settingsData);
|
const parsedSettings = JSON.parse(settingsData);
|
||||||
return { ...defaultSettings, ...parsedSettings };
|
return { ...defaultSettings, ...parsedSettings };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error reading settings file:', err);
|
console.error("Error reading settings file:", err);
|
||||||
console.log('Creating default settings file...');
|
console.log("Creating default settings file...");
|
||||||
|
|
||||||
let newSettingsFile = { ...defaultSettings };
|
let newSettingsFile = { ...defaultSettings };
|
||||||
|
|
||||||
let defaultDataPath = path.join(this.getUserDataPath(), 'data')
|
let defaultDataPath = path.join(this.getUserDataPath(), "data");
|
||||||
|
|
||||||
newSettingsFile.userDataPath = defaultDataPath;
|
newSettingsFile.userDataPath = defaultDataPath;
|
||||||
newSettingsFile.backPort = 4000;
|
newSettingsFile.backPort = 4000;
|
||||||
|
|
||||||
fs.mkdirSync(defaultDataPath, { recursive: true });
|
fs.mkdirSync(defaultDataPath, { recursive: true });
|
||||||
fs.writeFileSync(settingsFilePath, JSON.stringify(newSettingsFile, null, 2));
|
fs.writeFileSync(
|
||||||
console.log('Default settings file created.');
|
settingsFilePath,
|
||||||
|
JSON.stringify(newSettingsFile, null, 2),
|
||||||
|
);
|
||||||
|
console.log("Default settings file created.");
|
||||||
|
|
||||||
return defaultSettings;
|
return defaultSettings;
|
||||||
}
|
}
|
||||||
@@ -65,9 +68,16 @@ class ConfigService {
|
|||||||
const settingsFilePath = this.getSettingsFilePath();
|
const settingsFilePath = this.getSettingsFilePath();
|
||||||
|
|
||||||
const oldSettings = this.getSettings();
|
const oldSettings = this.getSettings();
|
||||||
let updatedSettings = { ...defaultSettings, ...oldSettings, ...newSettings };
|
let updatedSettings = {
|
||||||
|
...defaultSettings,
|
||||||
|
...oldSettings,
|
||||||
|
...newSettings,
|
||||||
|
};
|
||||||
fs.mkdirSync(updatedSettings.userDataPath, { recursive: true }); // making sure the newly set data path is created before saving the new config
|
fs.mkdirSync(updatedSettings.userDataPath, { recursive: true }); // making sure the newly set data path is created before saving the new config
|
||||||
fs.writeFileSync(settingsFilePath, JSON.stringify(updatedSettings, null, 2));
|
fs.writeFileSync(
|
||||||
|
settingsFilePath,
|
||||||
|
JSON.stringify(updatedSettings, null, 2),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
getMediaFolder() {
|
getMediaFolder() {
|
||||||
@@ -77,14 +87,39 @@ class ConfigService {
|
|||||||
const settings = this.getSettings();
|
const settings = this.getSettings();
|
||||||
const dataPath = settings.userDataPath;
|
const dataPath = settings.userDataPath;
|
||||||
|
|
||||||
const posterDir = path.join(dataPath, 'images', 'entries', 'posters');
|
const posterDir = path.join(dataPath, "images", "entries", "posters");
|
||||||
const backdropDir = path.join(dataPath, 'images', 'entries', 'backdrops');
|
const backdropDir = path.join(dataPath, "images", "entries", "backdrops");
|
||||||
const logoDir = path.join(dataPath, 'images', 'entries', 'logos');
|
const logoDir = path.join(dataPath, "images", "entries", "logos");
|
||||||
const collectionsPostersDir = path.join(dataPath, 'images', 'collections', 'posters');
|
const collectionsPostersDir = path.join(
|
||||||
const collectionsBackdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops');
|
dataPath,
|
||||||
const seasonsPostersDir = path.join(dataPath, 'images', 'seasons', 'posters');
|
"images",
|
||||||
const episodesStillsDir = path.join(dataPath, 'images', 'episodes', 'stills');
|
"collections",
|
||||||
const peopleProfilesDir = path.join(dataPath, 'images', 'peoples', 'profiles');
|
"posters",
|
||||||
|
);
|
||||||
|
const collectionsBackdropsDir = path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"backdrops",
|
||||||
|
);
|
||||||
|
const seasonsPostersDir = path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"seasons",
|
||||||
|
"posters",
|
||||||
|
);
|
||||||
|
const episodesStillsDir = path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"episodes",
|
||||||
|
"stills",
|
||||||
|
);
|
||||||
|
const peopleProfilesDir = path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"peoples",
|
||||||
|
"profiles",
|
||||||
|
);
|
||||||
|
|
||||||
fs.mkdirSync(posterDir, { recursive: true });
|
fs.mkdirSync(posterDir, { recursive: true });
|
||||||
fs.mkdirSync(backdropDir, { recursive: true });
|
fs.mkdirSync(backdropDir, { recursive: true });
|
||||||
@@ -103,7 +138,6 @@ class ConfigService {
|
|||||||
getTmdbApiKey() {
|
getTmdbApiKey() {
|
||||||
return this.settings.tmdbApiKey;
|
return this.settings.tmdbApiKey;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// const instance = new ConfigService();
|
// const instance = new ConfigService();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
const moment = require("../utils/moment");
|
const moment = require("../utils/moment");
|
||||||
|
|
||||||
const { Op } = require("sequelize")
|
const { Op } = require("sequelize");
|
||||||
const Episode = require("../models/Episode");
|
const Episode = require("../models/Episode");
|
||||||
const Season = require("../models/Season");
|
const Season = require("../models/Season");
|
||||||
const Entry = require("../models/Entry");
|
const Entry = require("../models/Entry");
|
||||||
@@ -10,7 +10,6 @@ const Media = require("../models/Media");
|
|||||||
const BadRequestError = require("../errors/BadRequestError");
|
const BadRequestError = require("../errors/BadRequestError");
|
||||||
|
|
||||||
class EpisodeService {
|
class EpisodeService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EpisodeService.instance) {
|
if (!EpisodeService.instance) {
|
||||||
EpisodeService.instance = this;
|
EpisodeService.instance = this;
|
||||||
@@ -27,37 +26,37 @@ class EpisodeService {
|
|||||||
throw new BadRequestError("end Date not provided");
|
throw new BadRequestError("end Date not provided");
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatedStartDate = moment(startDate).format('YYYY-MM-DD');
|
const formatedStartDate = moment(startDate).format("YYYY-MM-DD");
|
||||||
const formatedEndDate = moment(endDate).format('YYYY-MM-DD');
|
const formatedEndDate = moment(endDate).format("YYYY-MM-DD");
|
||||||
|
|
||||||
// fetch episodes that aired within the current month, only from entries with showInCalendar enabled
|
// fetch episodes that aired within the current month, only from entries with showInCalendar enabled
|
||||||
const episodes = await Episode.findAll({
|
const episodes = await Episode.findAll({
|
||||||
where: {
|
where: {
|
||||||
air_date: {
|
air_date: {
|
||||||
[Op.between]: [formatedStartDate, formatedEndDate]
|
[Op.between]: [formatedStartDate, formatedEndDate],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Season,
|
model: Season,
|
||||||
as: 'season',
|
as: "season",
|
||||||
include: {
|
include: {
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: 'entry',
|
as: "entry",
|
||||||
where: { showInCalendar: true },
|
where: { showInCalendar: true },
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{
|
{
|
||||||
model: Media,
|
model: Media,
|
||||||
as: 'medias',
|
as: "medias",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const modifiedEpisodes = episodes.map(episode => {
|
const modifiedEpisodes = episodes.map((episode) => {
|
||||||
const episodeJSON = episode.toJSON();
|
const episodeJSON = episode.toJSON();
|
||||||
if (episodeJSON.season && episodeJSON.season.entry) {
|
if (episodeJSON.season && episodeJSON.season.entry) {
|
||||||
episodeJSON.entry = episodeJSON.season.entry;
|
episodeJSON.entry = episodeJSON.season.entry;
|
||||||
@@ -68,7 +67,6 @@ class EpisodeService {
|
|||||||
|
|
||||||
return modifiedEpisodes;
|
return modifiedEpisodes;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new EpisodeService();
|
module.exports = new EpisodeService();
|
||||||
@@ -15,15 +15,13 @@ async function bulkImportMovies(movies) {
|
|||||||
const waitTime = 10000;
|
const waitTime = 10000;
|
||||||
|
|
||||||
let entries = [];
|
let entries = [];
|
||||||
let overAllFetches = 0
|
let overAllFetches = 0;
|
||||||
let currenFetch = 0;
|
let currenFetch = 0;
|
||||||
|
|
||||||
// ? gettings all entries from db
|
// ? gettings all entries from db
|
||||||
const entriesFromDb = await Entry.findAll({
|
const entriesFromDb = await Entry.findAll({
|
||||||
include: [
|
include: [{ model: EntryId, as: "entryId" }],
|
||||||
{ model: EntryId, as: 'entryId' }
|
});
|
||||||
]
|
|
||||||
})
|
|
||||||
|
|
||||||
// ? creating a dict from the entries
|
// ? creating a dict from the entries
|
||||||
const entriesDict = entriesFromDb.reduce((dict, entry) => {
|
const entriesDict = entriesFromDb.reduce((dict, entry) => {
|
||||||
@@ -32,20 +30,30 @@ async function bulkImportMovies(movies) {
|
|||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
for (const movie of movies) {
|
for (const movie of movies) {
|
||||||
|
|
||||||
if (entriesDict[movie.tmdbId]) {
|
if (entriesDict[movie.tmdbId]) {
|
||||||
console.log(`Entry already exists: ${entriesDict[movie.tmdbId].title} (${movie.tmdbId})`)
|
console.log(
|
||||||
|
`Entry already exists: ${entriesDict[movie.tmdbId].title} (${movie.tmdbId})`,
|
||||||
|
);
|
||||||
// ? adding date seen
|
// ? adding date seen
|
||||||
await EntrySeen.destroy({ where: { entry_id: entriesDict[movie.tmdbId].id } });
|
await EntrySeen.destroy({
|
||||||
await EntrySeen.create({ entry_id: entriesDict[movie.tmdbId].id, date_seen: movie.dateSeen, seen_with: "" });
|
where: { entry_id: entriesDict[movie.tmdbId].id },
|
||||||
|
});
|
||||||
|
await EntrySeen.create({
|
||||||
|
entry_id: entriesDict[movie.tmdbId].id,
|
||||||
|
date_seen: movie.dateSeen,
|
||||||
|
seen_with: "",
|
||||||
|
});
|
||||||
|
|
||||||
// ? adding entry user rating
|
// ? adding entry user rating
|
||||||
if (movie.userRating != 0) {
|
if (movie.userRating != 0) {
|
||||||
await EntryRating.update({ user_rating: movie.userRating }, {
|
await EntryRating.update(
|
||||||
|
{ user_rating: movie.userRating },
|
||||||
|
{
|
||||||
where: {
|
where: {
|
||||||
entry_id: entriesDict[movie.tmdbId].id
|
entry_id: entriesDict[movie.tmdbId].id,
|
||||||
}
|
},
|
||||||
});
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const data = await fetchEntryData(movie.tmdbId, false);
|
const data = await fetchEntryData(movie.tmdbId, false);
|
||||||
@@ -55,20 +63,27 @@ async function bulkImportMovies(movies) {
|
|||||||
const entry = await saveEntry(data);
|
const entry = await saveEntry(data);
|
||||||
|
|
||||||
// ? adding date seen
|
// ? adding date seen
|
||||||
await EntrySeen.create({ entry_id: entry.id, date_seen: movie.dateSeen, seen_with: "" });
|
await EntrySeen.create({
|
||||||
|
entry_id: entry.id,
|
||||||
|
date_seen: movie.dateSeen,
|
||||||
|
seen_with: "",
|
||||||
|
});
|
||||||
|
|
||||||
// ? adding entry user rating
|
// ? adding entry user rating
|
||||||
if (movie.userRating != 0) {
|
if (movie.userRating != 0) {
|
||||||
await EntryRating.update({ user_rating: movie.userRating }, {
|
await EntryRating.update(
|
||||||
|
{ user_rating: movie.userRating },
|
||||||
|
{
|
||||||
where: {
|
where: {
|
||||||
entry_id: entry.id
|
entry_id: entry.id,
|
||||||
}
|
},
|
||||||
});
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
entries.push(entry)
|
entries.push(entry);
|
||||||
// ? wait 100ms between each tmdb fetch
|
// ? wait 100ms between each tmdb fetch
|
||||||
await new Promise(resolve => setTimeout(resolve, fetchInterval));
|
await new Promise((resolve) => setTimeout(resolve, fetchInterval));
|
||||||
console.log(`${currenFetch} imported id: ${movie.tmdbId}`);
|
console.log(`${currenFetch} imported id: ${movie.tmdbId}`);
|
||||||
currenFetch++;
|
currenFetch++;
|
||||||
overAllFetches++;
|
overAllFetches++;
|
||||||
@@ -76,31 +91,28 @@ async function bulkImportMovies(movies) {
|
|||||||
// ? stop 10 seconds after 35 tmdb fetch
|
// ? stop 10 seconds after 35 tmdb fetch
|
||||||
if (currenFetch == maxFetches) {
|
if (currenFetch == maxFetches) {
|
||||||
console.log(`Now waiting ${waitTime / 1000} seconds...`);
|
console.log(`Now waiting ${waitTime / 1000} seconds...`);
|
||||||
await new Promise(resolve => setTimeout(resolve, waitTime));
|
await new Promise((resolve) => setTimeout(resolve, waitTime));
|
||||||
currentFetch = 0;
|
currentFetch = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function bulkImportTmdb(movies) {
|
async function bulkImportTmdb(movies) {
|
||||||
const maxFetches = 35; // ! max fetch per 10 seconds
|
const maxFetches = 35; // ! max fetch per 10 seconds
|
||||||
const fetchInterval = 500;
|
const fetchInterval = 500;
|
||||||
const waitTime = 10000;
|
const waitTime = 10000;
|
||||||
|
|
||||||
let entries = [];
|
let entries = [];
|
||||||
let overAllFetches = 0
|
let overAllFetches = 0;
|
||||||
let currentFetch = 0;
|
let currentFetch = 0;
|
||||||
|
|
||||||
// ? gettings all entries from db
|
// ? gettings all entries from db
|
||||||
const entriesFromDb = await Entry.findAll({
|
const entriesFromDb = await Entry.findAll({
|
||||||
include: [
|
include: [{ model: EntryId, as: "entryId" }],
|
||||||
{ model: EntryId, as: 'entryId' }
|
});
|
||||||
]
|
|
||||||
})
|
|
||||||
|
|
||||||
// ? creating a dict from the entries
|
// ? creating a dict from the entries
|
||||||
const entriesDict = entriesFromDb.reduce((dict, entry) => {
|
const entriesDict = entriesFromDb.reduce((dict, entry) => {
|
||||||
@@ -112,7 +124,9 @@ async function bulkImportTmdb(movies) {
|
|||||||
|
|
||||||
for (const movie of movies) {
|
for (const movie of movies) {
|
||||||
if (entriesDict[movie]) {
|
if (entriesDict[movie]) {
|
||||||
console.log(`Entry already exists: ${entriesDict[movie].title} (${movie})`)
|
console.log(
|
||||||
|
`Entry already exists: ${entriesDict[movie].title} (${movie})`,
|
||||||
|
);
|
||||||
created.push(movie);
|
created.push(movie);
|
||||||
} else {
|
} else {
|
||||||
if (created.includes(movie)) continue; // * skip doubles
|
if (created.includes(movie)) continue; // * skip doubles
|
||||||
@@ -122,20 +136,21 @@ async function bulkImportTmdb(movies) {
|
|||||||
console.log(`${currentFetch} data null for id: ${movie.id}`);
|
console.log(`${currentFetch} data null for id: ${movie.id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// ? saving the entry
|
// ? saving the entry
|
||||||
const entry = await saveEntry(data);
|
const entry = await saveEntry(data);
|
||||||
entries.push(entry)
|
entries.push(entry);
|
||||||
created.push(movie)
|
created.push(movie);
|
||||||
currentFetch += data.seasons.length;
|
currentFetch += data.seasons.length;
|
||||||
|
|
||||||
// TODO implement option like rating, dateseen...
|
// TODO implement option like rating, dateseen...
|
||||||
|
|
||||||
// ? wait 100ms between each tmdb fetch
|
// ? wait 100ms between each tmdb fetch
|
||||||
await new Promise(resolve => setTimeout(resolve, fetchInterval));
|
await new Promise((resolve) => setTimeout(resolve, fetchInterval));
|
||||||
console.log(`${overAllFetches} (${currentFetch + 1}/${maxFetches}) imported ${entry.title}`);
|
console.log(
|
||||||
|
`${overAllFetches} (${currentFetch + 1}/${maxFetches}) imported ${entry.title}`,
|
||||||
|
);
|
||||||
if (data.seasons.length)
|
if (data.seasons.length)
|
||||||
console.log(`With ${data.seasons.length} season(s).`)
|
console.log(`With ${data.seasons.length} season(s).`);
|
||||||
|
|
||||||
currentFetch++;
|
currentFetch++;
|
||||||
overAllFetches++;
|
overAllFetches++;
|
||||||
@@ -143,42 +158,40 @@ async function bulkImportTmdb(movies) {
|
|||||||
// ? stop 10 seconds after 35 tmdb fetch
|
// ? stop 10 seconds after 35 tmdb fetch
|
||||||
if (currentFetch >= maxFetches) {
|
if (currentFetch >= maxFetches) {
|
||||||
console.log(`Now waiting ${waitTime / 1000} seconds...`);
|
console.log(`Now waiting ${waitTime / 1000} seconds...`);
|
||||||
await new Promise(resolve => setTimeout(resolve, waitTime));
|
await new Promise((resolve) => setTimeout(resolve, waitTime));
|
||||||
currentFetch = 0;
|
currentFetch = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function bulkImportEpisodes(episodesSeen) {
|
async function bulkImportEpisodes(episodesSeen) {
|
||||||
try {
|
try {
|
||||||
// ! DANGER clearing old episode seen
|
// ! DANGER clearing old episode seen
|
||||||
await EpisodeSeen.destroy({
|
await EpisodeSeen.destroy({
|
||||||
where: {
|
where: {
|
||||||
entry_id: {
|
entry_id: {
|
||||||
[Op.ne]: 3
|
[Op.ne]: 3,
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
})
|
});
|
||||||
|
|
||||||
// ? gettings all entries from db
|
// ? gettings all entries from db
|
||||||
const entriesFromDb = await Entry.findAll({
|
const entriesFromDb = await Entry.findAll({
|
||||||
where: {
|
where: {
|
||||||
is_tvseries: 1
|
is_tvseries: 1,
|
||||||
},
|
},
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{
|
{
|
||||||
model: Season, as: 'seasons', include:
|
model: Season,
|
||||||
[
|
as: "seasons",
|
||||||
{ model: Episode, as: 'episodes' }
|
include: [{ model: Episode, as: "episodes" }],
|
||||||
]
|
},
|
||||||
}
|
],
|
||||||
]
|
});
|
||||||
})
|
|
||||||
|
|
||||||
// ? creating two dictionnaries names & ids
|
// ? creating two dictionnaries names & ids
|
||||||
const idsDict = entriesFromDb.reduce((dict, entry) => {
|
const idsDict = entriesFromDb.reduce((dict, entry) => {
|
||||||
@@ -198,14 +211,16 @@ async function bulkImportEpisodes(episodesSeen) {
|
|||||||
|
|
||||||
for (let i = 0; i < episodesSeen.length; i++) {
|
for (let i = 0; i < episodesSeen.length; i++) {
|
||||||
let theEntry;
|
let theEntry;
|
||||||
if (episodesSeen[i].type == 'id') {
|
if (episodesSeen[i].type == "id") {
|
||||||
theEntry = idsDict[episodesSeen[i].id];
|
theEntry = idsDict[episodesSeen[i].id];
|
||||||
} else if (episodesSeen[i].type == 'title') {
|
} else if (episodesSeen[i].type == "title") {
|
||||||
theEntry = titlesDict[episodesSeen[i].title.toLowerCase()];
|
theEntry = titlesDict[episodesSeen[i].title.toLowerCase()];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!theEntry) {
|
if (!theEntry) {
|
||||||
console.log(`No entry found for line ${i + 1} (${episodesSeen[i].id || episodesSeen[i].title})`);
|
console.log(
|
||||||
|
`No entry found for line ${i + 1} (${episodesSeen[i].id || episodesSeen[i].title})`,
|
||||||
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,18 +236,22 @@ async function bulkImportEpisodes(episodesSeen) {
|
|||||||
episodes++;
|
episodes++;
|
||||||
|
|
||||||
let date_seen = episodesSeen[i].date_seen;
|
let date_seen = episodesSeen[i].date_seen;
|
||||||
if (new Date(episodesSeen[i].date_seen) < new Date(episode.air_date)) {
|
if (
|
||||||
date_seen = episode.air_date.toISOString().split('T')[0];
|
new Date(episodesSeen[i].date_seen) < new Date(episode.air_date)
|
||||||
console.log(`Date seen changed for ${theEntry.title} S${episodesSeen[i].season}E${episodesSeen[i].episode} from ${episodesSeen[i].date_seen} to ${date_seen}`);
|
) {
|
||||||
|
date_seen = episode.air_date.toISOString().split("T")[0];
|
||||||
|
console.log(
|
||||||
|
`Date seen changed for ${theEntry.title} S${episodesSeen[i].season}E${episodesSeen[i].episode} from ${episodesSeen[i].date_seen} to ${date_seen}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let id = `${theEntry.id}${(episodesSeen[i].season + 0)}${episode.id}${date_seen.replace(/-/g, '')}`;
|
let id = `${theEntry.id}${episodesSeen[i].season + 0}${episode.id}${date_seen.replace(/-/g, "")}`;
|
||||||
if (!added[id]) {
|
if (!added[id]) {
|
||||||
await EpisodeSeen.create({
|
await EpisodeSeen.create({
|
||||||
entry_id: theEntry.id,
|
entry_id: theEntry.id,
|
||||||
episode_id: episode.id,
|
episode_id: episode.id,
|
||||||
date_seen: date_seen,
|
date_seen: date_seen,
|
||||||
seen_with: episodesSeen[i].seen_with
|
seen_with: episodesSeen[i].seen_with,
|
||||||
});
|
});
|
||||||
added[id] = true;
|
added[id] = true;
|
||||||
rows++;
|
rows++;
|
||||||
@@ -243,11 +262,13 @@ async function bulkImportEpisodes(episodesSeen) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`)
|
console.log(
|
||||||
|
`rows:${rows}, seasons:${seasons}, episodes:${episodes} (out of ${episodesSeen.length})`,
|
||||||
|
);
|
||||||
console.log(added);
|
console.log(added);
|
||||||
return rows;
|
return rows;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(error)
|
console.log(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
// logService.js
|
// logService.js
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
const util = require('util');
|
const util = require("util");
|
||||||
const moment = require('../utils/moment');
|
const moment = require("../utils/moment");
|
||||||
|
|
||||||
// Convert fs.writeFile to a promise-based function
|
// Convert fs.writeFile to a promise-based function
|
||||||
const writeFile = util.promisify(fs.writeFile);
|
const writeFile = util.promisify(fs.writeFile);
|
||||||
|
|
||||||
// Ensure the log file exists and is accessible
|
// Ensure the log file exists and is accessible
|
||||||
const logFilePath = 'showy.log';
|
const logFilePath = "showy.log";
|
||||||
fs.open(logFilePath, 'a', (err, fd) => {
|
fs.open(logFilePath, "a", (err, fd) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error("Failed to open log file:", err);
|
console.error("Failed to open log file:", err);
|
||||||
} else {
|
} else {
|
||||||
@@ -21,10 +21,10 @@ fs.open(logFilePath, 'a', (err, fd) => {
|
|||||||
// Asynchronous function to append a message to the log file
|
// Asynchronous function to append a message to the log file
|
||||||
async function logToFile(message) {
|
async function logToFile(message) {
|
||||||
try {
|
try {
|
||||||
const time = moment().format('YYYY-MM-DD HH:mm:ss')
|
const time = moment().format("YYYY-MM-DD HH:mm:ss");
|
||||||
const formatedMsg = `[${time}] ${message}`;
|
const formatedMsg = `[${time}] ${message}`;
|
||||||
console.log(formatedMsg);
|
console.log(formatedMsg);
|
||||||
await writeFile(logFilePath, formatedMsg + '\n', { flag: 'a' });
|
await writeFile(logFilePath, formatedMsg + "\n", { flag: "a" });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("Failed to write to log file:", err);
|
console.error("Failed to write to log file:", err);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
const path = require('path');
|
const path = require("path");
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
const { default: axios } = require('axios');
|
const { default: axios } = require("axios");
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require("uuid");
|
||||||
|
|
||||||
const { logToFile } = require("./logService");
|
const { logToFile } = require("./logService");
|
||||||
const configService = require('./configService');
|
const configService = require("./configService");
|
||||||
|
|
||||||
const _configService = configService;
|
const _configService = configService;
|
||||||
|
|
||||||
@@ -27,23 +27,51 @@ class MediaDownloaderService {
|
|||||||
|
|
||||||
const dataPath = _configService.getSettings().userDataPath;
|
const dataPath = _configService.getSettings().userDataPath;
|
||||||
|
|
||||||
const hasPoster = collection.medias && collection.medias.filter((m) => m.type == 'poster').length != 0;
|
const hasPoster =
|
||||||
|
collection.medias &&
|
||||||
|
collection.medias.filter((m) => m.type == "poster").length != 0;
|
||||||
if (collection.posterPath && !hasPoster) {
|
if (collection.posterPath && !hasPoster) {
|
||||||
const postersDir = path.join(dataPath, 'images', 'collections', 'posters')
|
const postersDir = path.join(
|
||||||
this.scheduleDownloads({ file_path: collection.posterPath }, 'poster', postersDir, downloadTasks, downloadedImages);
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"posters",
|
||||||
|
);
|
||||||
|
this.scheduleDownloads(
|
||||||
|
{ file_path: collection.posterPath },
|
||||||
|
"poster",
|
||||||
|
postersDir,
|
||||||
|
downloadTasks,
|
||||||
|
downloadedImages,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasBackdrop = collection.medias && collection.medias.filter((m) => m.type == 'backdrop').length != 0;
|
const hasBackdrop =
|
||||||
|
collection.medias &&
|
||||||
|
collection.medias.filter((m) => m.type == "backdrop").length != 0;
|
||||||
if (collection.backdropPath && !hasBackdrop) {
|
if (collection.backdropPath && !hasBackdrop) {
|
||||||
const backdropsDir = path.join(dataPath, 'images', 'collections', 'backdrops')
|
const backdropsDir = path.join(
|
||||||
this.scheduleDownloads({ file_path: collection.backdropPath }, 'backdrop', backdropsDir, downloadTasks, downloadedImages);
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"backdrops",
|
||||||
|
);
|
||||||
|
this.scheduleDownloads(
|
||||||
|
{ file_path: collection.backdropPath },
|
||||||
|
"backdrop",
|
||||||
|
backdropsDir,
|
||||||
|
downloadTasks,
|
||||||
|
downloadedImages,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait for all downloads to complete
|
// Wait for all downloads to complete
|
||||||
await Promise.all(downloadTasks).then(() => {
|
await Promise.all(downloadTasks)
|
||||||
console.log('Downloaded images:', downloadedImages);
|
.then(() => {
|
||||||
}).catch(err => {
|
console.log("Downloaded images:", downloadedImages);
|
||||||
console.error('Error downloading entry images:', err);
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("Error downloading entry images:", err);
|
||||||
});
|
});
|
||||||
|
|
||||||
return downloadedImages;
|
return downloadedImages;
|
||||||
@@ -61,32 +89,56 @@ class MediaDownloaderService {
|
|||||||
const dataPath = _configService.getSettings().userDataPath;
|
const dataPath = _configService.getSettings().userDataPath;
|
||||||
|
|
||||||
// Check if person already has a profile image
|
// Check if person already has a profile image
|
||||||
const hasProfile = person.medias && person.medias.filter((m) => m.type === 'profile').length !== 0;
|
const hasProfile =
|
||||||
|
person.medias &&
|
||||||
|
person.medias.filter((m) => m.type === "profile").length !== 0;
|
||||||
|
|
||||||
if (person.profile_path && !hasProfile) {
|
if (person.profile_path && !hasProfile) {
|
||||||
const profilesDir = path.join(dataPath, 'images', 'peoples', 'profiles');
|
const profilesDir = path.join(dataPath, "images", "peoples", "profiles");
|
||||||
this.scheduleDownloads({ file_path: person.profile_path }, 'profile', profilesDir, downloadTasks, downloadedImages);
|
this.scheduleDownloads(
|
||||||
|
{ file_path: person.profile_path },
|
||||||
|
"profile",
|
||||||
|
profilesDir,
|
||||||
|
downloadTasks,
|
||||||
|
downloadedImages,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait for all downloads to complete
|
// Wait for all downloads to complete
|
||||||
await Promise.all(downloadTasks).then(() => {
|
await Promise.all(downloadTasks)
|
||||||
console.log('Downloaded images:', downloadedImages);
|
.then(() => {
|
||||||
}).catch(err => {
|
console.log("Downloaded images:", downloadedImages);
|
||||||
console.error('Error downloading entry images:', err);
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("Error downloading entry images:", err);
|
||||||
});
|
});
|
||||||
|
|
||||||
return downloadedImages;
|
return downloadedImages;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Utility to find the preferred media (English if available, otherwise the first one)
|
// Utility to find the preferred media (English if available, otherwise the first one)
|
||||||
findPreferredMedia(mediaArray, preferredLanguage = 'en') {
|
findPreferredMedia(mediaArray, preferredLanguage = "en") {
|
||||||
return mediaArray.find(media => media.iso_639_1 === preferredLanguage && !media.file_path.includes('.svg')) || mediaArray.find(media => !media.file_path.includes('.svg')) || mediaArray[0];
|
return (
|
||||||
|
mediaArray.find(
|
||||||
|
(media) =>
|
||||||
|
media.iso_639_1 === preferredLanguage &&
|
||||||
|
!media.file_path.includes(".svg"),
|
||||||
|
) ||
|
||||||
|
mediaArray.find((media) => !media.file_path.includes(".svg")) ||
|
||||||
|
mediaArray[0]
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Adjusted scheduleDownloads to accept local arrays
|
// Adjusted scheduleDownloads to accept local arrays
|
||||||
scheduleDownloads(media, mediaType, mediaDir, downloadTasks, downloadedImages) {
|
scheduleDownloads(
|
||||||
|
media,
|
||||||
|
mediaType,
|
||||||
|
mediaDir,
|
||||||
|
downloadTasks,
|
||||||
|
downloadedImages,
|
||||||
|
) {
|
||||||
const uniqueFilename = uuidv4();
|
const uniqueFilename = uuidv4();
|
||||||
const extension = media.file_path.split('.').pop();
|
const extension = media.file_path.split(".").pop();
|
||||||
|
|
||||||
const url = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
const url = `https://image.tmdb.org/t/p/original${media.file_path}`;
|
||||||
const filename = `${uniqueFilename}.${extension}`;
|
const filename = `${uniqueFilename}.${extension}`;
|
||||||
@@ -96,38 +148,42 @@ class MediaDownloaderService {
|
|||||||
downloadTasks.push(
|
downloadTasks.push(
|
||||||
this.downloadImage(url, downloadPath)
|
this.downloadImage(url, downloadPath)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
logToFile(`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`)
|
logToFile(
|
||||||
downloadedImages.push({ type: mediaType, path: filename })
|
`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`,
|
||||||
})
|
);
|
||||||
.catch(err => {
|
downloadedImages.push({ type: mediaType, path: filename });
|
||||||
logToFile(`Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`)
|
|
||||||
logToFile(err)
|
|
||||||
console.error(`Error downloading ${mediaType}:`, err)
|
|
||||||
})
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
logToFile(
|
||||||
|
`Media Service | failed to download: ${mediaType}, path:${downloadPath} url:${url}`,
|
||||||
|
);
|
||||||
|
logToFile(err);
|
||||||
|
console.error(`Error downloading ${mediaType}:`, err);
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async downloadImage(url, filePath) {
|
async downloadImage(url, filePath) {
|
||||||
const response = await axios({
|
const response = await axios({
|
||||||
url: url,
|
url: url,
|
||||||
method: 'GET',
|
method: "GET",
|
||||||
responseType: 'stream'
|
responseType: "stream",
|
||||||
});
|
});
|
||||||
|
|
||||||
const writer = fs.createWriteStream(filePath);
|
const writer = fs.createWriteStream(filePath);
|
||||||
response.data.pipe(writer);
|
response.data.pipe(writer);
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
writer.on('finish', resolve);
|
writer.on("finish", resolve);
|
||||||
writer.on('error', reject);
|
writer.on("error", reject);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async downloadFile(url) {
|
async downloadFile(url) {
|
||||||
const response = await axios({
|
const response = await axios({
|
||||||
url: url,
|
url: url,
|
||||||
method: 'GET',
|
method: "GET",
|
||||||
responseType: 'stream'
|
responseType: "stream",
|
||||||
});
|
});
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const path = require('path');
|
const path = require("path");
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require("uuid");
|
||||||
|
|
||||||
const Entry = require("../models/Entry");
|
const Entry = require("../models/Entry");
|
||||||
|
|
||||||
@@ -11,9 +11,9 @@ const tmdbService = require("./tmdbService");
|
|||||||
const mediaService = require("./mediaService");
|
const mediaService = require("./mediaService");
|
||||||
const mediaDownloaderService = require("./mediaDownloaderService");
|
const mediaDownloaderService = require("./mediaDownloaderService");
|
||||||
const mediaOptimizerService = require("./mediaOptimizerService");
|
const mediaOptimizerService = require("./mediaOptimizerService");
|
||||||
const Season = require('../models/Season');
|
const Season = require("../models/Season");
|
||||||
const storageService = require('./storageService');
|
const storageService = require("./storageService");
|
||||||
const Media = require('../models/Media');
|
const Media = require("../models/Media");
|
||||||
|
|
||||||
const _configService = configService;
|
const _configService = configService;
|
||||||
const _mediaService = mediaService;
|
const _mediaService = mediaService;
|
||||||
@@ -23,7 +23,6 @@ const _mediaDownloaderService = mediaDownloaderService;
|
|||||||
const _storageService = storageService;
|
const _storageService = storageService;
|
||||||
|
|
||||||
class MediaManager {
|
class MediaManager {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!MediaManager.instance) {
|
if (!MediaManager.instance) {
|
||||||
MediaManager.instance = this;
|
MediaManager.instance = this;
|
||||||
@@ -32,7 +31,6 @@ class MediaManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async saveMedia(entryId, files) {
|
async saveMedia(entryId, files) {
|
||||||
|
|
||||||
if (!files) {
|
if (!files) {
|
||||||
throw new BadRequestError("No media uploaded");
|
throw new BadRequestError("No media uploaded");
|
||||||
}
|
}
|
||||||
@@ -42,7 +40,9 @@ class MediaManager {
|
|||||||
throw new NotFoundError("Entry not found");
|
throw new NotFoundError("Entry not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const fileType = ['poster', 'backdrop', 'logo'].find(type => req.files[type]);
|
const fileType = ["poster", "backdrop", "logo"].find(
|
||||||
|
(type) => req.files[type],
|
||||||
|
);
|
||||||
|
|
||||||
if (!fileType) {
|
if (!fileType) {
|
||||||
throw new BadRequestError("Invalid media type");
|
throw new BadRequestError("Invalid media type");
|
||||||
@@ -51,31 +51,38 @@ class MediaManager {
|
|||||||
// * 1 - save the media into database
|
// * 1 - save the media into database
|
||||||
const file = req.files[fileType][0];
|
const file = req.files[fileType][0];
|
||||||
const createdMedia = await _mediaService.createMedia({
|
const createdMedia = await _mediaService.createMedia({
|
||||||
mediaable: 'entry',
|
mediaable: "entry",
|
||||||
mediaableId: id,
|
mediaableId: id,
|
||||||
type: fileType,
|
type: fileType,
|
||||||
path: file.filename,
|
path: file.filename,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: false,
|
isSelected: false,
|
||||||
isCustom: true
|
isCustom: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// * 2 - generating low resolution preview
|
// * 2 - generating low resolution preview
|
||||||
_mediaOptimizerService.generatePreviewFiles('entries', fileType + 's', file.filename).then((result) => {
|
_mediaOptimizerService
|
||||||
|
.generatePreviewFiles("entries", fileType + "s", file.filename)
|
||||||
|
.then((result) => {
|
||||||
const stream = fs.createReadStream(filePath);
|
const stream = fs.createReadStream(filePath);
|
||||||
stream.pipe(res);
|
stream.pipe(res);
|
||||||
|
|
||||||
const msg = `Media Route | Generated Entry Preview`
|
const msg = `Media Route | Generated Entry Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
}).catch((err) => {
|
})
|
||||||
const msg = `Media Route | Error Generating Entry Preview`
|
.catch((err) => {
|
||||||
|
const msg = `Media Route | Error Generating Entry Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
});
|
});
|
||||||
|
|
||||||
return createdMedia;
|
return createdMedia;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getEntryMedia(tmdb_id, is_tvserie, includes = ['posters', 'logos', 'backdrops']) {
|
async getEntryMedia(
|
||||||
|
tmdb_id,
|
||||||
|
is_tvserie,
|
||||||
|
includes = ["posters", "logos", "backdrops"],
|
||||||
|
) {
|
||||||
// Fetching entry media
|
// Fetching entry media
|
||||||
const mediaData = await _tmdbService.fetchEntryMedia(tmdb_id, is_tvserie);
|
const mediaData = await _tmdbService.fetchEntryMedia(tmdb_id, is_tvserie);
|
||||||
if (!mediaData) {
|
if (!mediaData) {
|
||||||
@@ -93,27 +100,43 @@ class MediaManager {
|
|||||||
|
|
||||||
// Handling different media types
|
// Handling different media types
|
||||||
const mediaTypes = [
|
const mediaTypes = [
|
||||||
{ type: 'posters', dir: path.join(dataPath, 'images', 'entries', 'posters') },
|
{
|
||||||
{ type: 'logos', dir: path.join(dataPath, 'images', 'entries', 'logos') },
|
type: "posters",
|
||||||
{ type: 'backdrops', dir: path.join(dataPath, 'images', 'entries', 'backdrops') }
|
dir: path.join(dataPath, "images", "entries", "posters"),
|
||||||
|
},
|
||||||
|
{ type: "logos", dir: path.join(dataPath, "images", "entries", "logos") },
|
||||||
|
{
|
||||||
|
type: "backdrops",
|
||||||
|
dir: path.join(dataPath, "images", "entries", "backdrops"),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
mediaTypes.forEach(({ type, dir }) => {
|
mediaTypes.forEach(({ type, dir }) => {
|
||||||
if (!includes.includes(type)) return; // ? the media type is not requested
|
if (!includes.includes(type)) return; // ? the media type is not requested
|
||||||
|
|
||||||
if (mediaData[type] && mediaData[type].length) {
|
if (mediaData[type] && mediaData[type].length) {
|
||||||
const selectedMedia = _mediaDownloaderService.findPreferredMedia(mediaData[type]);
|
const selectedMedia = _mediaDownloaderService.findPreferredMedia(
|
||||||
|
mediaData[type],
|
||||||
|
);
|
||||||
if (selectedMedia) {
|
if (selectedMedia) {
|
||||||
_mediaDownloaderService.scheduleDownloads(selectedMedia, type.slice(0, -1), dir, downloadTasks, downloadedImages);
|
_mediaDownloaderService.scheduleDownloads(
|
||||||
|
selectedMedia,
|
||||||
|
type.slice(0, -1),
|
||||||
|
dir,
|
||||||
|
downloadTasks,
|
||||||
|
downloadedImages,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for all downloads to complete
|
// Wait for all downloads to complete
|
||||||
await Promise.all(downloadTasks).then(() => {
|
await Promise.all(downloadTasks)
|
||||||
console.log('Downloaded images:', downloadedImages);
|
.then(() => {
|
||||||
}).catch(err => {
|
console.log("Downloaded images:", downloadedImages);
|
||||||
console.error('Error downloading entry images:', err);
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("Error downloading entry images:", err);
|
||||||
});
|
});
|
||||||
|
|
||||||
return downloadedImages;
|
return downloadedImages;
|
||||||
@@ -125,23 +148,32 @@ class MediaManager {
|
|||||||
const file = await _mediaDownloaderService.downloadFile(url);
|
const file = await _mediaDownloaderService.downloadFile(url);
|
||||||
|
|
||||||
const uniqueFilename = uuidv4();
|
const uniqueFilename = uuidv4();
|
||||||
const extension = season.poster_path.split('.').pop();
|
const extension = season.poster_path.split(".").pop();
|
||||||
const filename = `${uniqueFilename}.${extension}`;
|
const filename = `${uniqueFilename}.${extension}`;
|
||||||
|
|
||||||
const dataPath = _configService.getSettings().userDataPath;
|
const dataPath = _configService.getSettings().userDataPath;
|
||||||
const fullFilePath = path.join(dataPath, 'images', 'seasons', 'posters', filename)
|
const fullFilePath = path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"seasons",
|
||||||
|
"posters",
|
||||||
|
filename,
|
||||||
|
);
|
||||||
|
|
||||||
_storageService.storeFile(file, fullFilePath).then(async () => {
|
_storageService
|
||||||
|
.storeFile(file, fullFilePath)
|
||||||
|
.then(async () => {
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'season',
|
mediaable: "season",
|
||||||
mediaableId: season.id,
|
mediaableId: season.id,
|
||||||
type: 'poster',
|
type: "poster",
|
||||||
path: filename,
|
path: filename,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true,
|
||||||
});
|
});
|
||||||
console.log(`File created for season: ${filename}`);
|
console.log(`File created for season: ${filename}`);
|
||||||
}).catch();
|
})
|
||||||
|
.catch();
|
||||||
}
|
}
|
||||||
|
|
||||||
async getEpisodenMedia(episode) {
|
async getEpisodenMedia(episode) {
|
||||||
@@ -150,25 +182,33 @@ class MediaManager {
|
|||||||
const file = await _mediaDownloaderService.downloadFile(url);
|
const file = await _mediaDownloaderService.downloadFile(url);
|
||||||
|
|
||||||
const uniqueFilename = uuidv4();
|
const uniqueFilename = uuidv4();
|
||||||
const extension = episode.still_path.split('.').pop();
|
const extension = episode.still_path.split(".").pop();
|
||||||
const filename = `${uniqueFilename}.${extension}`;
|
const filename = `${uniqueFilename}.${extension}`;
|
||||||
|
|
||||||
const dataPath = _configService.getSettings().userDataPath;
|
const dataPath = _configService.getSettings().userDataPath;
|
||||||
const fullFilePath = path.join(dataPath, 'images', 'episodes', 'stills', filename)
|
const fullFilePath = path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"episodes",
|
||||||
|
"stills",
|
||||||
|
filename,
|
||||||
|
);
|
||||||
|
|
||||||
_storageService.storeFile(file, fullFilePath).then(async () => {
|
_storageService
|
||||||
|
.storeFile(file, fullFilePath)
|
||||||
|
.then(async () => {
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'episode',
|
mediaable: "episode",
|
||||||
mediaableId: episode.id,
|
mediaableId: episode.id,
|
||||||
type: 'still',
|
type: "still",
|
||||||
path: filename,
|
path: filename,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true,
|
||||||
});
|
});
|
||||||
console.log(`File created for episode: ${filename}`);
|
console.log(`File created for episode: ${filename}`);
|
||||||
}).catch();
|
})
|
||||||
|
.catch();
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new MediaManager();
|
module.exports = new MediaManager();
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
const path = require('path');
|
const path = require("path");
|
||||||
const sharp = require('sharp');
|
const sharp = require("sharp");
|
||||||
|
|
||||||
const configService = require('./configService');
|
const configService = require("./configService");
|
||||||
|
|
||||||
const _configService = configService;
|
const _configService = configService;
|
||||||
|
|
||||||
class MediaOptimizerService {
|
class MediaOptimizerService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!MediaOptimizerService.instance) {
|
if (!MediaOptimizerService.instance) {
|
||||||
MediaOptimizerService.instance = this;
|
MediaOptimizerService.instance = this;
|
||||||
@@ -15,29 +14,44 @@ class MediaOptimizerService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// todo rename this function to prepareAndGeneratePreview
|
// todo rename this function to prepareAndGeneratePreview
|
||||||
doGeneratePreview(fileCategory, fileType, originalFileName, previewWidth = 0, previewQuality = 80) {
|
doGeneratePreview(
|
||||||
|
fileCategory,
|
||||||
|
fileType,
|
||||||
|
originalFileName,
|
||||||
|
previewWidth = 0,
|
||||||
|
previewQuality = 80,
|
||||||
|
) {
|
||||||
const dataPath = _configService.getSettings().userDataPath;
|
const dataPath = _configService.getSettings().userDataPath;
|
||||||
const mediaPath = path.join(dataPath, 'images', fileCategory, fileType);
|
const mediaPath = path.join(dataPath, "images", fileCategory, fileType);
|
||||||
|
|
||||||
const originalPath = path.join(mediaPath, originalFileName);
|
const originalPath = path.join(mediaPath, originalFileName);
|
||||||
|
|
||||||
const fileNameWithoutExt = originalFileName.split('.')[0];
|
const fileNameWithoutExt = originalFileName.split(".")[0];
|
||||||
const previewFileName = fileNameWithoutExt + '_preview.jpg';
|
const previewFileName = fileNameWithoutExt + "_preview.jpg";
|
||||||
const previewPath = path.join(mediaPath, previewFileName);
|
const previewPath = path.join(mediaPath, previewFileName);
|
||||||
|
|
||||||
if (previewWidth == 0) {
|
if (previewWidth == 0) {
|
||||||
previewWidth = 342; // ? poster
|
previewWidth = 342; // ? poster
|
||||||
if (fileType == 'backdrops') previewWidth = 780;
|
if (fileType == "backdrops") previewWidth = 780;
|
||||||
if (fileType == 'logos') previewWidth = 300;
|
if (fileType == "logos") previewWidth = 300;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (fileType == 'logos') {
|
if (fileType == "logos") {
|
||||||
return this.generatePreview(originalPath, previewPath.replace('.jpg', '.png'), previewWidth);
|
return this.generatePreview(
|
||||||
|
originalPath,
|
||||||
|
previewPath.replace(".jpg", ".png"),
|
||||||
|
previewWidth,
|
||||||
|
);
|
||||||
// return sharp(originalPath)
|
// return sharp(originalPath)
|
||||||
// .resize({ width: previewWidth })
|
// .resize({ width: previewWidth })
|
||||||
// .toFile(previewPath.replace('.jpg', '.png'));
|
// .toFile(previewPath.replace('.jpg', '.png'));
|
||||||
} else {
|
} else {
|
||||||
return this.generatePreview(originalPath, previewPath, previewWidth, previewQuality);
|
return this.generatePreview(
|
||||||
|
originalPath,
|
||||||
|
previewPath,
|
||||||
|
previewWidth,
|
||||||
|
previewQuality,
|
||||||
|
);
|
||||||
// return sharp(originalPath)
|
// return sharp(originalPath)
|
||||||
// .resize({ width: previewWidth })
|
// .resize({ width: previewWidth })
|
||||||
// .jpeg({ quality: previewQuality })
|
// .jpeg({ quality: previewQuality })
|
||||||
@@ -45,13 +59,17 @@ class MediaOptimizerService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
generatePreview(originalPath, previewPath, previewWidth, previewQuality = 80) {
|
generatePreview(
|
||||||
|
originalPath,
|
||||||
|
previewPath,
|
||||||
|
previewWidth,
|
||||||
|
previewQuality = 80,
|
||||||
|
) {
|
||||||
return sharp(originalPath)
|
return sharp(originalPath)
|
||||||
.resize({ width: previewWidth })
|
.resize({ width: previewWidth })
|
||||||
.jpeg({ quality: previewQuality })
|
.jpeg({ quality: previewQuality })
|
||||||
.toFile(previewPath);
|
.toFile(previewPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new MediaOptimizerService();
|
module.exports = new MediaOptimizerService();
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
const Media = require("../models/Media");
|
const Media = require("../models/Media");
|
||||||
|
|
||||||
class MediaService {
|
class MediaService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!MediaService.instance) {
|
if (!MediaService.instance) {
|
||||||
MediaService.instance = this;
|
MediaService.instance = this;
|
||||||
@@ -14,7 +13,6 @@ class MediaService {
|
|||||||
|
|
||||||
return media;
|
return media;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new MediaService();
|
module.exports = new MediaService();
|
||||||
@@ -1,23 +1,23 @@
|
|||||||
const moment = require('../../utils/moment.js');
|
const moment = require("../../utils/moment.js");
|
||||||
|
|
||||||
const { fetchSeasonData, fetchEntryData } = require('../tmdbService.js');
|
const { fetchSeasonData, fetchEntryData } = require("../tmdbService.js");
|
||||||
const { getEntryMedia, doGeneratePreview } = require('../mediaService.js');
|
const { getEntryMedia, doGeneratePreview } = require("../mediaService.js");
|
||||||
const { logToFile } = require('../logService.js');
|
const { logToFile } = require("../logService.js");
|
||||||
|
|
||||||
const NotFoundError = require('../../errors/NotFoundError.js');
|
const NotFoundError = require("../../errors/NotFoundError.js");
|
||||||
const InternalServerError = require('../../errors/InternalServerError.js');
|
const InternalServerError = require("../../errors/InternalServerError.js");
|
||||||
|
|
||||||
const { ValidationError, Op } = require('sequelize');
|
const { ValidationError, Op } = require("sequelize");
|
||||||
const Collection = require('../../models/Collection.js');
|
const Collection = require("../../models/Collection.js");
|
||||||
const Entry = require('../../models/Entry.js')
|
const Entry = require("../../models/Entry.js");
|
||||||
const EntryId = require('../../models/EntryId.js')
|
const EntryId = require("../../models/EntryId.js");
|
||||||
const EntryRating = require('../../models/EntryRating.js');
|
const EntryRating = require("../../models/EntryRating.js");
|
||||||
const Season = require('../../models/Season.js');
|
const Season = require("../../models/Season.js");
|
||||||
const EntryGenre = require('../../models/EntryGenre.js');
|
const EntryGenre = require("../../models/EntryGenre.js");
|
||||||
const EntrySeen = require('../../models/EntrySeen.js');
|
const EntrySeen = require("../../models/EntrySeen.js");
|
||||||
const Episode = require('../../models/Episode.js');
|
const Episode = require("../../models/Episode.js");
|
||||||
const Media = require('../../models/Media.js');
|
const Media = require("../../models/Media.js");
|
||||||
const Genre = require('../../models/Genre.js');
|
const Genre = require("../../models/Genre.js");
|
||||||
|
|
||||||
async function saveEntry(data) {
|
async function saveEntry(data) {
|
||||||
try {
|
try {
|
||||||
@@ -35,7 +35,10 @@ async function saveEntry(data) {
|
|||||||
|
|
||||||
tagline: data.tagline || null,
|
tagline: data.tagline || null,
|
||||||
storyline: data.overview,
|
storyline: data.overview,
|
||||||
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
country:
|
||||||
|
data.production_countries.length > 0
|
||||||
|
? data.production_countries[0].name
|
||||||
|
: null,
|
||||||
|
|
||||||
is_tvseries: is_tvseries,
|
is_tvseries: is_tvseries,
|
||||||
watchlist: true,
|
watchlist: true,
|
||||||
@@ -46,7 +49,7 @@ async function saveEntry(data) {
|
|||||||
poster_path: data.poster_path,
|
poster_path: data.poster_path,
|
||||||
banner_path: data.backdrop_path,
|
banner_path: data.backdrop_path,
|
||||||
|
|
||||||
last_fetch: new Date()
|
last_fetch: new Date(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const savedEntry = await movie.save();
|
const savedEntry = await movie.save();
|
||||||
@@ -62,8 +65,8 @@ async function saveEntry(data) {
|
|||||||
data.genres.forEach(async (genre) => {
|
data.genres.forEach(async (genre) => {
|
||||||
await EntryGenre.create({
|
await EntryGenre.create({
|
||||||
genre_id: genre.id,
|
genre_id: genre.id,
|
||||||
entry_id: savedEntry.id
|
entry_id: savedEntry.id,
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? ratings
|
// ? ratings
|
||||||
@@ -95,7 +98,7 @@ async function saveEntry(data) {
|
|||||||
|
|
||||||
poster_path: seasonData.poster_path,
|
poster_path: seasonData.poster_path,
|
||||||
banner_path: null,
|
banner_path: null,
|
||||||
})
|
});
|
||||||
|
|
||||||
// * episodes
|
// * episodes
|
||||||
let episodes = [];
|
let episodes = [];
|
||||||
@@ -122,43 +125,41 @@ async function saveEntry(data) {
|
|||||||
|
|
||||||
// TODO fetch cast
|
// TODO fetch cast
|
||||||
|
|
||||||
savedSeason.setDataValue('episodes', episodes);
|
savedSeason.setDataValue("episodes", episodes);
|
||||||
seasons.push(savedSeason)
|
seasons.push(savedSeason);
|
||||||
}
|
}
|
||||||
savedEntry.setDataValue('seasons', seasons);
|
savedEntry.setDataValue("seasons", seasons);
|
||||||
}
|
}
|
||||||
// + end of: seasons & episodes for tv series
|
// + end of: seasons & episodes for tv series
|
||||||
|
|
||||||
// ? cast
|
// ? cast
|
||||||
|
|
||||||
|
|
||||||
// ? media
|
// ? media
|
||||||
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
|
const downloadedImages = await getEntryMedia(data.id, is_tvseries);
|
||||||
// console.log(`entry service, downloaded images: `, downloadedImages)
|
// console.log(`entry service, downloaded images: `, downloadedImages)
|
||||||
for (const image of downloadedImages) {
|
for (const image of downloadedImages) {
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'entry',
|
mediaable: "entry",
|
||||||
mediaableId: savedEntry.id,
|
mediaableId: savedEntry.id,
|
||||||
type: image.type,
|
type: image.type,
|
||||||
path: image.path,
|
path: image.path,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
doGeneratePreview('entries', image.type + 's', image.path);
|
doGeneratePreview("entries", image.type + "s", image.path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const currentGenresNames = await data.genres.map((genre) => genre.name);
|
||||||
|
|
||||||
const currentGenresNames = await data.genres.map(genre => genre.name);
|
savedEntry.setDataValue("entryId", ids);
|
||||||
|
savedEntry.setDataValue("entryRating", ratings);
|
||||||
savedEntry.setDataValue('entryId', ids);
|
savedEntry.setDataValue("genres", currentGenresNames);
|
||||||
savedEntry.setDataValue('entryRating', ratings);
|
|
||||||
savedEntry.setDataValue('genres', currentGenresNames);
|
|
||||||
|
|
||||||
return savedEntry;
|
return savedEntry;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log(`Error saving entry (in entry serive): `, error);
|
console.log(`Error saving entry (in entry serive): `, error);
|
||||||
return null
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,7 +172,10 @@ async function updateEntry(oldEntry, data) {
|
|||||||
|
|
||||||
tagline: data.tagline || null,
|
tagline: data.tagline || null,
|
||||||
storyline: data.overview,
|
storyline: data.overview,
|
||||||
country: data.production_countries.length > 0 ? data.production_countries[0].name : null,
|
country:
|
||||||
|
data.production_countries.length > 0
|
||||||
|
? data.production_countries[0].name
|
||||||
|
: null,
|
||||||
|
|
||||||
status: data.status,
|
status: data.status,
|
||||||
|
|
||||||
@@ -190,11 +194,11 @@ async function updateEntry(oldEntry, data) {
|
|||||||
|
|
||||||
// update ratings
|
// update ratings
|
||||||
const ratings = await oldEntry.entryRating.update({
|
const ratings = await oldEntry.entryRating.update({
|
||||||
tmdb_rating: data.vote_average
|
tmdb_rating: data.vote_average,
|
||||||
});
|
});
|
||||||
|
|
||||||
// update genres
|
// update genres
|
||||||
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
|
||||||
let currentGenresNames = [];
|
let currentGenresNames = [];
|
||||||
data.genres.forEach(async (genre) => {
|
data.genres.forEach(async (genre) => {
|
||||||
// add genres names to an array so it can be returned with the entry object
|
// add genres names to an array so it can be returned with the entry object
|
||||||
@@ -206,12 +210,14 @@ async function updateEntry(oldEntry, data) {
|
|||||||
// otherwise assign the genre to the entry
|
// otherwise assign the genre to the entry
|
||||||
await EntryGenre.create({
|
await EntryGenre.create({
|
||||||
genre_id: genre.id,
|
genre_id: genre.id,
|
||||||
entry_id: savedEntry.id
|
entry_id: savedEntry.id,
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// fetch entry-seens
|
// fetch entry-seens
|
||||||
const entrySeens = await EntrySeen.findAll({ where: { entry_id: oldEntry.id } });
|
const entrySeens = await EntrySeen.findAll({
|
||||||
|
where: { entry_id: oldEntry.id },
|
||||||
|
});
|
||||||
|
|
||||||
// TODO: refrech seasons
|
// TODO: refrech seasons
|
||||||
if (oldEntry.is_tvseries) {
|
if (oldEntry.is_tvseries) {
|
||||||
@@ -224,8 +230,8 @@ async function updateEntry(oldEntry, data) {
|
|||||||
// Fetch existing season if it exists (using tmdb_id)
|
// Fetch existing season if it exists (using tmdb_id)
|
||||||
let existingSeason = await Season.findOne({
|
let existingSeason = await Season.findOne({
|
||||||
where: {
|
where: {
|
||||||
tmdb_id: season.id
|
tmdb_id: season.id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// If the season exists, update it; otherwise, create a new season
|
// If the season exists, update it; otherwise, create a new season
|
||||||
@@ -269,7 +275,7 @@ async function updateEntry(oldEntry, data) {
|
|||||||
let existingEpisode = await Episode.findOne({
|
let existingEpisode = await Episode.findOne({
|
||||||
where: {
|
where: {
|
||||||
tmdb_id: episode.id,
|
tmdb_id: episode.id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// If the episode exists, update it; otherwise, create a new episode
|
// If the episode exists, update it; otherwise, create a new episode
|
||||||
@@ -309,19 +315,18 @@ async function updateEntry(oldEntry, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Update the episodes of the current season
|
// Update the episodes of the current season
|
||||||
existingSeason.setDataValue('episodes', updatedEpisodes);
|
existingSeason.setDataValue("episodes", updatedEpisodes);
|
||||||
updatedSeasons.push(existingSeason);
|
updatedSeasons.push(existingSeason);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the seasons of the movie
|
// Update the seasons of the movie
|
||||||
savedEntry.setDataValue('seasons', updatedSeasons);
|
savedEntry.setDataValue("seasons", updatedSeasons);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
savedEntry.setDataValue("entryId", ids);
|
||||||
savedEntry.setDataValue('entryId', ids);
|
savedEntry.setDataValue("entryRating", ratings);
|
||||||
savedEntry.setDataValue('entryRating', ratings);
|
savedEntry.setDataValue("genres", currentGenresNames);
|
||||||
savedEntry.setDataValue('genres', currentGenresNames);
|
savedEntry.setDataValue("entrySeen", entrySeens);
|
||||||
savedEntry.setDataValue('entrySeen', entrySeens);
|
|
||||||
|
|
||||||
return savedEntry;
|
return savedEntry;
|
||||||
}
|
}
|
||||||
@@ -332,25 +337,24 @@ async function refrechEntry(entryId) {
|
|||||||
// ! note: the includes are required for the update
|
// ! note: the includes are required for the update
|
||||||
const oldEntry = await Entry.findByPk(entryId, {
|
const oldEntry = await Entry.findByPk(entryId, {
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
{ model: EntryRating, as: "entryRating" },
|
||||||
{ model: EntrySeen, as: 'entrySeen' },
|
{ model: EntrySeen, as: "entrySeen" },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: "seasons" },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: "medias" },
|
||||||
{
|
{
|
||||||
model: Collection, as: 'collections',
|
model: Collection,
|
||||||
include: [
|
as: "collections",
|
||||||
{ model: Media, as: 'medias' }
|
include: [{ model: Media, as: "medias" }],
|
||||||
]
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: "genres",
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
order: [
|
order: [
|
||||||
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
|
[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"], // Order the entry-seen list
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!oldEntry) {
|
if (!oldEntry) {
|
||||||
@@ -358,7 +362,10 @@ async function refrechEntry(entryId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ? getting new data from TMDB
|
// ? getting new data from TMDB
|
||||||
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
const entryData = await fetchEntryData(
|
||||||
|
oldEntry.entryId.tmdb_id,
|
||||||
|
oldEntry.is_tvseries,
|
||||||
|
);
|
||||||
if (entryData == null) {
|
if (entryData == null) {
|
||||||
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
||||||
}
|
}
|
||||||
@@ -373,14 +380,17 @@ async function refrechEntry(entryId) {
|
|||||||
|
|
||||||
tagline: entryData.tagline || null,
|
tagline: entryData.tagline || null,
|
||||||
storyline: entryData.overview,
|
storyline: entryData.overview,
|
||||||
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
|
country:
|
||||||
|
entryData.production_countries.length > 0
|
||||||
|
? entryData.production_countries[0].name
|
||||||
|
: null,
|
||||||
|
|
||||||
status: entryData.status,
|
status: entryData.status,
|
||||||
|
|
||||||
poster_path: entryData.poster_path,
|
poster_path: entryData.poster_path,
|
||||||
banner_path: entryData.backdrop_path,
|
banner_path: entryData.backdrop_path,
|
||||||
|
|
||||||
last_fetch: new Date()
|
last_fetch: new Date(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const savedEntry = await oldEntry.update(newData);
|
const savedEntry = await oldEntry.update(newData);
|
||||||
@@ -393,11 +403,11 @@ async function refrechEntry(entryId) {
|
|||||||
|
|
||||||
// * updating ratings
|
// * updating ratings
|
||||||
await oldEntry.entryRating.update({
|
await oldEntry.entryRating.update({
|
||||||
tmdb_rating: entryData.vote_average
|
tmdb_rating: entryData.vote_average,
|
||||||
});
|
});
|
||||||
|
|
||||||
// * updating genres
|
// * updating genres
|
||||||
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
|
||||||
entryData.genres.forEach(async (genre) => {
|
entryData.genres.forEach(async (genre) => {
|
||||||
// if the entry already has this genre then skip
|
// if the entry already has this genre then skip
|
||||||
if (currentGenresIds.includes(genre.id)) return;
|
if (currentGenresIds.includes(genre.id)) return;
|
||||||
@@ -405,10 +415,9 @@ async function refrechEntry(entryId) {
|
|||||||
// otherwise assign the genre to the entry
|
// otherwise assign the genre to the entry
|
||||||
await EntryGenre.create({
|
await EntryGenre.create({
|
||||||
genre_id: genre.id,
|
genre_id: genre.id,
|
||||||
entry_id: savedEntry.id
|
entry_id: savedEntry.id,
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// * For TV-Series (Seasons & Episodes)
|
// * For TV-Series (Seasons & Episodes)
|
||||||
if (oldEntry.is_tvseries) {
|
if (oldEntry.is_tvseries) {
|
||||||
@@ -418,13 +427,16 @@ async function refrechEntry(entryId) {
|
|||||||
// * Update or insert seasons for the entry
|
// * Update or insert seasons for the entry
|
||||||
for (const season of entryData.seasons) {
|
for (const season of entryData.seasons) {
|
||||||
// fetch new season data from tmdb
|
// fetch new season data from tmdb
|
||||||
let seasonData = await fetchSeasonData(entryData.id, season.season_number);
|
let seasonData = await fetchSeasonData(
|
||||||
|
entryData.id,
|
||||||
|
season.season_number,
|
||||||
|
);
|
||||||
|
|
||||||
// Fetch existing season if it exists (using tmdb_id)
|
// Fetch existing season if it exists (using tmdb_id)
|
||||||
let existingSeason = await Season.findOne({
|
let existingSeason = await Season.findOne({
|
||||||
where: {
|
where: {
|
||||||
tmdb_id: season.id
|
tmdb_id: season.id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// If the season exists, update it; otherwise, create a new season
|
// If the season exists, update it; otherwise, create a new season
|
||||||
@@ -464,7 +476,7 @@ async function refrechEntry(entryId) {
|
|||||||
let existingEpisode = await Episode.findOne({
|
let existingEpisode = await Episode.findOne({
|
||||||
where: {
|
where: {
|
||||||
tmdb_id: episode.id,
|
tmdb_id: episode.id,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// If the episode exists, update it; otherwise, create a new episode
|
// If the episode exists, update it; otherwise, create a new episode
|
||||||
@@ -512,12 +524,12 @@ async function refrechEntry(entryId) {
|
|||||||
|
|
||||||
// ? count media by type
|
// ? count media by type
|
||||||
let availableMedia = {
|
let availableMedia = {
|
||||||
'posters': 0,
|
posters: 0,
|
||||||
'logos': 0,
|
logos: 0,
|
||||||
'backdrops': 0
|
backdrops: 0,
|
||||||
};
|
};
|
||||||
for (let i = 0; i < oldEntry.medias.length; i++) {
|
for (let i = 0; i < oldEntry.medias.length; i++) {
|
||||||
availableMedia[oldEntry.medias[i].type + 's'] += 1;
|
availableMedia[oldEntry.medias[i].type + "s"] += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? if the count of a media type == 0, the add the type to mediaToGet
|
// ? if the count of a media type == 0, the add the type to mediaToGet
|
||||||
@@ -528,26 +540,32 @@ async function refrechEntry(entryId) {
|
|||||||
|
|
||||||
let downloadedImages;
|
let downloadedImages;
|
||||||
if (mediaToGet.length != 0) {
|
if (mediaToGet.length != 0) {
|
||||||
downloadedImages = await getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
|
downloadedImages = await getEntryMedia(
|
||||||
|
entryData.id,
|
||||||
|
oldEntry.is_tvseries,
|
||||||
|
mediaToGet,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (downloadedImages) {
|
if (downloadedImages) {
|
||||||
for (const image of downloadedImages) {
|
for (const image of downloadedImages) {
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'entry',
|
mediaable: "entry",
|
||||||
mediaableId: oldEntry.id,
|
mediaableId: oldEntry.id,
|
||||||
type: image.type,
|
type: image.type,
|
||||||
path: image.path,
|
path: image.path,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? fetch collection
|
// ? fetch collection
|
||||||
if (entryData.belongs_to_collection) {
|
if (entryData.belongs_to_collection) {
|
||||||
const collectionService = require('../collectionService.js');
|
const collectionService = require("../collectionService.js");
|
||||||
await collectionService.createOrUpdateCollection(entryData.belongs_to_collection.id);
|
await collectionService.createOrUpdateCollection(
|
||||||
|
entryData.belongs_to_collection.id,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// + end of: refrech logic
|
// + end of: refrech logic
|
||||||
@@ -573,33 +591,32 @@ async function refrechEntry(entryId) {
|
|||||||
|
|
||||||
const updatedEntry = await Entry.findByPk(entryId, {
|
const updatedEntry = await Entry.findByPk(entryId, {
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
{ model: EntryRating, as: "entryRating" },
|
||||||
{ model: EntrySeen, as: 'entrySeen' },
|
{ model: EntrySeen, as: "entrySeen" },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: "seasons" },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: "medias" },
|
||||||
{
|
{
|
||||||
model: Collection, as: 'collections',
|
model: Collection,
|
||||||
include: [
|
as: "collections",
|
||||||
{ model: Media, as: 'medias' }
|
include: [{ model: Media, as: "medias" }],
|
||||||
]
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: "genres",
|
||||||
attributes: ['name'], // Only fetch the genre ID
|
attributes: ["name"], // Only fetch the genre ID
|
||||||
through: {
|
through: {
|
||||||
attributes: [] // Do not fetch any attributes from the join table
|
attributes: [], // Do not fetch any attributes from the join table
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
order: [
|
order: [
|
||||||
[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC'] // Order the entry-seen list
|
[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"], // Order the entry-seen list
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const plainEntry = updatedEntry.get({ plain: true });
|
const plainEntry = updatedEntry.get({ plain: true });
|
||||||
plainEntry.genres = plainEntry.genres.map(genre => genre.name);
|
plainEntry.genres = plainEntry.genres.map((genre) => genre.name);
|
||||||
|
|
||||||
return plainEntry;
|
return plainEntry;
|
||||||
}
|
}
|
||||||
@@ -607,19 +624,16 @@ async function refrechEntry(entryId) {
|
|||||||
/** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today
|
/** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today
|
||||||
*/
|
*/
|
||||||
async function SyncSeriesData() {
|
async function SyncSeriesData() {
|
||||||
const today = moment().format('YYYY-MM-DD');
|
const today = moment().format("YYYY-MM-DD");
|
||||||
const entries = await Entry.findAll({
|
const entries = await Entry.findAll({
|
||||||
where: {
|
where: {
|
||||||
is_tvseries: true,
|
is_tvseries: true,
|
||||||
autoSync: true,
|
autoSync: true,
|
||||||
last_fetch: {
|
last_fetch: {
|
||||||
[Op.ne]: today
|
[Op.ne]: today,
|
||||||
},
|
},
|
||||||
status: {
|
status: {
|
||||||
[Op.notIn]: [
|
[Op.notIn]: ["Ended", "Canceled"],
|
||||||
'Ended',
|
|
||||||
'Canceled'
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -627,7 +641,7 @@ async function SyncSeriesData() {
|
|||||||
logToFile(`Started syncing ${entries.length} Tv-Series`);
|
logToFile(`Started syncing ${entries.length} Tv-Series`);
|
||||||
|
|
||||||
const results = await Promise.all(
|
const results = await Promise.all(
|
||||||
entries.map(entry => SyncSerieData(entry.id))
|
entries.map((entry) => SyncSerieData(entry.id)),
|
||||||
);
|
);
|
||||||
logToFile(`Syncing Tv-Series Finished`);
|
logToFile(`Syncing Tv-Series Finished`);
|
||||||
|
|
||||||
@@ -637,30 +651,31 @@ async function SyncSeriesData() {
|
|||||||
async function SyncSerieData(entryId) {
|
async function SyncSerieData(entryId) {
|
||||||
const oldEntry = await Entry.findByPk(entryId, {
|
const oldEntry = await Entry.findByPk(entryId, {
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
{ model: EntryRating, as: "entryRating" },
|
||||||
{ model: EntrySeen, as: 'entrySeen' },
|
{ model: EntrySeen, as: "entrySeen" },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: "seasons" },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: "medias" },
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: "genres",
|
||||||
attributes: ['id'],
|
attributes: ["id"],
|
||||||
through: {
|
through: {
|
||||||
attributes: []
|
attributes: [],
|
||||||
}
|
},
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`)
|
logToFile(`Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`);
|
||||||
|
|
||||||
if (!oldEntry)
|
if (!oldEntry) throw NotFoundError("Entry Not Found");
|
||||||
throw NotFoundError('Entry Not Found');
|
const entryData = await fetchEntryData(
|
||||||
const entryData = await fetchEntryData(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
oldEntry.entryId.tmdb_id,
|
||||||
|
oldEntry.is_tvseries,
|
||||||
|
);
|
||||||
|
|
||||||
if (!entryData)
|
if (!entryData) throw new ValidationError(`Couldn't Fetch Entry Data`);
|
||||||
throw new ValidationError(`Couldn't Fetch Entry Data`);
|
|
||||||
|
|
||||||
// ! 1 - Normal Data
|
// ! 1 - Normal Data
|
||||||
let newData = {
|
let newData = {
|
||||||
@@ -671,14 +686,17 @@ async function SyncSerieData(entryId) {
|
|||||||
|
|
||||||
tagline: entryData.tagline || null,
|
tagline: entryData.tagline || null,
|
||||||
storyline: entryData.overview,
|
storyline: entryData.overview,
|
||||||
country: entryData.production_countries.length > 0 ? entryData.production_countries[0].name : null,
|
country:
|
||||||
|
entryData.production_countries.length > 0
|
||||||
|
? entryData.production_countries[0].name
|
||||||
|
: null,
|
||||||
|
|
||||||
status: entryData.status,
|
status: entryData.status,
|
||||||
|
|
||||||
poster_path: entryData.poster_path,
|
poster_path: entryData.poster_path,
|
||||||
banner_path: entryData.backdrop_path,
|
banner_path: entryData.backdrop_path,
|
||||||
|
|
||||||
last_fetch: new Date()
|
last_fetch: new Date(),
|
||||||
};
|
};
|
||||||
|
|
||||||
await oldEntry.update(newData);
|
await oldEntry.update(newData);
|
||||||
@@ -691,30 +709,39 @@ async function SyncSerieData(entryId) {
|
|||||||
|
|
||||||
// ! 3 - Ratings
|
// ! 3 - Ratings
|
||||||
await oldEntry.entryRating.update({
|
await oldEntry.entryRating.update({
|
||||||
tmdb_rating: entryData.vote_average
|
tmdb_rating: entryData.vote_average,
|
||||||
});
|
});
|
||||||
|
|
||||||
// ! 4 - Genres
|
// ! 4 - Genres
|
||||||
const currentGenresIds = oldEntry.genres.map(genre => genre.id);
|
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
|
||||||
entryData.genres.forEach(async (genre) => {
|
entryData.genres.forEach(async (genre) => {
|
||||||
// ? only assing the genre if its not already asigned
|
// ? only assing the genre if its not already asigned
|
||||||
if (!currentGenresIds.includes(genre.id)) {
|
if (!currentGenresIds.includes(genre.id)) {
|
||||||
await EntryGenre.create({
|
await EntryGenre.create({
|
||||||
genre_id: genre.id,
|
genre_id: genre.id,
|
||||||
entry_id: oldEntry.id
|
entry_id: oldEntry.id,
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ! 5 - Seasons
|
// ! 5 - Seasons
|
||||||
// ? only update the last seasons available + season 0 (specials)
|
// ? only update the last seasons available + season 0 (specials)
|
||||||
if (oldEntry.is_tvseries) {
|
if (oldEntry.is_tvseries) {
|
||||||
const latestAvailableSeason = await Math.max(...oldEntry.seasons.map(s => s.season_number));
|
const latestAvailableSeason = await Math.max(
|
||||||
|
...oldEntry.seasons.map((s) => s.season_number),
|
||||||
|
);
|
||||||
for (const season of entryData.seasons) {
|
for (const season of entryData.seasons) {
|
||||||
if (season.season_number != 0 && season.season_number != latestAvailableSeason) continue;
|
if (
|
||||||
|
season.season_number != 0 &&
|
||||||
|
season.season_number != latestAvailableSeason
|
||||||
|
)
|
||||||
|
continue;
|
||||||
|
|
||||||
// ? fetch new season data from tmdb
|
// ? fetch new season data from tmdb
|
||||||
let seasonData = await fetchSeasonData(oldEntry.entryId.tmdb_id, season.season_number);
|
let seasonData = await fetchSeasonData(
|
||||||
|
oldEntry.entryId.tmdb_id,
|
||||||
|
season.season_number,
|
||||||
|
);
|
||||||
|
|
||||||
// * find or create the season
|
// * find or create the season
|
||||||
const [oldSeason, createdSeason] = await Season.findOrCreate({
|
const [oldSeason, createdSeason] = await Season.findOrCreate({
|
||||||
@@ -731,7 +758,7 @@ async function SyncSerieData(entryId) {
|
|||||||
tmdb_rating: seasonData.vote_average,
|
tmdb_rating: seasonData.vote_average,
|
||||||
poster_path: seasonData.poster_path,
|
poster_path: seasonData.poster_path,
|
||||||
banner_path: null,
|
banner_path: null,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? if the season already exist then just update it with new data
|
// ? if the season already exist then just update it with new data
|
||||||
@@ -769,7 +796,7 @@ async function SyncSerieData(entryId) {
|
|||||||
air_date: episode.air_date,
|
air_date: episode.air_date,
|
||||||
tmdb_rating: episode.vote_average,
|
tmdb_rating: episode.vote_average,
|
||||||
still_path: episode.still_path,
|
still_path: episode.still_path,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? if the episode already exist then just update it with new data
|
// ? if the episode already exist then just update it with new data
|
||||||
@@ -802,4 +829,4 @@ module.exports = {
|
|||||||
refrechEntry,
|
refrechEntry,
|
||||||
SyncSeriesData,
|
SyncSeriesData,
|
||||||
SyncSerieData,
|
SyncSerieData,
|
||||||
}
|
};
|
||||||
@@ -1,43 +1,29 @@
|
|||||||
const Entry = require('../../models/Entry.js')
|
const Entry = require("../../models/Entry.js");
|
||||||
const EntryId = require('../../models/EntryId.js')
|
const EntryId = require("../../models/EntryId.js");
|
||||||
const EntryRating = require('../../models/EntryRating.js');
|
const EntryRating = require("../../models/EntryRating.js");
|
||||||
const Season = require('../../models/Season.js');
|
const Season = require("../../models/Season.js");
|
||||||
const EntryGenre = require('../../models/EntryGenre.js');
|
const EntryGenre = require("../../models/EntryGenre.js");
|
||||||
const EntrySeen = require('../../models/EntrySeen.js');
|
const EntrySeen = require("../../models/EntrySeen.js");
|
||||||
|
|
||||||
async function saveSeason(entryId) {
|
async function saveSeason(entryId) {
|
||||||
// fetch data from tmdb
|
// fetch data from tmdb
|
||||||
|
|
||||||
// save season to db
|
// save season to db
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function updateSeason(seasonId) {
|
async function updateSeason(seasonId) {
|
||||||
// fetch season form db
|
// fetch season form db
|
||||||
|
|
||||||
// fetch data from tmdb
|
// fetch data from tmdb
|
||||||
|
|
||||||
// update fields
|
// update fields
|
||||||
|
|
||||||
// save
|
// save
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function getSeason() {}
|
||||||
|
|
||||||
async function getSeason() {
|
async function deleteSeason() {}
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async function deleteSeason() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
saveSeason,
|
saveSeason,
|
||||||
updateSeason,
|
updateSeason,
|
||||||
getSeason,
|
getSeason,
|
||||||
deleteSeason,
|
deleteSeason,
|
||||||
}
|
};
|
||||||
@@ -1,67 +1,64 @@
|
|||||||
const multer = require('multer');
|
const multer = require("multer");
|
||||||
const { v4: uuidv4 } = require('uuid');
|
const { v4: uuidv4 } = require("uuid");
|
||||||
const path = require('path');
|
const path = require("path");
|
||||||
const configService = require('./configService');
|
const configService = require("./configService");
|
||||||
|
|
||||||
// ? users
|
// ? users
|
||||||
const entryPicturesUpload = multer({
|
const entryPicturesUpload = multer({
|
||||||
storage:
|
storage: multer.diskStorage({
|
||||||
multer.diskStorage({
|
|
||||||
destination: function (req, file, cb) {
|
destination: function (req, file, cb) {
|
||||||
let folder = 'posters';
|
let folder = "posters";
|
||||||
if (file.fieldname == 'backdrop') folder = 'backdrops';
|
if (file.fieldname == "backdrop") folder = "backdrops";
|
||||||
if (file.fieldname == 'logo') folder = 'logos';
|
if (file.fieldname == "logo") folder = "logos";
|
||||||
|
|
||||||
const dataPath = configService.getSettings().userDataPath;
|
const dataPath = configService.getSettings().userDataPath;
|
||||||
|
|
||||||
cb(null, path.join(dataPath, 'images', 'entries', folder));
|
cb(null, path.join(dataPath, "images", "entries", folder));
|
||||||
},
|
},
|
||||||
filename: function (req, file, cb) {
|
filename: function (req, file, cb) {
|
||||||
const uniqueFilename = uuidv4();
|
const uniqueFilename = uuidv4();
|
||||||
const extension = file.originalname.split('.').pop();
|
const extension = file.originalname.split(".").pop();
|
||||||
cb(null, `${uniqueFilename}.${extension}`);
|
cb(null, `${uniqueFilename}.${extension}`);
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const collectionPicturesUpload = multer({
|
const collectionPicturesUpload = multer({
|
||||||
storage:
|
storage: multer.diskStorage({
|
||||||
multer.diskStorage({
|
|
||||||
destination: function (req, file, cb) {
|
destination: function (req, file, cb) {
|
||||||
let folder = 'posters';
|
let folder = "posters";
|
||||||
if (file.fieldname == 'backdrop') folder = 'backdrops';
|
if (file.fieldname == "backdrop") folder = "backdrops";
|
||||||
if (file.fieldname == 'logo') folder = 'logos';
|
if (file.fieldname == "logo") folder = "logos";
|
||||||
|
|
||||||
const dataPath = configService.getSettings().userDataPath;
|
const dataPath = configService.getSettings().userDataPath;
|
||||||
|
|
||||||
cb(null, path.join(dataPath, 'images', 'collections', folder));
|
cb(null, path.join(dataPath, "images", "collections", folder));
|
||||||
},
|
},
|
||||||
filename: function (req, file, cb) {
|
filename: function (req, file, cb) {
|
||||||
const uniqueFilename = uuidv4();
|
const uniqueFilename = uuidv4();
|
||||||
const extension = file.originalname.split('.').pop();
|
const extension = file.originalname.split(".").pop();
|
||||||
cb(null, `${uniqueFilename}.${extension}`);
|
cb(null, `${uniqueFilename}.${extension}`);
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const peoplePicturesUpload = multer({
|
const peoplePicturesUpload = multer({
|
||||||
storage:
|
storage: multer.diskStorage({
|
||||||
multer.diskStorage({
|
|
||||||
destination: function (req, file, cb) {
|
destination: function (req, file, cb) {
|
||||||
let folder = 'profiles';
|
let folder = "profiles";
|
||||||
const dataPath = configService.getSettings().userDataPath;
|
const dataPath = configService.getSettings().userDataPath;
|
||||||
cb(null, path.join(dataPath, 'images', 'people', folder));
|
cb(null, path.join(dataPath, "images", "people", folder));
|
||||||
},
|
},
|
||||||
filename: function (req, file, cb) {
|
filename: function (req, file, cb) {
|
||||||
const uniqueFilename = uuidv4();
|
const uniqueFilename = uuidv4();
|
||||||
const extension = file.originalname.split('.').pop();
|
const extension = file.originalname.split(".").pop();
|
||||||
cb(null, `${uniqueFilename}.${extension}`);
|
cb(null, `${uniqueFilename}.${extension}`);
|
||||||
}
|
},
|
||||||
})
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
entryPicturesUpload,
|
entryPicturesUpload,
|
||||||
collectionPicturesUpload,
|
collectionPicturesUpload,
|
||||||
peoplePicturesUpload,
|
peoplePicturesUpload,
|
||||||
}
|
};
|
||||||
@@ -8,7 +8,6 @@ const Network = require("../models/Network");
|
|||||||
const Season = require("../models/Season");
|
const Season = require("../models/Season");
|
||||||
|
|
||||||
class NetworkService {
|
class NetworkService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!NetworkService.instance) {
|
if (!NetworkService.instance) {
|
||||||
NetworkService.instance = this;
|
NetworkService.instance = this;
|
||||||
@@ -20,11 +19,12 @@ class NetworkService {
|
|||||||
const networks = await Network.findAll({
|
const networks = await Network.findAll({
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Entry, as: 'entries',
|
model: Entry,
|
||||||
include: { model: Media, as: 'medias' }
|
as: "entries",
|
||||||
}
|
include: { model: Media, as: "medias" },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
order: [['name', 'ASC']]
|
order: [["name", "ASC"]],
|
||||||
});
|
});
|
||||||
|
|
||||||
return networks;
|
return networks;
|
||||||
@@ -32,17 +32,19 @@ class NetworkService {
|
|||||||
|
|
||||||
async getNetworkById(id) {
|
async getNetworkById(id) {
|
||||||
const network = await Network.findByPk(id, {
|
const network = await Network.findByPk(id, {
|
||||||
include: [{
|
|
||||||
model: Entry,
|
|
||||||
as: 'entries',
|
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
model: Entry,
|
||||||
{ model: Season, as: 'seasons' },
|
as: "entries",
|
||||||
{ model: Media, as: 'medias' },
|
include: [
|
||||||
{ model: Genre, as: 'genres' },
|
{ model: EntryId, as: "entryId" },
|
||||||
]
|
{ model: EntryRating, as: "entryRating" },
|
||||||
}]
|
{ model: Season, as: "seasons" },
|
||||||
|
{ model: Media, as: "medias" },
|
||||||
|
{ model: Genre, as: "genres" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
return network;
|
return network;
|
||||||
@@ -61,10 +63,9 @@ class NetworkService {
|
|||||||
logoPath: networkData.logoPath,
|
logoPath: networkData.logoPath,
|
||||||
posterPath: networkData.posterPath,
|
posterPath: networkData.posterPath,
|
||||||
backdropPath: networkData.backdropPath,
|
backdropPath: networkData.backdropPath,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new NetworkService();
|
module.exports = new NetworkService();
|
||||||
@@ -15,7 +15,6 @@ const _mediaDownloaderService = mediaDownloaderService;
|
|||||||
const _mediaOptimizerService = mediaOptimizerService;
|
const _mediaOptimizerService = mediaOptimizerService;
|
||||||
|
|
||||||
class PeopleManager {
|
class PeopleManager {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!PeopleManager.instance) {
|
if (!PeopleManager.instance) {
|
||||||
PeopleManager.instance = this;
|
PeopleManager.instance = this;
|
||||||
@@ -36,7 +35,9 @@ class PeopleManager {
|
|||||||
// * 3 - fetch person data from TMDB
|
// * 3 - fetch person data from TMDB
|
||||||
const personData = await fetchPersonDetails(person.tmdb_id);
|
const personData = await fetchPersonDetails(person.tmdb_id);
|
||||||
if (!personData) {
|
if (!personData) {
|
||||||
throw new InternalServerError(`Couldn't fetch data from TMDB for person with ID: ${id}`);
|
throw new InternalServerError(
|
||||||
|
`Couldn't fetch data from TMDB for person with ID: ${id}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// * 4 - update person with fetched data
|
// * 4 - update person with fetched data
|
||||||
@@ -50,25 +51,29 @@ class PeopleManager {
|
|||||||
// * 5 - download person media
|
// * 5 - download person media
|
||||||
// TODO: peopleManage: update the person media each year
|
// TODO: peopleManage: update the person media each year
|
||||||
if (!person.medias || person.medias.length === 0) {
|
if (!person.medias || person.medias.length === 0) {
|
||||||
const downloadedImages = await _mediaDownloaderService.downloadPersonMedia(person);
|
const downloadedImages =
|
||||||
|
await _mediaDownloaderService.downloadPersonMedia(person);
|
||||||
for (const image of downloadedImages) {
|
for (const image of downloadedImages) {
|
||||||
// ? generating preview
|
// ? generating preview
|
||||||
_mediaOptimizerService.doGeneratePreview('peoples', image.type + 's', image.path).then((result) => {
|
_mediaOptimizerService
|
||||||
|
.doGeneratePreview("peoples", image.type + "s", image.path)
|
||||||
|
.then((result) => {
|
||||||
const msg = `People Service | Generated Person Preview`;
|
const msg = `People Service | Generated Person Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
}).catch((err) => {
|
})
|
||||||
|
.catch((err) => {
|
||||||
const msg = `People Service | Error Generating Person Preview`;
|
const msg = `People Service | Error Generating Person Preview`;
|
||||||
logToFile(msg);
|
logToFile(msg);
|
||||||
logToFile(err);
|
logToFile(err);
|
||||||
});
|
});
|
||||||
// ? inserting data
|
// ? inserting data
|
||||||
await Media.create({
|
await Media.create({
|
||||||
mediaable: 'people',
|
mediaable: "people",
|
||||||
mediaableId: person.id,
|
mediaableId: person.id,
|
||||||
type: image.type,
|
type: image.type,
|
||||||
path: image.path,
|
path: image.path,
|
||||||
isLocal: true,
|
isLocal: true,
|
||||||
isSelected: true
|
isSelected: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -76,7 +81,6 @@ class PeopleManager {
|
|||||||
// * 6 - return the person
|
// * 6 - return the person
|
||||||
return await _peopleService.getPersonById(id);
|
return await _peopleService.getPersonById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new PeopleManager();
|
module.exports = new PeopleManager();
|
||||||
@@ -22,8 +22,8 @@ class PeopleService {
|
|||||||
async getAllPeople(includeCrew = false, { page, limit, search } = {}) {
|
async getAllPeople(includeCrew = false, { page, limit, search } = {}) {
|
||||||
let where = {
|
let where = {
|
||||||
where: {
|
where: {
|
||||||
cast_type: 'cast'
|
cast_type: "cast",
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
if (includeCrew) {
|
if (includeCrew) {
|
||||||
@@ -45,11 +45,11 @@ class PeopleService {
|
|||||||
include: {
|
include: {
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: "entry",
|
as: "entry",
|
||||||
include: { model: Media, as: "medias" }
|
include: { model: Media, as: "medias" },
|
||||||
},
|
},
|
||||||
...where
|
...where,
|
||||||
},
|
},
|
||||||
{ model: Media, as: 'medias' }
|
{ model: Media, as: "medias" },
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,11 +83,11 @@ class PeopleService {
|
|||||||
include: {
|
include: {
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: "entry",
|
as: "entry",
|
||||||
include: { model: Media, as: "medias" }
|
include: { model: Media, as: "medias" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ model: Media, as: 'medias' }
|
{ model: Media, as: "medias" },
|
||||||
]
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!person) {
|
if (!person) {
|
||||||
@@ -107,11 +107,11 @@ class PeopleService {
|
|||||||
include: {
|
include: {
|
||||||
model: Entry,
|
model: Entry,
|
||||||
as: "entry",
|
as: "entry",
|
||||||
include: { model: Media, as: "medias" }
|
include: { model: Media, as: "medias" },
|
||||||
}
|
|
||||||
},
|
},
|
||||||
{ model: Media, as: 'medias' }
|
},
|
||||||
]
|
{ model: Media, as: "medias" },
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
return person;
|
return person;
|
||||||
@@ -120,13 +120,11 @@ class PeopleService {
|
|||||||
async searchPeople(query) {
|
async searchPeople(query) {
|
||||||
const people = await People.findAll({
|
const people = await People.findAll({
|
||||||
where: {
|
where: {
|
||||||
name: { [Op.like]: `%${query}%` }
|
name: { [Op.like]: `%${query}%` },
|
||||||
},
|
},
|
||||||
order: [["popularity", "DESC"]],
|
order: [["popularity", "DESC"]],
|
||||||
limit: 20,
|
limit: 20,
|
||||||
include: [
|
include: [{ model: Media, as: "medias" }],
|
||||||
{ model: Media, as: 'medias' }
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
return people;
|
return people;
|
||||||
}
|
}
|
||||||
@@ -134,7 +132,7 @@ class PeopleService {
|
|||||||
async createPerson(personData) {
|
async createPerson(personData) {
|
||||||
try {
|
try {
|
||||||
const existingPerson = await People.findOne({
|
const existingPerson = await People.findOne({
|
||||||
where: { tmdb_id: personData.tmdb_id }
|
where: { tmdb_id: personData.tmdb_id },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (existingPerson) {
|
if (existingPerson) {
|
||||||
@@ -165,14 +163,16 @@ class PeopleService {
|
|||||||
},
|
},
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Credit, as: 'roles',
|
model: Credit,
|
||||||
|
as: "roles",
|
||||||
include: {
|
include: {
|
||||||
model: Entry, as: 'entry',
|
model: Entry,
|
||||||
include: [{ model: Media, as: 'medias' }]
|
as: "entry",
|
||||||
}
|
include: [{ model: Media, as: "medias" }],
|
||||||
},
|
},
|
||||||
{ model: Media, as: 'medias' }
|
},
|
||||||
]
|
{ model: Media, as: "medias" },
|
||||||
|
],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,7 +235,9 @@ class PeopleService {
|
|||||||
// Fetch person data from TMDB
|
// Fetch person data from TMDB
|
||||||
const personData = await fetchPersonData(tmdbId);
|
const personData = await fetchPersonData(tmdbId);
|
||||||
if (!personData) {
|
if (!personData) {
|
||||||
throw new NotFoundError(`Person with TMDB ID ${tmdbId} not found in TMDB`);
|
throw new NotFoundError(
|
||||||
|
`Person with TMDB ID ${tmdbId} not found in TMDB`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create new person in database
|
// Create new person in database
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const path = require('path');
|
const path = require("path");
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
|
|
||||||
const configService = require("./configService");
|
const configService = require("./configService");
|
||||||
const tmdbService = require("./tmdbService");
|
const tmdbService = require("./tmdbService");
|
||||||
@@ -14,7 +14,6 @@ const _mediaOptimizerService = mediaOptimizerService;
|
|||||||
const _mediaDownloaderService = mediaDownloaderService;
|
const _mediaDownloaderService = mediaDownloaderService;
|
||||||
|
|
||||||
class StorageService {
|
class StorageService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!StorageService.instance) {
|
if (!StorageService.instance) {
|
||||||
StorageService.instance = this;
|
StorageService.instance = this;
|
||||||
@@ -27,11 +26,10 @@ class StorageService {
|
|||||||
file.data.pipe(writer);
|
file.data.pipe(writer);
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
writer.on('finish', resolve);
|
writer.on("finish", resolve);
|
||||||
writer.on('error', reject);
|
writer.on("error", reject);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new StorageService();
|
module.exports = new StorageService();
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
const axios = require('axios');
|
const axios = require("axios");
|
||||||
const { logToFile } = require('./logService');
|
const { logToFile } = require("./logService");
|
||||||
const configService = require('./configService');
|
const configService = require("./configService");
|
||||||
|
|
||||||
const TMDB_APIURL = configService.getTmdbApiUrl();
|
const TMDB_APIURL = configService.getTmdbApiUrl();
|
||||||
const TMDB_APIKEY = configService.getTmdbApiKey();
|
const TMDB_APIKEY = configService.getTmdbApiKey();
|
||||||
@@ -8,44 +8,41 @@ const TMDB_APIKEY = configService.getTmdbApiKey();
|
|||||||
async function fetchEntryData(tmdb_id, is_tvserie) {
|
async function fetchEntryData(tmdb_id, is_tvserie) {
|
||||||
try {
|
try {
|
||||||
let type = is_tvserie ? "tv" : "movie";
|
let type = is_tvserie ? "tv" : "movie";
|
||||||
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`
|
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||||
logToFile(`Fetching Entry Data From: ${url}`)
|
logToFile(`Fetching Entry Data From: ${url}`);
|
||||||
let data;
|
let data;
|
||||||
await axios.get(url)
|
await axios.get(url).then((response) => {
|
||||||
.then((response) => {
|
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
logToFile(`Error Fetching Data From: ${url}`)
|
logToFile(`Error Fetching Data From: ${url}`);
|
||||||
return console.log('Error fetching the data.')
|
return console.log("Error fetching the data.");
|
||||||
};
|
}
|
||||||
data = response.data;
|
data = response.data;
|
||||||
})
|
});
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching the entry data.', error)
|
console.log("Error fetching the entry data.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function fetchSeasonData(tmdbTvId, seasonNumber) {
|
async function fetchSeasonData(tmdbTvId, seasonNumber) {
|
||||||
// fetching the informations
|
// fetching the informations
|
||||||
try {
|
try {
|
||||||
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`
|
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||||
logToFile(`Fetching Season Data From: ${url}`)
|
logToFile(`Fetching Season Data From: ${url}`);
|
||||||
let data;
|
let data;
|
||||||
await axios.get(url)
|
await axios.get(url).then((response) => {
|
||||||
.then((response) => {
|
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
logToFile(`Error Fetching Data From: ${url}`)
|
logToFile(`Error Fetching Data From: ${url}`);
|
||||||
return console.log('Error fetching the data.')
|
return console.log("Error fetching the data.");
|
||||||
};
|
}
|
||||||
data = response.data;
|
data = response.data;
|
||||||
})
|
});
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching the data.')
|
console.log("Error fetching the data.");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,42 +50,44 @@ async function fetchSeasonData(tmdbTvId, seasonNumber) {
|
|||||||
async function fetchEntryMedia(tmdb_id, is_tvserie) {
|
async function fetchEntryMedia(tmdb_id, is_tvserie) {
|
||||||
try {
|
try {
|
||||||
let type = is_tvserie ? "tv" : "movie";
|
let type = is_tvserie ? "tv" : "movie";
|
||||||
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`
|
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`;
|
||||||
logToFile(`Fetching Entry Media Data From: ${url}`)
|
logToFile(`Fetching Entry Media Data From: ${url}`);
|
||||||
let data;
|
let data;
|
||||||
await axios.get(url)
|
await axios.get(url).then((response) => {
|
||||||
.then((response) => {
|
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
logToFile(`Error Fetching Data From: ${url}`)
|
logToFile(`Error Fetching Data From: ${url}`);
|
||||||
return console.log('Error fetching the data.')
|
return console.log("Error fetching the data.");
|
||||||
};
|
}
|
||||||
data = response.data;
|
data = response.data;
|
||||||
})
|
});
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching the entry media.', error)
|
console.log("Error fetching the entry media.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchCollectionData(collectionId) {
|
async function fetchCollectionData(collectionId) {
|
||||||
try {
|
try {
|
||||||
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`
|
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||||
logToFile(`Fetching Collection Data From: ${url}`)
|
logToFile(`Fetching Collection Data From: ${url}`);
|
||||||
let data;
|
let data;
|
||||||
await axios.get(url)
|
await axios.get(url).then((response) => {
|
||||||
.then((response) => {
|
if (response.status != 200)
|
||||||
if (response.status != 200) return console.log('Error fetching collection data from tmdb:', response);
|
return console.log(
|
||||||
|
"Error fetching collection data from tmdb:",
|
||||||
|
response,
|
||||||
|
);
|
||||||
data = response.data;
|
data = response.data;
|
||||||
})
|
});
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
logToFile(`Error Fetching Data From: ${url}`)
|
logToFile(`Error Fetching Data From: ${url}`);
|
||||||
return console.log('Error fetching the data.')
|
return console.log("Error fetching the data.");
|
||||||
};
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -105,24 +104,23 @@ async function fetchEntryCredits(tmdb_id, is_tvserie) {
|
|||||||
let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`;
|
let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||||
|
|
||||||
if (is_tvserie) {
|
if (is_tvserie) {
|
||||||
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`
|
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`;
|
||||||
}
|
}
|
||||||
|
|
||||||
logToFile(`Fetching Entry Credits From: ${url}`);
|
logToFile(`Fetching Entry Credits From: ${url}`);
|
||||||
|
|
||||||
let data;
|
let data;
|
||||||
await axios.get(url)
|
await axios.get(url).then((response) => {
|
||||||
.then((response) => {
|
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
logToFile(`Error Fetching Credits From: ${url}`);
|
logToFile(`Error Fetching Credits From: ${url}`);
|
||||||
return console.log('Error fetching the credits data.');
|
return console.log("Error fetching the credits data.");
|
||||||
};
|
}
|
||||||
data = response.data;
|
data = response.data;
|
||||||
});
|
});
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching the entry credits.', error);
|
console.log("Error fetching the entry credits.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -138,18 +136,17 @@ async function fetchPersonDetails(tmdb_id) {
|
|||||||
logToFile(`Fetching Person Details From: ${url}`);
|
logToFile(`Fetching Person Details From: ${url}`);
|
||||||
|
|
||||||
let data;
|
let data;
|
||||||
await axios.get(url)
|
await axios.get(url).then((response) => {
|
||||||
.then((response) => {
|
|
||||||
if (response.status != 200) {
|
if (response.status != 200) {
|
||||||
logToFile(`Error Fetching Person Details From: ${url}`);
|
logToFile(`Error Fetching Person Details From: ${url}`);
|
||||||
return console.log('Error fetching the person data.');
|
return console.log("Error fetching the person data.");
|
||||||
};
|
}
|
||||||
data = response.data;
|
data = response.data;
|
||||||
});
|
});
|
||||||
|
|
||||||
return data;
|
return data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching the person details.', error);
|
console.log("Error fetching the person details.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,7 +194,7 @@ async function fetchUpcoming(page = 1) {
|
|||||||
const response = await axios.get(url);
|
const response = await axios.get(url);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching upcoming movies.', error);
|
console.log("Error fetching upcoming movies.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -209,7 +206,7 @@ async function searchMulti(query, page = 1) {
|
|||||||
const response = await axios.get(url);
|
const response = await axios.get(url);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error searching TMDB.', error);
|
console.log("Error searching TMDB.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -221,7 +218,7 @@ async function searchPeople(query, page = 1) {
|
|||||||
const response = await axios.get(url);
|
const response = await axios.get(url);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error searching TMDB people.', error);
|
console.log("Error searching TMDB people.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -233,7 +230,7 @@ async function fetchPopularPeople(page = 1) {
|
|||||||
const response = await axios.get(url);
|
const response = await axios.get(url);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching popular people.', error);
|
console.log("Error fetching popular people.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -245,7 +242,7 @@ async function fetchPersonCombinedCredits(tmdb_id) {
|
|||||||
const response = await axios.get(url);
|
const response = await axios.get(url);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.log('Error fetching person combined credits.', error);
|
console.log("Error fetching person combined credits.", error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -265,7 +262,4 @@ module.exports = {
|
|||||||
searchMulti,
|
searchMulti,
|
||||||
searchPeople,
|
searchPeople,
|
||||||
fetchPopularPeople,
|
fetchPopularPeople,
|
||||||
}
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
+789
-829
File diff suppressed because it is too large.
Load diff
@@ -29,3 +29,9 @@
|
|||||||
- Created `MarkSeasonWatchedDialog` — dedicated dialog for marking a season as watched, replacing the old two-step EpisodeSeenEditDialog+ConfirmDialog flow
|
- Created `MarkSeasonWatchedDialog` — dedicated dialog for marking a season as watched, replacing the old two-step EpisodeSeenEditDialog+ConfirmDialog flow
|
||||||
- Added **Scatter Mode** toggle: distributes episodes across a date range (start → end) with an even spread, shows preview of days and max episodes/day
|
- Added **Scatter Mode** toggle: distributes episodes across a date range (start → end) with an even spread, shows preview of days and max episodes/day
|
||||||
- "Mark Season Watched" button is now always visible (not hidden when all episodes are watched)
|
- "Mark Season Watched" button is now always visible (not hidden when all episodes are watched)
|
||||||
|
|
||||||
|
### Milestone 001.2
|
||||||
|
|
||||||
|
#### Frontend Changes
|
||||||
|
|
||||||
|
- **TmdbPreviewPage**: Added redirect when entry is already in library — navigating to `/entry/tmdb/:type/:id` for an in-library entry now immediately redirects to `/entry/:id` (EntryDetailsPage) with `replace: true`, eliminating the extra "Already in Library — View" button step
|
||||||
Generated
+7
-1183
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": false,
|
||||||
|
"trailingComma": "all",
|
||||||
|
"tabWidth": 2,
|
||||||
|
"semi": true
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { RouterProvider } from 'react-router-dom';
|
import { RouterProvider } from "react-router-dom";
|
||||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||||
import { Toaster } from '@/components/ui/sonner';
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
import { router } from './router';
|
import { router } from "./router";
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
@@ -19,7 +19,12 @@ export function App() {
|
|||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<RouterProvider router={router} />
|
<RouterProvider router={router} />
|
||||||
<Toaster position="bottom-right" richColors closeButton duration={3000} />
|
<Toaster
|
||||||
|
position="bottom-right"
|
||||||
|
richColors
|
||||||
|
closeButton
|
||||||
|
duration={3000}
|
||||||
|
/>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import { normalizeCollection } from '@/lib/normalizers';
|
import { normalizeCollection } from "@/lib/normalizers";
|
||||||
import type { Collection } from '@/types';
|
import type { Collection } from "@/types";
|
||||||
|
|
||||||
export const collectionsApi = {
|
export const collectionsApi = {
|
||||||
getAll: () =>
|
getAll: () =>
|
||||||
api
|
api
|
||||||
.get<Collection[]>('/collections')
|
.get<Collection[]>("/collections")
|
||||||
.then((r) => r.data.map(normalizeCollection)),
|
.then((r) => r.data.map(normalizeCollection)),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
@@ -14,23 +14,26 @@ export const collectionsApi = {
|
|||||||
.then((r) => normalizeCollection(r.data)),
|
.then((r) => normalizeCollection(r.data)),
|
||||||
|
|
||||||
create: (data: Partial<Collection>) =>
|
create: (data: Partial<Collection>) =>
|
||||||
api.post<Collection>('/collections', data).then((r) => r.data),
|
api.post<Collection>("/collections", data).then((r) => r.data),
|
||||||
|
|
||||||
update: (id: number, data: Partial<Collection>) =>
|
update: (id: number, data: Partial<Collection>) =>
|
||||||
api.put<Collection>(`/collections/${id}`, data).then((r) => normalizeCollection(r.data)),
|
api
|
||||||
|
.put<Collection>(`/collections/${id}`, data)
|
||||||
|
.then((r) => normalizeCollection(r.data)),
|
||||||
|
|
||||||
updateWithMedia: (id: number, formData: FormData) =>
|
updateWithMedia: (id: number, formData: FormData) =>
|
||||||
api
|
api
|
||||||
.put<Collection>(`/collections/${id}`, formData, {
|
.put<Collection>(`/collections/${id}`, formData, {
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
headers: { "Content-Type": "multipart/form-data" },
|
||||||
})
|
})
|
||||||
.then((r) => normalizeCollection(r.data)),
|
.then((r) => normalizeCollection(r.data)),
|
||||||
|
|
||||||
delete: (id: number) =>
|
delete: (id: number) => api.delete(`/collections/${id}`).then((r) => r.data),
|
||||||
api.delete(`/collections/${id}`).then((r) => r.data),
|
|
||||||
|
|
||||||
getCollectionParts: (id: number) =>
|
getCollectionParts: (id: number) =>
|
||||||
api.put<Collection>(`/collections/${id}/parts`).then((r) => normalizeCollection(r.data)),
|
api
|
||||||
|
.put<Collection>(`/collections/${id}/parts`)
|
||||||
|
.then((r) => normalizeCollection(r.data)),
|
||||||
|
|
||||||
addEntry: (collectionId: number, entryId: number) =>
|
addEntry: (collectionId: number, entryId: number) =>
|
||||||
api
|
api
|
||||||
|
|||||||
@@ -1,19 +1,23 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import { normalizeEntry, normalizeCredit } from '@/lib/normalizers';
|
import { normalizeEntry, normalizeCredit } from "@/lib/normalizers";
|
||||||
import type { Entry, Credit, TmdbPreview } from '@/types';
|
import type { Entry, Credit, TmdbPreview } from "@/types";
|
||||||
|
|
||||||
export const entriesApi = {
|
export const entriesApi = {
|
||||||
getAll: () =>
|
getAll: () =>
|
||||||
api.get<Entry[]>('/entries').then((r) => r.data.map(normalizeEntry)),
|
api.get<Entry[]>("/entries").then((r) => r.data.map(normalizeEntry)),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
api.get<Entry>(`/entries/${id}`).then((r) => normalizeEntry(r.data)),
|
api.get<Entry>(`/entries/${id}`).then((r) => normalizeEntry(r.data)),
|
||||||
|
|
||||||
create: (tmdb_id: number, is_tvserie: boolean) =>
|
create: (tmdb_id: number, is_tvserie: boolean) =>
|
||||||
api.post<Entry>('/entries', { tmdb_id, is_tvserie }).then((r) => normalizeEntry(r.data)),
|
api
|
||||||
|
.post<Entry>("/entries", { tmdb_id, is_tvserie })
|
||||||
|
.then((r) => normalizeEntry(r.data)),
|
||||||
|
|
||||||
update: (id: number, data: Partial<Entry>) =>
|
update: (id: number, data: Partial<Entry>) =>
|
||||||
api.put<Entry>(`/entries/${id}`, { entryData: data }).then((r) => normalizeEntry(r.data)),
|
api
|
||||||
|
.put<Entry>(`/entries/${id}`, { entryData: data })
|
||||||
|
.then((r) => normalizeEntry(r.data)),
|
||||||
|
|
||||||
updateRatings: (
|
updateRatings: (
|
||||||
id: number,
|
id: number,
|
||||||
@@ -23,39 +27,48 @@ export const entriesApi = {
|
|||||||
tmdb_rating?: number | null;
|
tmdb_rating?: number | null;
|
||||||
imdb_rating?: number | null;
|
imdb_rating?: number | null;
|
||||||
rotten_tomatoes_rating?: number | null;
|
rotten_tomatoes_rating?: number | null;
|
||||||
}
|
},
|
||||||
) => api.put(`/entries/${id}/ratings`, { entryRatings: ratings }).then((r) => r.data),
|
) =>
|
||||||
|
api
|
||||||
|
.put(`/entries/${id}/ratings`, { entryRatings: ratings })
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
updateIds: (
|
updateIds: (
|
||||||
id: number,
|
id: number,
|
||||||
ids: { tmdb_id?: number; imdb_id?: string; tvdb_id?: number }
|
ids: { tmdb_id?: number; imdb_id?: string; tvdb_id?: number },
|
||||||
) => api.put(`/entries/${id}/ids`, ids).then((r) => r.data),
|
) => api.put(`/entries/${id}/ids`, ids).then((r) => r.data),
|
||||||
|
|
||||||
delete: (id: number) => api.delete(`/entries/${id}`).then((r) => r.data),
|
delete: (id: number) => api.delete(`/entries/${id}`).then((r) => r.data),
|
||||||
|
|
||||||
refresh: (id: number) =>
|
refresh: (id: number) =>
|
||||||
api.put<Entry>(`/entries/${id}/refresh`).then((r) => normalizeEntry(r.data)),
|
api
|
||||||
|
.put<Entry>(`/entries/${id}/refresh`)
|
||||||
|
.then((r) => normalizeEntry(r.data)),
|
||||||
|
|
||||||
fetchCollection: (id: number) =>
|
fetchCollection: (id: number) =>
|
||||||
api.put(`/entries/${id}/fetch-collection`).then((r) => r.data),
|
api.put(`/entries/${id}/fetch-collection`).then((r) => r.data),
|
||||||
|
|
||||||
getSeasons: (id: number) =>
|
getSeasons: (id: number) =>
|
||||||
api.get(`/entries/${id}/seasons`).then((r) => Array.isArray(r.data) ? r.data : []),
|
api
|
||||||
|
.get(`/entries/${id}/seasons`)
|
||||||
|
.then((r) => (Array.isArray(r.data) ? r.data : [])),
|
||||||
|
|
||||||
getCredits: (id: number) =>
|
getCredits: (id: number) =>
|
||||||
api
|
api
|
||||||
.get<Credit[]>(`/entries/${id}/credits`)
|
.get<Credit[]>(`/entries/${id}/credits`)
|
||||||
.then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])),
|
.then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])),
|
||||||
|
|
||||||
syncSeries: () => api.get('/entries/sync-series').then((r) => r.data),
|
syncSeries: () => api.get("/entries/sync-series").then((r) => r.data),
|
||||||
|
|
||||||
previewTmdb: (tmdbId: number, type: 'movie' | 'tv') =>
|
previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
|
||||||
api.get<TmdbPreview>(`/entries/tmdb/preview/${type}/${tmdbId}`).then((r) => r.data),
|
api
|
||||||
|
.get<TmdbPreview>(`/entries/tmdb/preview/${type}/${tmdbId}`)
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
uploadMedia: (id: number, formData: FormData) =>
|
uploadMedia: (id: number, formData: FormData) =>
|
||||||
api
|
api
|
||||||
.post(`/entries/${id}/media`, formData, {
|
.post(`/entries/${id}/media`, formData, {
|
||||||
headers: { 'Content-Type': 'multipart/form-data' },
|
headers: { "Content-Type": "multipart/form-data" },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { EntrySeen } from '@/types';
|
import type { EntrySeen } from "@/types";
|
||||||
|
|
||||||
export const entrySeenApi = {
|
export const entrySeenApi = {
|
||||||
getAll: () => api.get<EntrySeen[]>('/entry-seen').then((r) => r.data),
|
getAll: () => api.get<EntrySeen[]>("/entry-seen").then((r) => r.data),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
api.get<EntrySeen>(`/entry-seen/${id}`).then((r) => r.data),
|
api.get<EntrySeen>(`/entry-seen/${id}`).then((r) => r.data),
|
||||||
@@ -16,8 +16,12 @@ export const entrySeenApi = {
|
|||||||
throw err;
|
throw err;
|
||||||
}),
|
}),
|
||||||
|
|
||||||
create: (data: { entry_id: number; date_seen: string; seen_with?: string; accuracy?: string }) =>
|
create: (data: {
|
||||||
api.post<EntrySeen>('/entry-seen', data).then((r) => r.data),
|
entry_id: number;
|
||||||
|
date_seen: string;
|
||||||
|
seen_with?: string;
|
||||||
|
accuracy?: string;
|
||||||
|
}) => api.post<EntrySeen>("/entry-seen", data).then((r) => r.data),
|
||||||
|
|
||||||
update: (id: number, data: Partial<EntrySeen>) =>
|
update: (id: number, data: Partial<EntrySeen>) =>
|
||||||
api.put<EntrySeen>(`/entry-seen/${id}`, data).then((r) => r.data),
|
api.put<EntrySeen>(`/entry-seen/${id}`, data).then((r) => r.data),
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { EpisodeSeen } from '@/types';
|
import type { EpisodeSeen } from "@/types";
|
||||||
|
|
||||||
export const episodeSeenApi = {
|
export const episodeSeenApi = {
|
||||||
getAll: () => api.get<EpisodeSeen[]>('/episode-seen').then((r) => r.data),
|
getAll: () => api.get<EpisodeSeen[]>("/episode-seen").then((r) => r.data),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
api.get<EpisodeSeen>(`/episode-seen/${id}`).then((r) => r.data),
|
api.get<EpisodeSeen>(`/episode-seen/${id}`).then((r) => r.data),
|
||||||
@@ -22,11 +22,10 @@ export const episodeSeenApi = {
|
|||||||
date_seen: string;
|
date_seen: string;
|
||||||
seen_with?: string;
|
seen_with?: string;
|
||||||
accuracy?: string;
|
accuracy?: string;
|
||||||
}) => api.post<EpisodeSeen>('/episode-seen', data).then((r) => r.data),
|
}) => api.post<EpisodeSeen>("/episode-seen", data).then((r) => r.data),
|
||||||
|
|
||||||
update: (id: number, data: Partial<EpisodeSeen>) =>
|
update: (id: number, data: Partial<EpisodeSeen>) =>
|
||||||
api.put<EpisodeSeen>(`/episode-seen/${id}`, data).then((r) => r.data),
|
api.put<EpisodeSeen>(`/episode-seen/${id}`, data).then((r) => r.data),
|
||||||
|
|
||||||
delete: (id: number) =>
|
delete: (id: number) => api.delete(`/episode-seen/${id}`).then((r) => r.data),
|
||||||
api.delete(`/episode-seen/${id}`).then((r) => r.data),
|
|
||||||
};
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { Episode } from '@/types';
|
import type { Episode } from "@/types";
|
||||||
|
|
||||||
export const episodesApi = {
|
export const episodesApi = {
|
||||||
getByMonth: (startDate: string, endDate: string) =>
|
getByMonth: (startDate: string, endDate: string) =>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { People, Credit } from '@/types';
|
import type { People, Credit } from "@/types";
|
||||||
|
|
||||||
export interface TmdbFilmographyItem {
|
export interface TmdbFilmographyItem {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -8,7 +8,7 @@ export interface TmdbFilmographyItem {
|
|||||||
poster_path: string | null;
|
poster_path: string | null;
|
||||||
release_date?: string;
|
release_date?: string;
|
||||||
first_air_date?: string;
|
first_air_date?: string;
|
||||||
media_type: 'movie' | 'tv';
|
media_type: "movie" | "tv";
|
||||||
character?: string;
|
character?: string;
|
||||||
job?: string;
|
job?: string;
|
||||||
department?: string;
|
department?: string;
|
||||||
@@ -44,31 +44,38 @@ export interface PaginatedPeopleResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const peopleApi = {
|
export const peopleApi = {
|
||||||
getAll: () => api.get<People[]>('/people').then((r) => r.data),
|
getAll: () => api.get<People[]>("/people").then((r) => r.data),
|
||||||
|
|
||||||
getAllPaginated: (page: number, limit: number, search?: string) =>
|
getAllPaginated: (page: number, limit: number, search?: string) =>
|
||||||
api
|
api
|
||||||
.get<PaginatedPeopleResponse>('/people', { params: { page, limit, ...(search ? { search } : {}) } })
|
.get<PaginatedPeopleResponse>("/people", {
|
||||||
|
params: { page, limit, ...(search ? { search } : {}) },
|
||||||
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) => api.get<People>(`/people/${id}`).then((r) => r.data),
|
||||||
api.get<People>(`/people/${id}`).then((r) => r.data),
|
|
||||||
|
|
||||||
getCredits: (id: number) =>
|
getCredits: (id: number) =>
|
||||||
api.get<Credit[]>(`/people/${id}/credits`).then((r) => r.data),
|
api.get<Credit[]>(`/people/${id}/credits`).then((r) => r.data),
|
||||||
|
|
||||||
getTmdbFilmography: (id: number) =>
|
getTmdbFilmography: (id: number) =>
|
||||||
api.get<TmdbFilmographyResponse>(`/people/${id}/tmdb-filmography`).then((r) => r.data),
|
api
|
||||||
|
.get<TmdbFilmographyResponse>(`/people/${id}/tmdb-filmography`)
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
previewTmdb: (tmdbId: number) =>
|
previewTmdb: (tmdbId: number) =>
|
||||||
api.get<TmdbPersonPreview>(`/people/tmdb/preview/${tmdbId}`).then((r) => r.data),
|
api
|
||||||
|
.get<TmdbPersonPreview>(`/people/tmdb/preview/${tmdbId}`)
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
fetchByTmdbId: (tmdb_id: number, pinned = false) =>
|
fetchByTmdbId: (tmdb_id: number, pinned = false) =>
|
||||||
api.post<People>('/people/fetch', { tmdb_id, pinned }).then((r) => r.data),
|
api.post<People>("/people/fetch", { tmdb_id, pinned }).then((r) => r.data),
|
||||||
|
|
||||||
update: (id: number, data: Partial<People>) =>
|
update: (id: number, data: Partial<People>) =>
|
||||||
api.put<People>(`/people/${id}`, data).then((r) => r.data),
|
api.put<People>(`/people/${id}`, data).then((r) => r.data),
|
||||||
|
|
||||||
search: (query: string) =>
|
search: (query: string) =>
|
||||||
api.get<People[]>('/people/search', { params: { query } }).then((r) => r.data),
|
api
|
||||||
|
.get<People[]>("/people/search", { params: { query } })
|
||||||
|
.then((r) => r.data),
|
||||||
};
|
};
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { Season, Episode } from '@/types';
|
import type { Season, Episode } from "@/types";
|
||||||
|
|
||||||
export const seasonsApi = {
|
export const seasonsApi = {
|
||||||
getAll: () => api.get<Season[]>('/seasons').then((r) => r.data),
|
getAll: () => api.get<Season[]>("/seasons").then((r) => r.data),
|
||||||
|
|
||||||
getById: (id: number) =>
|
getById: (id: number) =>
|
||||||
api.get<Season>(`/seasons/${id}`).then((r) => r.data),
|
api.get<Season>(`/seasons/${id}`).then((r) => r.data),
|
||||||
@@ -11,7 +11,7 @@ export const seasonsApi = {
|
|||||||
api.get<Episode[]>(`/seasons/${id}/episodes`).then((r) => r.data),
|
api.get<Episode[]>(`/seasons/${id}/episodes`).then((r) => r.data),
|
||||||
|
|
||||||
create: (data: Partial<Season>) =>
|
create: (data: Partial<Season>) =>
|
||||||
api.post<Season>('/seasons', data).then((r) => r.data),
|
api.post<Season>("/seasons", data).then((r) => r.data),
|
||||||
|
|
||||||
update: (id: number, data: Partial<Season>) =>
|
update: (id: number, data: Partial<Season>) =>
|
||||||
api.put<Season>(`/seasons/${id}`, data).then((r) => r.data),
|
api.put<Season>(`/seasons/${id}`, data).then((r) => r.data),
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { Settings } from '@/types';
|
import type { Settings } from "@/types";
|
||||||
|
|
||||||
export const settingsApi = {
|
export const settingsApi = {
|
||||||
get: () => api.get<Settings>('/settings').then((r) => r.data),
|
get: () => api.get<Settings>("/settings").then((r) => r.data),
|
||||||
|
|
||||||
update: (data: Partial<Settings>) =>
|
update: (data: Partial<Settings>) =>
|
||||||
api.put<Settings>('/settings', data).then((r) => r.data),
|
api.put<Settings>("/settings", data).then((r) => r.data),
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
|
|
||||||
export interface MonthlyCountItem {
|
export interface MonthlyCountItem {
|
||||||
month: number;
|
month: number;
|
||||||
@@ -37,11 +37,17 @@ export interface AllTimeWatchTime {
|
|||||||
|
|
||||||
export const statisticsApi = {
|
export const statisticsApi = {
|
||||||
getAllTimeWatchTime: () =>
|
getAllTimeWatchTime: () =>
|
||||||
api.get<AllTimeWatchTime>('/statistics/watch-time').then((r) => r.data),
|
api.get<AllTimeWatchTime>("/statistics/watch-time").then((r) => r.data),
|
||||||
getYearlyWatchCount: (year: number) =>
|
getYearlyWatchCount: (year: number) =>
|
||||||
api.get<YearlyWatchCount>(`/statistics/watch-count/year/${year}`).then((r) => r.data),
|
api
|
||||||
|
.get<YearlyWatchCount>(`/statistics/watch-count/year/${year}`)
|
||||||
|
.then((r) => r.data),
|
||||||
getYearlyWatchTime: (year: number) =>
|
getYearlyWatchTime: (year: number) =>
|
||||||
api.get<YearlyWatchTime>(`/statistics/watch-time/year/${year}`).then((r) => r.data),
|
api
|
||||||
|
.get<YearlyWatchTime>(`/statistics/watch-time/year/${year}`)
|
||||||
|
.then((r) => r.data),
|
||||||
getWatchdayDistribution: () =>
|
getWatchdayDistribution: () =>
|
||||||
api.get<WatchdayDistribution>('/statistics/watch-weekday').then((r) => r.data),
|
api
|
||||||
|
.get<WatchdayDistribution>("/statistics/watch-weekday")
|
||||||
|
.then((r) => r.data),
|
||||||
};
|
};
|
||||||
@@ -1,73 +1,73 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
import type { TmdbEntry, TmdbPaginatedResponse, TmdbPerson } from '@/types';
|
import type { TmdbEntry, TmdbPaginatedResponse, TmdbPerson } from "@/types";
|
||||||
|
|
||||||
export const tmdbApi = {
|
export const tmdbApi = {
|
||||||
getPopularMovies: (page = 1) =>
|
getPopularMovies: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/popular/movie', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/popular/movie", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getPopularTv: (page = 1) =>
|
getPopularTv: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/popular/tv', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/popular/tv", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getTrendingMovies: (page = 1) =>
|
getTrendingMovies: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/trending/movie', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/trending/movie", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getTrendingTv: (page = 1) =>
|
getTrendingTv: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/trending/tv', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/trending/tv", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getTopRatedMovies: (page = 1) =>
|
getTopRatedMovies: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/top-rated/movie', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/top-rated/movie", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getTopRatedTv: (page = 1) =>
|
getTopRatedTv: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/top-rated/tv', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/top-rated/tv", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getUpcomingMovies: (page = 1) =>
|
getUpcomingMovies: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/upcoming/movie', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/upcoming/movie", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
search: (query: string, page = 1) =>
|
search: (query: string, page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbEntry>>('/entries/tmdb/search', {
|
.get<TmdbPaginatedResponse<TmdbEntry>>("/entries/tmdb/search", {
|
||||||
params: { query, page },
|
params: { query, page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
getPopularPeople: (page = 1) =>
|
getPopularPeople: (page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbPerson>>('/people/tmdb/popular', {
|
.get<TmdbPaginatedResponse<TmdbPerson>>("/people/tmdb/popular", {
|
||||||
params: { page },
|
params: { page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|
||||||
searchPeople: (query: string, page = 1) =>
|
searchPeople: (query: string, page = 1) =>
|
||||||
api
|
api
|
||||||
.get<TmdbPaginatedResponse<TmdbPerson>>('/people/tmdb/search', {
|
.get<TmdbPaginatedResponse<TmdbPerson>>("/people/tmdb/search", {
|
||||||
params: { query, page },
|
params: { query, page },
|
||||||
})
|
})
|
||||||
.then((r) => r.data),
|
.then((r) => r.data),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
Search,
|
Search,
|
||||||
Film,
|
Film,
|
||||||
@@ -16,22 +16,22 @@ import {
|
|||||||
ArrowDown,
|
ArrowDown,
|
||||||
CornerDownLeft,
|
CornerDownLeft,
|
||||||
ArrowRight,
|
ArrowRight,
|
||||||
} from 'lucide-react';
|
} from "lucide-react";
|
||||||
import { tmdbApi } from '@/api/tmdb';
|
import { tmdbApi } from "@/api/tmdb";
|
||||||
import { useLibraryStore } from '@/stores/useLibraryStore';
|
import { useLibraryStore } from "@/stores/useLibraryStore";
|
||||||
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
|
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
|
||||||
import { useCreateEntry } from '@/hooks/useEntries';
|
import { useCreateEntry } from "@/hooks/useEntries";
|
||||||
import { getTmdbImageUrl } from '@/lib/api';
|
import { getTmdbImageUrl } from "@/lib/api";
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from "@/lib/utils";
|
||||||
import type { TmdbEntry } from '@/types';
|
import type { TmdbEntry } from "@/types";
|
||||||
|
|
||||||
interface CommandItem {
|
interface CommandItem {
|
||||||
id: string;
|
id: string;
|
||||||
type: 'command' | 'library' | 'tmdb';
|
type: "command" | "library" | "tmdb";
|
||||||
title: string;
|
title: string;
|
||||||
subtitle?: string;
|
subtitle?: string;
|
||||||
year?: string;
|
year?: string;
|
||||||
mediaType?: 'movie' | 'tv';
|
mediaType?: "movie" | "tv";
|
||||||
posterPath?: string | null;
|
posterPath?: string | null;
|
||||||
icon?: React.ReactNode;
|
icon?: React.ReactNode;
|
||||||
inLibrary?: boolean;
|
inLibrary?: boolean;
|
||||||
@@ -41,23 +41,58 @@ interface CommandItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const NAVIGATION_COMMANDS: CommandItem[] = [
|
const NAVIGATION_COMMANDS: CommandItem[] = [
|
||||||
{ id: 'cmd-library', type: 'command', title: 'Go to Library', icon: <Library className="h-4 w-4" /> },
|
{
|
||||||
{ id: 'cmd-watchlist', type: 'command', title: 'Go to Watchlist', icon: <BookOpen className="h-4 w-4" /> },
|
id: "cmd-library",
|
||||||
{ id: 'cmd-stats', type: 'command', title: 'Go to Statistics', icon: <BarChart3 className="h-4 w-4" /> },
|
type: "command",
|
||||||
{ id: 'cmd-calendar', type: 'command', title: 'Go to Calendar', icon: <Calendar className="h-4 w-4" /> },
|
title: "Go to Library",
|
||||||
{ id: 'cmd-people', type: 'command', title: 'Go to People', icon: <Users className="h-4 w-4" /> },
|
icon: <Library className="h-4 w-4" />,
|
||||||
{ id: 'cmd-settings', type: 'command', title: 'Go to Settings', icon: <Settings className="h-4 w-4" /> },
|
},
|
||||||
{ id: 'cmd-favorites', type: 'command', title: 'Go to Favorites', icon: <Star className="h-4 w-4" /> },
|
{
|
||||||
|
id: "cmd-watchlist",
|
||||||
|
type: "command",
|
||||||
|
title: "Go to Watchlist",
|
||||||
|
icon: <BookOpen className="h-4 w-4" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "cmd-stats",
|
||||||
|
type: "command",
|
||||||
|
title: "Go to Statistics",
|
||||||
|
icon: <BarChart3 className="h-4 w-4" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "cmd-calendar",
|
||||||
|
type: "command",
|
||||||
|
title: "Go to Calendar",
|
||||||
|
icon: <Calendar className="h-4 w-4" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "cmd-people",
|
||||||
|
type: "command",
|
||||||
|
title: "Go to People",
|
||||||
|
icon: <Users className="h-4 w-4" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "cmd-settings",
|
||||||
|
type: "command",
|
||||||
|
title: "Go to Settings",
|
||||||
|
icon: <Settings className="h-4 w-4" />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "cmd-favorites",
|
||||||
|
type: "command",
|
||||||
|
title: "Go to Favorites",
|
||||||
|
icon: <Star className="h-4 w-4" />,
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const COMMAND_ROUTES: Record<string, string> = {
|
const COMMAND_ROUTES: Record<string, string> = {
|
||||||
'cmd-library': '/library',
|
"cmd-library": "/library",
|
||||||
'cmd-watchlist': '/watchlist',
|
"cmd-watchlist": "/watchlist",
|
||||||
'cmd-stats': '/dashboard',
|
"cmd-stats": "/dashboard",
|
||||||
'cmd-calendar': '/calendar',
|
"cmd-calendar": "/calendar",
|
||||||
'cmd-people': '/people',
|
"cmd-people": "/people",
|
||||||
'cmd-settings': '/settings',
|
"cmd-settings": "/settings",
|
||||||
'cmd-favorites': '/library?filter=favorites',
|
"cmd-favorites": "/library?filter=favorites",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function CommandPalette() {
|
export function CommandPalette() {
|
||||||
@@ -68,8 +103,8 @@ export function CommandPalette() {
|
|||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const listRef = useRef<HTMLDivElement>(null);
|
const listRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const [query, setQuery] = useState('');
|
const [query, setQuery] = useState("");
|
||||||
const [debouncedQuery, setDebouncedQuery] = useState('');
|
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||||
|
|
||||||
// Debounce search query
|
// Debounce search query
|
||||||
@@ -81,8 +116,8 @@ export function CommandPalette() {
|
|||||||
// Focus input when opened
|
// Focus input when opened
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) {
|
if (isOpen) {
|
||||||
setQuery('');
|
setQuery("");
|
||||||
setDebouncedQuery('');
|
setDebouncedQuery("");
|
||||||
setSelectedIndex(0);
|
setSelectedIndex(0);
|
||||||
setTimeout(() => inputRef.current?.focus(), 50);
|
setTimeout(() => inputRef.current?.focus(), 50);
|
||||||
}
|
}
|
||||||
@@ -90,7 +125,7 @@ export function CommandPalette() {
|
|||||||
|
|
||||||
// TMDB search
|
// TMDB search
|
||||||
const { data: tmdbResults, isFetching: tmdbLoading } = useQuery({
|
const { data: tmdbResults, isFetching: tmdbLoading } = useQuery({
|
||||||
queryKey: ['command-palette', 'tmdb', debouncedQuery],
|
queryKey: ["command-palette", "tmdb", debouncedQuery],
|
||||||
queryFn: () => tmdbApi.search(debouncedQuery, 1),
|
queryFn: () => tmdbApi.search(debouncedQuery, 1),
|
||||||
enabled: debouncedQuery.length > 1,
|
enabled: debouncedQuery.length > 1,
|
||||||
staleTime: 60 * 1000,
|
staleTime: 60 * 1000,
|
||||||
@@ -98,7 +133,16 @@ export function CommandPalette() {
|
|||||||
|
|
||||||
// Build library TMDB ID index for fast lookups
|
// Build library TMDB ID index for fast lookups
|
||||||
const libraryTmdbIndex = useMemo(() => {
|
const libraryTmdbIndex = useMemo(() => {
|
||||||
const index = new Map<number, { id: number; title: string; is_tvseries: boolean; poster_path: string | null; rating: number | null }>();
|
const index = new Map<
|
||||||
|
number,
|
||||||
|
{
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
is_tvseries: boolean;
|
||||||
|
poster_path: string | null;
|
||||||
|
rating: number | null;
|
||||||
|
}
|
||||||
|
>();
|
||||||
libraryEntries.forEach((entry) => {
|
libraryEntries.forEach((entry) => {
|
||||||
if (entry.entryIds?.tmdb_id) {
|
if (entry.entryIds?.tmdb_id) {
|
||||||
index.set(entry.entryIds.tmdb_id, {
|
index.set(entry.entryIds.tmdb_id, {
|
||||||
@@ -122,10 +166,10 @@ export function CommandPalette() {
|
|||||||
if (entry.title.toLowerCase().includes(lower)) {
|
if (entry.title.toLowerCase().includes(lower)) {
|
||||||
results.push({
|
results.push({
|
||||||
id: `lib-${entry.id}`,
|
id: `lib-${entry.id}`,
|
||||||
type: 'library',
|
type: "library",
|
||||||
title: entry.title,
|
title: entry.title,
|
||||||
year: entry.release_date?.slice(0, 4),
|
year: entry.release_date?.slice(0, 4),
|
||||||
mediaType: entry.is_tvseries ? 'tv' : 'movie',
|
mediaType: entry.is_tvseries ? "tv" : "movie",
|
||||||
posterPath: entry.poster_path,
|
posterPath: entry.poster_path,
|
||||||
inLibrary: true,
|
inLibrary: true,
|
||||||
libraryId: entry.id,
|
libraryId: entry.id,
|
||||||
@@ -145,13 +189,13 @@ export function CommandPalette() {
|
|||||||
.filter((r: TmdbEntry) => !libraryTmdbIndex.has(r.id))
|
.filter((r: TmdbEntry) => !libraryTmdbIndex.has(r.id))
|
||||||
.slice(0, 8)
|
.slice(0, 8)
|
||||||
.map((r: TmdbEntry) => {
|
.map((r: TmdbEntry) => {
|
||||||
const mediaType = r.media_type === 'tv' || r.name ? 'tv' : 'movie';
|
const mediaType = r.media_type === "tv" || r.name ? "tv" : "movie";
|
||||||
const title = r.title || r.name || 'Unknown';
|
const title = r.title || r.name || "Unknown";
|
||||||
const year = (r.release_date || r.first_air_date)?.slice(0, 4);
|
const year = (r.release_date || r.first_air_date)?.slice(0, 4);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: `tmdb-${r.id}`,
|
id: `tmdb-${r.id}`,
|
||||||
type: 'tmdb' as const,
|
type: "tmdb" as const,
|
||||||
title,
|
title,
|
||||||
year,
|
year,
|
||||||
mediaType,
|
mediaType,
|
||||||
@@ -167,7 +211,9 @@ export function CommandPalette() {
|
|||||||
const filteredCommands = useMemo((): CommandItem[] => {
|
const filteredCommands = useMemo((): CommandItem[] => {
|
||||||
if (!query.trim()) return NAVIGATION_COMMANDS;
|
if (!query.trim()) return NAVIGATION_COMMANDS;
|
||||||
const lower = query.toLowerCase();
|
const lower = query.toLowerCase();
|
||||||
return NAVIGATION_COMMANDS.filter((c) => c.title.toLowerCase().includes(lower));
|
return NAVIGATION_COMMANDS.filter((c) =>
|
||||||
|
c.title.toLowerCase().includes(lower),
|
||||||
|
);
|
||||||
}, [query]);
|
}, [query]);
|
||||||
|
|
||||||
// Recently viewed items (shown when no query)
|
// Recently viewed items (shown when no query)
|
||||||
@@ -175,7 +221,7 @@ export function CommandPalette() {
|
|||||||
if (query.trim()) return [];
|
if (query.trim()) return [];
|
||||||
return recentlyViewed.map((r) => ({
|
return recentlyViewed.map((r) => ({
|
||||||
id: `recent-${r.id}`,
|
id: `recent-${r.id}`,
|
||||||
type: (r.libraryId ? 'library' : 'tmdb') as 'library' | 'tmdb',
|
type: (r.libraryId ? "library" : "tmdb") as "library" | "tmdb",
|
||||||
title: r.title,
|
title: r.title,
|
||||||
mediaType: r.type,
|
mediaType: r.type,
|
||||||
posterPath: r.poster_path,
|
posterPath: r.poster_path,
|
||||||
@@ -187,7 +233,12 @@ export function CommandPalette() {
|
|||||||
|
|
||||||
// All items combined
|
// All items combined
|
||||||
const allItems = useMemo(() => {
|
const allItems = useMemo(() => {
|
||||||
return [...filteredCommands, ...localResults, ...tmdbItems, ...(query ? [] : recentItems)];
|
return [
|
||||||
|
...filteredCommands,
|
||||||
|
...localResults,
|
||||||
|
...tmdbItems,
|
||||||
|
...(query ? [] : recentItems),
|
||||||
|
];
|
||||||
}, [filteredCommands, localResults, tmdbItems, recentItems, query]);
|
}, [filteredCommands, localResults, tmdbItems, recentItems, query]);
|
||||||
|
|
||||||
// Keep selected index in bounds
|
// Keep selected index in bounds
|
||||||
@@ -199,13 +250,15 @@ export function CommandPalette() {
|
|||||||
|
|
||||||
// Scroll selected item into view
|
// Scroll selected item into view
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = listRef.current?.querySelector(`[data-index="${selectedIndex}"]`);
|
const el = listRef.current?.querySelector(
|
||||||
el?.scrollIntoView({ block: 'nearest' });
|
`[data-index="${selectedIndex}"]`,
|
||||||
|
);
|
||||||
|
el?.scrollIntoView({ block: "nearest" });
|
||||||
}, [selectedIndex]);
|
}, [selectedIndex]);
|
||||||
|
|
||||||
const handleSelect = useCallback(
|
const handleSelect = useCallback(
|
||||||
(item: CommandItem, quickAdd = false) => {
|
(item: CommandItem, quickAdd = false) => {
|
||||||
if (item.type === 'command') {
|
if (item.type === "command") {
|
||||||
const route = COMMAND_ROUTES[item.id];
|
const route = COMMAND_ROUTES[item.id];
|
||||||
if (route) navigate(route);
|
if (route) navigate(route);
|
||||||
close();
|
close();
|
||||||
@@ -220,13 +273,13 @@ export function CommandPalette() {
|
|||||||
|
|
||||||
if (quickAdd && item.tmdbId && item.mediaType) {
|
if (quickAdd && item.tmdbId && item.mediaType) {
|
||||||
createEntry.mutate(
|
createEntry.mutate(
|
||||||
{ tmdb_id: item.tmdbId, is_tvserie: item.mediaType === 'tv' },
|
{ tmdb_id: item.tmdbId, is_tvserie: item.mediaType === "tv" },
|
||||||
{
|
{
|
||||||
onSuccess: (entry) => {
|
onSuccess: (entry) => {
|
||||||
navigate(`/entry/${entry.id}`);
|
navigate(`/entry/${entry.id}`);
|
||||||
close();
|
close();
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -237,39 +290,42 @@ export function CommandPalette() {
|
|||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[navigate, close, createEntry]
|
[navigate, close, createEntry],
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleKeyDown = useCallback(
|
const handleKeyDown = useCallback(
|
||||||
(e: React.KeyboardEvent) => {
|
(e: React.KeyboardEvent) => {
|
||||||
switch (e.key) {
|
switch (e.key) {
|
||||||
case 'ArrowDown':
|
case "ArrowDown":
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setSelectedIndex((i) => Math.min(i + 1, allItems.length - 1));
|
setSelectedIndex((i) => Math.min(i + 1, allItems.length - 1));
|
||||||
break;
|
break;
|
||||||
case 'ArrowUp':
|
case "ArrowUp":
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setSelectedIndex((i) => Math.max(i - 1, 0));
|
setSelectedIndex((i) => Math.max(i - 1, 0));
|
||||||
break;
|
break;
|
||||||
case 'Enter': {
|
case "Enter": {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const item = allItems[selectedIndex];
|
const item = allItems[selectedIndex];
|
||||||
if (item) handleSelect(item, e.shiftKey);
|
if (item) handleSelect(item, e.shiftKey);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'Escape':
|
case "Escape":
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
close();
|
close();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[allItems, selectedIndex, handleSelect, close]
|
[allItems, selectedIndex, handleSelect, close],
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!isOpen) return null;
|
if (!isOpen) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]" onClick={close}>
|
<div
|
||||||
|
className="fixed inset-0 z-50 flex items-start justify-center pt-[15vh]"
|
||||||
|
onClick={close}
|
||||||
|
>
|
||||||
{/* Backdrop */}
|
{/* Backdrop */}
|
||||||
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
|
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm" />
|
||||||
|
|
||||||
@@ -304,7 +360,7 @@ export function CommandPalette() {
|
|||||||
{filteredCommands.length > 0 && (
|
{filteredCommands.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
|
<div className="px-2 py-1.5 text-xs font-medium text-muted-foreground">
|
||||||
{query ? 'Commands' : 'Quick Actions'}
|
{query ? "Commands" : "Quick Actions"}
|
||||||
</div>
|
</div>
|
||||||
{filteredCommands.map((item, i) => {
|
{filteredCommands.map((item, i) => {
|
||||||
const idx = i;
|
const idx = i;
|
||||||
@@ -346,7 +402,9 @@ export function CommandPalette() {
|
|||||||
{localResults.length > 0 && (
|
{localResults.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between px-2 py-1.5">
|
<div className="flex items-center justify-between px-2 py-1.5">
|
||||||
<span className="text-xs font-medium text-muted-foreground">Library</span>
|
<span className="text-xs font-medium text-muted-foreground">
|
||||||
|
Library
|
||||||
|
</span>
|
||||||
<button
|
<button
|
||||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -376,7 +434,9 @@ export function CommandPalette() {
|
|||||||
{tmdbItems.length > 0 && (
|
{tmdbItems.length > 0 && (
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between px-2 py-1.5">
|
<div className="flex items-center justify-between px-2 py-1.5">
|
||||||
<span className="text-xs font-medium text-muted-foreground">TMDB Results</span>
|
<span className="text-xs font-medium text-muted-foreground">
|
||||||
|
TMDB Results
|
||||||
|
</span>
|
||||||
<button
|
<button
|
||||||
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -416,7 +476,9 @@ export function CommandPalette() {
|
|||||||
<CornerDownLeft className="h-3 w-3" /> Open
|
<CornerDownLeft className="h-3 w-3" /> Open
|
||||||
</span>
|
</span>
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
<kbd className="rounded border border-border px-1 font-mono text-[10px]">⇧</kbd>
|
<kbd className="rounded border border-border px-1 font-mono text-[10px]">
|
||||||
|
⇧
|
||||||
|
</kbd>
|
||||||
<CornerDownLeft className="h-3 w-3" /> Quick Add
|
<CornerDownLeft className="h-3 w-3" /> Quick Add
|
||||||
</span>
|
</span>
|
||||||
<span className="flex items-center gap-1">
|
<span className="flex items-center gap-1">
|
||||||
@@ -424,7 +486,10 @@ export function CommandPalette() {
|
|||||||
<ArrowDown className="h-3 w-3" /> Navigate
|
<ArrowDown className="h-3 w-3" /> Navigate
|
||||||
</span>
|
</span>
|
||||||
<span className="ml-auto">
|
<span className="ml-auto">
|
||||||
<kbd className="rounded border border-border px-1 font-mono text-[10px]">Esc</kbd> Close
|
<kbd className="rounded border border-border px-1 font-mono text-[10px]">
|
||||||
|
Esc
|
||||||
|
</kbd>{" "}
|
||||||
|
Close
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -447,25 +512,29 @@ function ResultRow({
|
|||||||
<div
|
<div
|
||||||
data-index={dataIndex}
|
data-index={dataIndex}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 transition-colors',
|
"flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 transition-colors",
|
||||||
isSelected ? 'bg-accent text-accent-foreground' : 'hover:bg-muted'
|
isSelected ? "bg-accent text-accent-foreground" : "hover:bg-muted",
|
||||||
)}
|
)}
|
||||||
onClick={onClick}
|
onClick={onClick}
|
||||||
>
|
>
|
||||||
{/* Poster or icon */}
|
{/* Poster or icon */}
|
||||||
{item.type === 'command' ? (
|
{item.type === "command" ? (
|
||||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted">
|
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-muted">
|
||||||
{item.icon}
|
{item.icon}
|
||||||
</div>
|
</div>
|
||||||
) : item.posterPath ? (
|
) : item.posterPath ? (
|
||||||
<img
|
<img
|
||||||
src={getTmdbImageUrl(item.posterPath, 'w92')}
|
src={getTmdbImageUrl(item.posterPath, "w92")}
|
||||||
alt=""
|
alt=""
|
||||||
className="h-12 w-8 shrink-0 rounded object-cover"
|
className="h-12 w-8 shrink-0 rounded object-cover"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex h-12 w-8 shrink-0 items-center justify-center rounded bg-muted">
|
<div className="flex h-12 w-8 shrink-0 items-center justify-center rounded bg-muted">
|
||||||
{item.mediaType === 'tv' ? <Tv className="h-4 w-4 text-muted-foreground" /> : <Film className="h-4 w-4 text-muted-foreground" />}
|
{item.mediaType === "tv" ? (
|
||||||
|
<Tv className="h-4 w-4 text-muted-foreground" />
|
||||||
|
) : (
|
||||||
|
<Film className="h-4 w-4 text-muted-foreground" />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -478,9 +547,11 @@ function ResultRow({
|
|||||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
{item.year && <span>{item.year}</span>}
|
{item.year && <span>{item.year}</span>}
|
||||||
{item.mediaType && (
|
{item.mediaType && (
|
||||||
<span className="capitalize">{item.mediaType === 'tv' ? 'TV Series' : 'Movie'}</span>
|
<span className="capitalize">
|
||||||
|
{item.mediaType === "tv" ? "TV Series" : "Movie"}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
{item.rating != null && item.type !== 'command' && (
|
{item.rating != null && item.type !== "command" && (
|
||||||
<span className="flex items-center gap-0.5">
|
<span className="flex items-center gap-0.5">
|
||||||
<Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
|
<Star className="h-3 w-3 fill-yellow-500 text-yellow-500" />
|
||||||
{item.rating}
|
{item.rating}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { useCallback, useRef, useEffect } from 'react';
|
import { useCallback, useRef, useEffect } from "react";
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from "react-router-dom";
|
||||||
import { getCollectionPosterUrl } from '@/lib/media-utils';
|
import { getCollectionPosterUrl } from "@/lib/media-utils";
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import type { Collection } from '@/types';
|
import type { Collection } from "@/types";
|
||||||
|
|
||||||
interface CollectionCardProps {
|
interface CollectionCardProps {
|
||||||
collection: Collection;
|
collection: Collection;
|
||||||
@@ -61,7 +61,7 @@ export function CollectionsGrid({
|
|||||||
});
|
});
|
||||||
if (node) observerRef.current.observe(node);
|
if (node) observerRef.current.observe(node);
|
||||||
},
|
},
|
||||||
[isLoading, hasMore, onLoadMore]
|
[isLoading, hasMore, onLoadMore],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo } from 'react';
|
import { useMemo } from "react";
|
||||||
import {
|
import {
|
||||||
BarChart,
|
BarChart,
|
||||||
Bar,
|
Bar,
|
||||||
@@ -8,30 +8,37 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
Cell,
|
Cell,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
} from 'recharts';
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import {
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
Card,
|
||||||
import { useWatchdayDistribution } from '@/hooks/useStatistics';
|
CardContent,
|
||||||
import type { WatchdayItem } from '@/api/statistics';
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
CardDescription,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { useWatchdayDistribution } from "@/hooks/useStatistics";
|
||||||
|
import type { WatchdayItem } from "@/api/statistics";
|
||||||
|
|
||||||
// DAYOFWEEK: MySQL returns 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat
|
// DAYOFWEEK: MySQL returns 1=Sun, 2=Mon, 3=Tue, 4=Wed, 5=Thu, 6=Fri, 7=Sat
|
||||||
// We display Mon–Sun
|
// We display Mon–Sun
|
||||||
const DAY_ORDER = [2, 3, 4, 5, 6, 7, 1];
|
const DAY_ORDER = [2, 3, 4, 5, 6, 7, 1];
|
||||||
const DAY_LABELS: Record<number, string> = {
|
const DAY_LABELS: Record<number, string> = {
|
||||||
1: 'Sun',
|
1: "Sun",
|
||||||
2: 'Mon',
|
2: "Mon",
|
||||||
3: 'Tue',
|
3: "Tue",
|
||||||
4: 'Wed',
|
4: "Wed",
|
||||||
5: 'Thu',
|
5: "Thu",
|
||||||
6: 'Fri',
|
6: "Fri",
|
||||||
7: 'Sat',
|
7: "Sat",
|
||||||
};
|
};
|
||||||
|
|
||||||
function buildChartData(episodes: WatchdayItem[], movies: WatchdayItem[]) {
|
function buildChartData(episodes: WatchdayItem[], movies: WatchdayItem[]) {
|
||||||
return DAY_ORDER.map((dayNum) => {
|
return DAY_ORDER.map((dayNum) => {
|
||||||
const ep = episodes.find((x) => Number(x.day) === dayNum);
|
const ep = episodes.find((x) => Number(x.day) === dayNum);
|
||||||
const mv = movies.find((x) => Number(x.day) === dayNum);
|
const mv = movies.find((x) => Number(x.day) === dayNum);
|
||||||
const total = (ep ? parseInt(ep.count, 10) : 0) + (mv ? parseInt(mv.count, 10) : 0);
|
const total =
|
||||||
|
(ep ? parseInt(ep.count, 10) : 0) + (mv ? parseInt(mv.count, 10) : 0);
|
||||||
return { day: DAY_LABELS[dayNum], total, dayNum };
|
return { day: DAY_LABELS[dayNum], total, dayNum };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -47,16 +54,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--color-card)',
|
backgroundColor: "var(--color-card)",
|
||||||
border: '1px solid var(--color-border)',
|
border: "1px solid var(--color-border)",
|
||||||
borderRadius: '8px',
|
borderRadius: "8px",
|
||||||
padding: '8px 12px',
|
padding: "8px 12px",
|
||||||
fontSize: '13px',
|
fontSize: "13px",
|
||||||
color: 'var(--color-card-foreground)',
|
color: "var(--color-card-foreground)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p style={{ fontWeight: 600 }}>{day}</p>
|
<p style={{ fontWeight: 600 }}>{day}</p>
|
||||||
<p style={{ color: 'var(--color-muted-foreground)' }}>{total} {total === 1 ? 'watch' : 'watches'}</p>
|
<p style={{ color: "var(--color-muted-foreground)" }}>
|
||||||
|
{total} {total === 1 ? "watch" : "watches"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -71,7 +80,10 @@ export function CouchDayChart() {
|
|||||||
|
|
||||||
const peakDay = useMemo(() => {
|
const peakDay = useMemo(() => {
|
||||||
if (!chartData.length) return null;
|
if (!chartData.length) return null;
|
||||||
return chartData.reduce((max, d) => (d.total > max.total ? d : max), chartData[0]);
|
return chartData.reduce(
|
||||||
|
(max, d) => (d.total > max.total ? d : max),
|
||||||
|
chartData[0],
|
||||||
|
);
|
||||||
}, [chartData]);
|
}, [chartData]);
|
||||||
|
|
||||||
const maxTotal = Math.max(...chartData.map((d) => d.total), 1);
|
const maxTotal = Math.max(...chartData.map((d) => d.total), 1);
|
||||||
@@ -96,29 +108,39 @@ export function CouchDayChart() {
|
|||||||
<Skeleton className="h-52 w-full" />
|
<Skeleton className="h-52 w-full" />
|
||||||
) : (
|
) : (
|
||||||
<ResponsiveContainer width="100%" height={210}>
|
<ResponsiveContainer width="100%" height={210}>
|
||||||
<BarChart data={chartData} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
|
<BarChart
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
|
data={chartData}
|
||||||
|
margin={{ top: 4, right: 8, left: -20, bottom: 0 }}
|
||||||
|
>
|
||||||
|
<CartesianGrid
|
||||||
|
strokeDasharray="3 3"
|
||||||
|
stroke="var(--color-border)"
|
||||||
|
vertical={false}
|
||||||
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="day"
|
dataKey="day"
|
||||||
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
|
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
allowDecimals={false}
|
allowDecimals={false}
|
||||||
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
|
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
/>
|
/>
|
||||||
<Tooltip content={<CustomTooltip />} cursor={{ fill: 'var(--color-accent)' }} />
|
<Tooltip
|
||||||
|
content={<CustomTooltip />}
|
||||||
|
cursor={{ fill: "var(--color-accent)" }}
|
||||||
|
/>
|
||||||
<Bar dataKey="total" radius={[4, 4, 0, 0]}>
|
<Bar dataKey="total" radius={[4, 4, 0, 0]}>
|
||||||
{chartData.map((entry) => (
|
{chartData.map((entry) => (
|
||||||
<Cell
|
<Cell
|
||||||
key={entry.day}
|
key={entry.day}
|
||||||
fill={
|
fill={
|
||||||
entry.total === maxTotal && entry.total > 0
|
entry.total === maxTotal && entry.total > 0
|
||||||
? 'var(--color-chart-4)'
|
? "var(--color-chart-4)"
|
||||||
: 'var(--color-chart-1)'
|
: "var(--color-chart-1)"
|
||||||
}
|
}
|
||||||
opacity={entry.total === 0 ? 0.3 : 1}
|
opacity={entry.total === 0 ? 0.3 : 1}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
AreaChart,
|
AreaChart,
|
||||||
Area,
|
Area,
|
||||||
@@ -7,15 +7,37 @@ import {
|
|||||||
CartesianGrid,
|
CartesianGrid,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
} from 'recharts';
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import {
|
||||||
import { useLibraryEntries } from '@/stores/useLibraryStore';
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
CardDescription,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { useLibraryEntries } from "@/stores/useLibraryStore";
|
||||||
|
|
||||||
const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
const MONTH_LABELS = [
|
||||||
|
"Jan",
|
||||||
|
"Feb",
|
||||||
|
"Mar",
|
||||||
|
"Apr",
|
||||||
|
"May",
|
||||||
|
"Jun",
|
||||||
|
"Jul",
|
||||||
|
"Aug",
|
||||||
|
"Sep",
|
||||||
|
"Oct",
|
||||||
|
"Nov",
|
||||||
|
"Dec",
|
||||||
|
];
|
||||||
|
|
||||||
interface CustomTooltipProps {
|
interface CustomTooltipProps {
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
payload?: { value: number; payload: { month: string; count: number; cumulative: number } }[];
|
payload?: {
|
||||||
|
value: number;
|
||||||
|
payload: { month: string; count: number; cumulative: number };
|
||||||
|
}[];
|
||||||
}
|
}
|
||||||
|
|
||||||
function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
||||||
@@ -24,17 +46,19 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--color-card)',
|
backgroundColor: "var(--color-card)",
|
||||||
border: '1px solid var(--color-border)',
|
border: "1px solid var(--color-border)",
|
||||||
borderRadius: '8px',
|
borderRadius: "8px",
|
||||||
padding: '8px 12px',
|
padding: "8px 12px",
|
||||||
fontSize: '13px',
|
fontSize: "13px",
|
||||||
color: 'var(--color-card-foreground)',
|
color: "var(--color-card-foreground)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p style={{ fontWeight: 600 }}>{d.month}</p>
|
<p style={{ fontWeight: 600 }}>{d.month}</p>
|
||||||
<p style={{ color: 'var(--color-muted-foreground)' }}>+{d.count} added</p>
|
<p style={{ color: "var(--color-muted-foreground)" }}>+{d.count} added</p>
|
||||||
<p style={{ color: 'var(--color-muted-foreground)' }}>{d.cumulative} total</p>
|
<p style={{ color: "var(--color-muted-foreground)" }}>
|
||||||
|
{d.cumulative} total
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -43,8 +67,7 @@ export function LibraryGrowthChart() {
|
|||||||
const allEntries = useLibraryEntries();
|
const allEntries = useLibraryEntries();
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
|
|
||||||
const getEntryDate = (e: { createdAt?: string }) =>
|
const getEntryDate = (e: { createdAt?: string }) => e.createdAt || null;
|
||||||
e.createdAt || null;
|
|
||||||
|
|
||||||
const years = useMemo(() => {
|
const years = useMemo(() => {
|
||||||
const set = new Set<number>();
|
const set = new Set<number>();
|
||||||
@@ -56,16 +79,17 @@ export function LibraryGrowthChart() {
|
|||||||
return Array.from(set).sort((a, b) => b - a);
|
return Array.from(set).sort((a, b) => b - a);
|
||||||
}, [allEntries, currentYear]);
|
}, [allEntries, currentYear]);
|
||||||
|
|
||||||
const [year, setYear] = useState<number | 'all'>('all');
|
const [year, setYear] = useState<number | "all">("all");
|
||||||
|
|
||||||
// Ensure selected year is always valid
|
// Ensure selected year is always valid
|
||||||
const effectiveYear = year === 'all' ? 'all' : (years.includes(year) ? year : years[0]);
|
const effectiveYear =
|
||||||
|
year === "all" ? "all" : years.includes(year) ? year : years[0];
|
||||||
|
|
||||||
const chartData = useMemo(() => {
|
const chartData = useMemo(() => {
|
||||||
// Include all entries (library + watchlist)
|
// Include all entries (library + watchlist)
|
||||||
const entries = allEntries;
|
const entries = allEntries;
|
||||||
|
|
||||||
if (effectiveYear === 'all') {
|
if (effectiveYear === "all") {
|
||||||
// Build monthly data across all years
|
// Build monthly data across all years
|
||||||
const dateEntries = entries
|
const dateEntries = entries
|
||||||
.map((e) => {
|
.map((e) => {
|
||||||
@@ -75,7 +99,11 @@ export function LibraryGrowthChart() {
|
|||||||
.filter(Boolean) as Date[];
|
.filter(Boolean) as Date[];
|
||||||
|
|
||||||
if (dateEntries.length === 0) {
|
if (dateEntries.length === 0) {
|
||||||
return MONTH_LABELS.map((label) => ({ month: label, count: 0, cumulative: 0 }));
|
return MONTH_LABELS.map((label) => ({
|
||||||
|
month: label,
|
||||||
|
count: 0,
|
||||||
|
cumulative: 0,
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
const minYear = Math.min(...dateEntries.map((d) => d.getFullYear()));
|
const minYear = Math.min(...dateEntries.map((d) => d.getFullYear()));
|
||||||
@@ -88,7 +116,7 @@ export function LibraryGrowthChart() {
|
|||||||
for (let y = minYear; y <= maxYear; y++) {
|
for (let y = minYear; y <= maxYear; y++) {
|
||||||
for (let m = 0; m < 12; m++) {
|
for (let m = 0; m < 12; m++) {
|
||||||
const count = dateEntries.filter(
|
const count = dateEntries.filter(
|
||||||
(d) => d.getFullYear() === y && d.getMonth() === m
|
(d) => d.getFullYear() === y && d.getMonth() === m,
|
||||||
).length;
|
).length;
|
||||||
cumulative += count;
|
cumulative += count;
|
||||||
data.push({
|
data.push({
|
||||||
@@ -137,29 +165,50 @@ export function LibraryGrowthChart() {
|
|||||||
value={effectiveYear}
|
value={effectiveYear}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const val = e.target.value;
|
const val = e.target.value;
|
||||||
setYear(val === 'all' ? 'all' : Number(val));
|
setYear(val === "all" ? "all" : Number(val));
|
||||||
}}
|
}}
|
||||||
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
|
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
|
||||||
>
|
>
|
||||||
<option value="all">All</option>
|
<option value="all">All</option>
|
||||||
{years.map((y) => (
|
{years.map((y) => (
|
||||||
<option key={y} value={y}>{y}</option>
|
<option key={y} value={y}>
|
||||||
|
{y}
|
||||||
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ResponsiveContainer width="100%" height={260}>
|
<ResponsiveContainer width="100%" height={260}>
|
||||||
<AreaChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
|
<AreaChart
|
||||||
|
data={chartData}
|
||||||
|
margin={{ top: 4, right: 8, left: -16, bottom: 0 }}
|
||||||
|
>
|
||||||
<defs>
|
<defs>
|
||||||
<linearGradient id="colorGrowth" x1="0" y1="0" x2="0" y2="1">
|
<linearGradient id="colorGrowth" x1="0" y1="0" x2="0" y2="1">
|
||||||
<stop offset="5%" stopColor="var(--color-chart-4)" stopOpacity={0.3} />
|
<stop
|
||||||
<stop offset="95%" stopColor="var(--color-chart-4)" stopOpacity={0} />
|
offset="5%"
|
||||||
|
stopColor="var(--color-chart-4)"
|
||||||
|
stopOpacity={0.3}
|
||||||
|
/>
|
||||||
|
<stop
|
||||||
|
offset="95%"
|
||||||
|
stopColor="var(--color-chart-4)"
|
||||||
|
stopOpacity={0}
|
||||||
|
/>
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
</defs>
|
</defs>
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
|
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
|
||||||
<XAxis dataKey="month" tick={{ fontSize: 12 }} stroke="var(--color-muted-foreground)" />
|
<XAxis
|
||||||
<YAxis tick={{ fontSize: 12 }} stroke="var(--color-muted-foreground)" allowDecimals={false} />
|
dataKey="month"
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
stroke="var(--color-muted-foreground)"
|
||||||
|
/>
|
||||||
|
<YAxis
|
||||||
|
tick={{ fontSize: 12 }}
|
||||||
|
stroke="var(--color-muted-foreground)"
|
||||||
|
allowDecimals={false}
|
||||||
|
/>
|
||||||
<Tooltip content={<CustomTooltip />} />
|
<Tooltip content={<CustomTooltip />} />
|
||||||
<Area
|
<Area
|
||||||
type="monotone"
|
type="monotone"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
PieChart,
|
PieChart,
|
||||||
Pie,
|
Pie,
|
||||||
@@ -6,13 +6,19 @@ import {
|
|||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
Legend,
|
Legend,
|
||||||
} from 'recharts';
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import {
|
||||||
import { useLibraryEntries } from '@/stores/useLibraryStore';
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
CardDescription,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { useLibraryEntries } from "@/stores/useLibraryStore";
|
||||||
|
|
||||||
type Scope = 'library' | 'watchlist';
|
type Scope = "library" | "watchlist";
|
||||||
|
|
||||||
const COLORS = ['var(--color-chart-1)', 'var(--color-chart-2)'];
|
const COLORS = ["var(--color-chart-1)", "var(--color-chart-2)"];
|
||||||
|
|
||||||
interface CustomTooltipProps {
|
interface CustomTooltipProps {
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
@@ -25,33 +31,34 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--color-card)',
|
backgroundColor: "var(--color-card)",
|
||||||
border: '1px solid var(--color-border)',
|
border: "1px solid var(--color-border)",
|
||||||
borderRadius: '8px',
|
borderRadius: "8px",
|
||||||
padding: '8px 12px',
|
padding: "8px 12px",
|
||||||
fontSize: '13px',
|
fontSize: "13px",
|
||||||
color: 'var(--color-card-foreground)',
|
color: "var(--color-card-foreground)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p style={{ fontWeight: 600 }}>{name}</p>
|
<p style={{ fontWeight: 600 }}>{name}</p>
|
||||||
<p style={{ color: 'var(--color-muted-foreground)' }}>{value} titles</p>
|
<p style={{ color: "var(--color-muted-foreground)" }}>{value} titles</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function MediaTypeChart() {
|
export function MediaTypeChart() {
|
||||||
const allEntries = useLibraryEntries();
|
const allEntries = useLibraryEntries();
|
||||||
const [scope, setScope] = useState<Scope>('library');
|
const [scope, setScope] = useState<Scope>("library");
|
||||||
|
|
||||||
const chartData = useMemo(() => {
|
const chartData = useMemo(() => {
|
||||||
const filtered = scope === 'library'
|
const filtered =
|
||||||
|
scope === "library"
|
||||||
? allEntries.filter((e) => !e.watchlist)
|
? allEntries.filter((e) => !e.watchlist)
|
||||||
: allEntries.filter((e) => e.watchlist);
|
: allEntries.filter((e) => e.watchlist);
|
||||||
const movies = filtered.filter((e) => !e.is_tvseries).length;
|
const movies = filtered.filter((e) => !e.is_tvseries).length;
|
||||||
const tv = filtered.filter((e) => e.is_tvseries).length;
|
const tv = filtered.filter((e) => e.is_tvseries).length;
|
||||||
return [
|
return [
|
||||||
{ name: 'Movies', value: movies },
|
{ name: "Movies", value: movies },
|
||||||
{ name: 'TV Series', value: tv },
|
{ name: "TV Series", value: tv },
|
||||||
];
|
];
|
||||||
}, [allEntries, scope]);
|
}, [allEntries, scope]);
|
||||||
|
|
||||||
@@ -68,14 +75,14 @@ export function MediaTypeChart() {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
|
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
|
||||||
{(['library', 'watchlist'] as Scope[]).map((s) => (
|
{(["library", "watchlist"] as Scope[]).map((s) => (
|
||||||
<button
|
<button
|
||||||
key={s}
|
key={s}
|
||||||
onClick={() => setScope(s)}
|
onClick={() => setScope(s)}
|
||||||
className={`px-3 py-1.5 capitalize transition-colors ${
|
className={`px-3 py-1.5 capitalize transition-colors ${
|
||||||
scope === s
|
scope === s
|
||||||
? 'bg-primary text-primary-foreground'
|
? "bg-primary text-primary-foreground"
|
||||||
: 'text-muted-foreground hover:bg-accent'
|
: "text-muted-foreground hover:bg-accent"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{s}
|
{s}
|
||||||
@@ -103,7 +110,11 @@ export function MediaTypeChart() {
|
|||||||
<Tooltip content={<CustomTooltip />} />
|
<Tooltip content={<CustomTooltip />} />
|
||||||
<Legend
|
<Legend
|
||||||
formatter={(value) => (
|
formatter={(value) => (
|
||||||
<span style={{ color: 'var(--color-foreground)', fontSize: '13px' }}>{value}</span>
|
<span
|
||||||
|
style={{ color: "var(--color-foreground)", fontSize: "13px" }}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
</PieChart>
|
</PieChart>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from "react";
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from "react-router-dom";
|
||||||
import {
|
import {
|
||||||
BarChart,
|
BarChart,
|
||||||
Bar,
|
Bar,
|
||||||
@@ -9,12 +9,18 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
Cell,
|
Cell,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
} from 'recharts';
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import {
|
||||||
import { useLibraryEntries } from '@/stores/useLibraryStore';
|
Card,
|
||||||
import type { Entry } from '@/types';
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
CardDescription,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { useLibraryEntries } from "@/stores/useLibraryStore";
|
||||||
|
import type { Entry } from "@/types";
|
||||||
|
|
||||||
type Filter = 'all' | 'movies' | 'series';
|
type Filter = "all" | "movies" | "series";
|
||||||
|
|
||||||
function buildRatingsData(entries: Entry[]) {
|
function buildRatingsData(entries: Entry[]) {
|
||||||
const counts: Record<number, number> = {};
|
const counts: Record<number, number> = {};
|
||||||
@@ -37,16 +43,16 @@ function buildRatingsData(entries: Entry[]) {
|
|||||||
|
|
||||||
// Color ramp: low scores red-ish → mid yellow-ish → high scores green/blue
|
// Color ramp: low scores red-ish → mid yellow-ish → high scores green/blue
|
||||||
const SCORE_COLORS: Record<number, string> = {
|
const SCORE_COLORS: Record<number, string> = {
|
||||||
1: 'var(--color-chart-5)',
|
1: "var(--color-chart-5)",
|
||||||
2: 'var(--color-chart-5)',
|
2: "var(--color-chart-5)",
|
||||||
3: 'var(--color-chart-5)',
|
3: "var(--color-chart-5)",
|
||||||
4: 'var(--color-chart-3)',
|
4: "var(--color-chart-3)",
|
||||||
5: 'var(--color-chart-3)',
|
5: "var(--color-chart-3)",
|
||||||
6: 'var(--color-chart-3)',
|
6: "var(--color-chart-3)",
|
||||||
7: 'var(--color-chart-2)',
|
7: "var(--color-chart-2)",
|
||||||
8: 'var(--color-chart-2)',
|
8: "var(--color-chart-2)",
|
||||||
9: 'var(--color-chart-1)',
|
9: "var(--color-chart-1)",
|
||||||
10: 'var(--color-chart-1)',
|
10: "var(--color-chart-1)",
|
||||||
};
|
};
|
||||||
|
|
||||||
interface CustomTooltipProps {
|
interface CustomTooltipProps {
|
||||||
@@ -60,16 +66,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--color-card)',
|
backgroundColor: "var(--color-card)",
|
||||||
border: '1px solid var(--color-border)',
|
border: "1px solid var(--color-border)",
|
||||||
borderRadius: '8px',
|
borderRadius: "8px",
|
||||||
padding: '8px 12px',
|
padding: "8px 12px",
|
||||||
fontSize: '13px',
|
fontSize: "13px",
|
||||||
color: 'var(--color-card-foreground)',
|
color: "var(--color-card-foreground)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p style={{ fontWeight: 600 }}>{score}</p>
|
<p style={{ fontWeight: 600 }}>{score}</p>
|
||||||
<p style={{ color: 'var(--color-muted-foreground)' }}>{count} {count === 1 ? 'title' : 'titles'}</p>
|
<p style={{ color: "var(--color-muted-foreground)" }}>
|
||||||
|
{count} {count === 1 ? "title" : "titles"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -77,16 +85,19 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
|||||||
export function RatingsChart() {
|
export function RatingsChart() {
|
||||||
const allEntries = useLibraryEntries();
|
const allEntries = useLibraryEntries();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [filter, setFilter] = useState<Filter>('all');
|
const [filter, setFilter] = useState<Filter>("all");
|
||||||
|
|
||||||
const filteredEntries = useMemo(() => {
|
const filteredEntries = useMemo(() => {
|
||||||
const library = allEntries.filter((e) => !e.watchlist);
|
const library = allEntries.filter((e) => !e.watchlist);
|
||||||
if (filter === 'movies') return library.filter((e) => !e.is_tvseries);
|
if (filter === "movies") return library.filter((e) => !e.is_tvseries);
|
||||||
if (filter === 'series') return library.filter((e) => e.is_tvseries);
|
if (filter === "series") return library.filter((e) => e.is_tvseries);
|
||||||
return library;
|
return library;
|
||||||
}, [allEntries, filter]);
|
}, [allEntries, filter]);
|
||||||
|
|
||||||
const chartData = useMemo(() => buildRatingsData(filteredEntries), [filteredEntries]);
|
const chartData = useMemo(
|
||||||
|
() => buildRatingsData(filteredEntries),
|
||||||
|
[filteredEntries],
|
||||||
|
);
|
||||||
|
|
||||||
const ratedCount = filteredEntries.filter(
|
const ratedCount = filteredEntries.filter(
|
||||||
(e) => e.entryRatings?.user_rating != null,
|
(e) => e.entryRatings?.user_rating != null,
|
||||||
@@ -99,18 +110,23 @@ export function RatingsChart() {
|
|||||||
<div>
|
<div>
|
||||||
<CardTitle>My Ratings</CardTitle>
|
<CardTitle>My Ratings</CardTitle>
|
||||||
<CardDescription className="mt-1">
|
<CardDescription className="mt-1">
|
||||||
{ratedCount} rated {filter === 'all' ? 'titles' : filter === 'movies' ? 'movies' : 'series'}
|
{ratedCount} rated{" "}
|
||||||
|
{filter === "all"
|
||||||
|
? "titles"
|
||||||
|
: filter === "movies"
|
||||||
|
? "movies"
|
||||||
|
: "series"}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
|
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
|
||||||
{(['all', 'movies', 'series'] as Filter[]).map((f) => (
|
{(["all", "movies", "series"] as Filter[]).map((f) => (
|
||||||
<button
|
<button
|
||||||
key={f}
|
key={f}
|
||||||
onClick={() => setFilter(f)}
|
onClick={() => setFilter(f)}
|
||||||
className={`px-3 py-1.5 capitalize transition-colors ${
|
className={`px-3 py-1.5 capitalize transition-colors ${
|
||||||
filter === f
|
filter === f
|
||||||
? 'bg-primary text-primary-foreground'
|
? "bg-primary text-primary-foreground"
|
||||||
: 'text-muted-foreground hover:bg-accent'
|
: "text-muted-foreground hover:bg-accent"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{f}
|
{f}
|
||||||
@@ -121,21 +137,31 @@ export function RatingsChart() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ResponsiveContainer width="100%" height={220}>
|
<ResponsiveContainer width="100%" height={220}>
|
||||||
<BarChart data={chartData} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
|
<BarChart
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" vertical={false} />
|
data={chartData}
|
||||||
|
margin={{ top: 4, right: 8, left: -20, bottom: 0 }}
|
||||||
|
>
|
||||||
|
<CartesianGrid
|
||||||
|
strokeDasharray="3 3"
|
||||||
|
stroke="var(--color-border)"
|
||||||
|
vertical={false}
|
||||||
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="score"
|
dataKey="score"
|
||||||
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
|
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
allowDecimals={false}
|
allowDecimals={false}
|
||||||
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
|
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
/>
|
/>
|
||||||
<Tooltip content={<CustomTooltip />} cursor={{ fill: 'var(--color-accent)' }} />
|
<Tooltip
|
||||||
|
content={<CustomTooltip />}
|
||||||
|
cursor={{ fill: "var(--color-accent)" }}
|
||||||
|
/>
|
||||||
<Bar
|
<Bar
|
||||||
dataKey="count"
|
dataKey="count"
|
||||||
radius={[4, 4, 0, 0]}
|
radius={[4, 4, 0, 0]}
|
||||||
@@ -145,12 +171,12 @@ export function RatingsChart() {
|
|||||||
navigate(`/library?ratingMin=${raw}&ratingMax=${raw}`);
|
navigate(`/library?ratingMin=${raw}&ratingMax=${raw}`);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
style={{ cursor: 'pointer' }}
|
style={{ cursor: "pointer" }}
|
||||||
>
|
>
|
||||||
{chartData.map((entry) => (
|
{chartData.map((entry) => (
|
||||||
<Cell
|
<Cell
|
||||||
key={entry.raw}
|
key={entry.raw}
|
||||||
fill={SCORE_COLORS[entry.raw] ?? 'var(--color-chart-1)'}
|
fill={SCORE_COLORS[entry.raw] ?? "var(--color-chart-1)"}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Bar>
|
</Bar>
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
import { useMemo, useState } from 'react';
|
import { useMemo, useState } from "react";
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { Treemap, ResponsiveContainer, Tooltip } from "recharts";
|
||||||
import {
|
import {
|
||||||
Treemap,
|
Card,
|
||||||
ResponsiveContainer,
|
CardContent,
|
||||||
Tooltip,
|
CardHeader,
|
||||||
} from 'recharts';
|
CardTitle,
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
CardDescription,
|
||||||
import { useLibraryEntries } from '@/stores/useLibraryStore';
|
} from "@/components/ui/card";
|
||||||
import type { Entry } from '@/types';
|
import { useLibraryEntries } from "@/stores/useLibraryStore";
|
||||||
|
import type { Entry } from "@/types";
|
||||||
|
|
||||||
type Filter = 'all' | 'movies' | 'series';
|
type Filter = "all" | "movies" | "series";
|
||||||
|
|
||||||
const TOP_N = 10;
|
const TOP_N = 10;
|
||||||
|
|
||||||
const COLORS = [
|
const COLORS = [
|
||||||
'var(--color-chart-1)',
|
"var(--color-chart-1)",
|
||||||
'var(--color-chart-2)',
|
"var(--color-chart-2)",
|
||||||
'var(--color-chart-3)',
|
"var(--color-chart-3)",
|
||||||
'var(--color-chart-4)',
|
"var(--color-chart-4)",
|
||||||
'var(--color-chart-5)',
|
"var(--color-chart-5)",
|
||||||
];
|
];
|
||||||
|
|
||||||
function buildGenreData(entries: Entry[]) {
|
function buildGenreData(entries: Entry[]) {
|
||||||
@@ -26,7 +28,7 @@ function buildGenreData(entries: Entry[]) {
|
|||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
if (!entry.genres) continue;
|
if (!entry.genres) continue;
|
||||||
for (const genre of entry.genres) {
|
for (const genre of entry.genres) {
|
||||||
const name = typeof genre === 'string' ? genre : genre.name;
|
const name = typeof genre === "string" ? genre : genre.name;
|
||||||
if (!name) continue;
|
if (!name) continue;
|
||||||
counts[name] = (counts[name] ?? 0) + 1;
|
counts[name] = (counts[name] ?? 0) + 1;
|
||||||
}
|
}
|
||||||
@@ -34,7 +36,11 @@ function buildGenreData(entries: Entry[]) {
|
|||||||
return Object.entries(counts)
|
return Object.entries(counts)
|
||||||
.sort((a, b) => b[1] - a[1])
|
.sort((a, b) => b[1] - a[1])
|
||||||
.slice(0, TOP_N)
|
.slice(0, TOP_N)
|
||||||
.map(([genre, count], i) => ({ name: genre, size: count, fill: COLORS[i % COLORS.length] }));
|
.map(([genre, count], i) => ({
|
||||||
|
name: genre,
|
||||||
|
size: count,
|
||||||
|
fill: COLORS[i % COLORS.length],
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CustomTooltipProps {
|
interface CustomTooltipProps {
|
||||||
@@ -48,16 +54,18 @@ function CustomTooltip({ active, payload }: CustomTooltipProps) {
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
backgroundColor: 'var(--color-card)',
|
backgroundColor: "var(--color-card)",
|
||||||
border: '1px solid var(--color-border)',
|
border: "1px solid var(--color-border)",
|
||||||
borderRadius: '8px',
|
borderRadius: "8px",
|
||||||
padding: '8px 12px',
|
padding: "8px 12px",
|
||||||
fontSize: '13px',
|
fontSize: "13px",
|
||||||
color: 'var(--color-card-foreground)',
|
color: "var(--color-card-foreground)",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<p style={{ fontWeight: 600 }}>{name}</p>
|
<p style={{ fontWeight: 600 }}>{name}</p>
|
||||||
<p style={{ color: 'var(--color-muted-foreground)' }}>{size} {size === 1 ? 'title' : 'titles'}</p>
|
<p style={{ color: "var(--color-muted-foreground)" }}>
|
||||||
|
{size} {size === 1 ? "title" : "titles"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -83,7 +91,7 @@ function TreemapContent(props: {
|
|||||||
fill={fill}
|
fill={fill}
|
||||||
stroke="var(--color-card)"
|
stroke="var(--color-card)"
|
||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
style={{ cursor: 'pointer' }}
|
style={{ cursor: "pointer" }}
|
||||||
/>
|
/>
|
||||||
{width > 50 && height > 28 && (
|
{width > 50 && height > 28 && (
|
||||||
<text
|
<text
|
||||||
@@ -94,7 +102,7 @@ function TreemapContent(props: {
|
|||||||
fill="white"
|
fill="white"
|
||||||
fontSize={Math.min(12, width / 6)}
|
fontSize={Math.min(12, width / 6)}
|
||||||
fontWeight={500}
|
fontWeight={500}
|
||||||
style={{ pointerEvents: 'none' }}
|
style={{ pointerEvents: "none" }}
|
||||||
>
|
>
|
||||||
{name}
|
{name}
|
||||||
</text>
|
</text>
|
||||||
@@ -106,17 +114,20 @@ function TreemapContent(props: {
|
|||||||
export function TopGenresChart() {
|
export function TopGenresChart() {
|
||||||
const allEntries = useLibraryEntries();
|
const allEntries = useLibraryEntries();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [filter, setFilter] = useState<Filter>('all');
|
const [filter, setFilter] = useState<Filter>("all");
|
||||||
|
|
||||||
const filteredEntries = useMemo(() => {
|
const filteredEntries = useMemo(() => {
|
||||||
// Only count actually watched entries (not watchlist, must be seen)
|
// Only count actually watched entries (not watchlist, must be seen)
|
||||||
const watched = allEntries.filter((e) => !e.watchlist && e.date_last_seen);
|
const watched = allEntries.filter((e) => !e.watchlist && e.date_last_seen);
|
||||||
if (filter === 'movies') return watched.filter((e) => !e.is_tvseries);
|
if (filter === "movies") return watched.filter((e) => !e.is_tvseries);
|
||||||
if (filter === 'series') return watched.filter((e) => e.is_tvseries);
|
if (filter === "series") return watched.filter((e) => e.is_tvseries);
|
||||||
return watched;
|
return watched;
|
||||||
}, [allEntries, filter]);
|
}, [allEntries, filter]);
|
||||||
|
|
||||||
const chartData = useMemo(() => buildGenreData(filteredEntries), [filteredEntries]);
|
const chartData = useMemo(
|
||||||
|
() => buildGenreData(filteredEntries),
|
||||||
|
[filteredEntries],
|
||||||
|
);
|
||||||
|
|
||||||
const handleClick = (node: { name?: string }) => {
|
const handleClick = (node: { name?: string }) => {
|
||||||
if (node?.name) {
|
if (node?.name) {
|
||||||
@@ -135,14 +146,14 @@ export function TopGenresChart() {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
|
<div className="flex rounded-md border border-border overflow-hidden text-xs self-start">
|
||||||
{(['all', 'movies', 'series'] as Filter[]).map((f) => (
|
{(["all", "movies", "series"] as Filter[]).map((f) => (
|
||||||
<button
|
<button
|
||||||
key={f}
|
key={f}
|
||||||
onClick={() => setFilter(f)}
|
onClick={() => setFilter(f)}
|
||||||
className={`px-3 py-1.5 capitalize transition-colors ${
|
className={`px-3 py-1.5 capitalize transition-colors ${
|
||||||
filter === f
|
filter === f
|
||||||
? 'bg-primary text-primary-foreground'
|
? "bg-primary text-primary-foreground"
|
||||||
: 'text-muted-foreground hover:bg-accent'
|
: "text-muted-foreground hover:bg-accent"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{f}
|
{f}
|
||||||
@@ -157,7 +168,16 @@ export function TopGenresChart() {
|
|||||||
data={chartData}
|
data={chartData}
|
||||||
dataKey="size"
|
dataKey="size"
|
||||||
aspectRatio={4 / 3}
|
aspectRatio={4 / 3}
|
||||||
content={<TreemapContent x={0} y={0} width={0} height={0} name="" fill="" />}
|
content={
|
||||||
|
<TreemapContent
|
||||||
|
x={0}
|
||||||
|
y={0}
|
||||||
|
width={0}
|
||||||
|
height={0}
|
||||||
|
name=""
|
||||||
|
fill=""
|
||||||
|
/>
|
||||||
|
}
|
||||||
onClick={handleClick}
|
onClick={handleClick}
|
||||||
>
|
>
|
||||||
<Tooltip content={<CustomTooltip />} />
|
<Tooltip content={<CustomTooltip />} />
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useMemo } from 'react';
|
import { useState, useMemo } from "react";
|
||||||
import {
|
import {
|
||||||
AreaChart,
|
AreaChart,
|
||||||
Area,
|
Area,
|
||||||
@@ -8,14 +8,33 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
Legend,
|
Legend,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
} from 'recharts';
|
} from "recharts";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import {
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
Card,
|
||||||
import { useYearlyWatchCount } from '@/hooks/useStatistics';
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
CardDescription,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { useYearlyWatchCount } from "@/hooks/useStatistics";
|
||||||
|
|
||||||
const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
const MONTH_LABELS = [
|
||||||
|
"Jan",
|
||||||
|
"Feb",
|
||||||
|
"Mar",
|
||||||
|
"Apr",
|
||||||
|
"May",
|
||||||
|
"Jun",
|
||||||
|
"Jul",
|
||||||
|
"Aug",
|
||||||
|
"Sep",
|
||||||
|
"Oct",
|
||||||
|
"Nov",
|
||||||
|
"Dec",
|
||||||
|
];
|
||||||
|
|
||||||
type Filter = 'all' | 'movies' | 'episodes';
|
type Filter = "all" | "movies" | "episodes";
|
||||||
|
|
||||||
function buildChartData(
|
function buildChartData(
|
||||||
series: { month: number; count: string }[],
|
series: { month: number; count: string }[],
|
||||||
@@ -36,7 +55,7 @@ function buildChartData(
|
|||||||
export function WatchActivityChart() {
|
export function WatchActivityChart() {
|
||||||
const currentYear = new Date().getFullYear();
|
const currentYear = new Date().getFullYear();
|
||||||
const [year, setYear] = useState(currentYear);
|
const [year, setYear] = useState(currentYear);
|
||||||
const [filter, setFilter] = useState<Filter>('all');
|
const [filter, setFilter] = useState<Filter>("all");
|
||||||
|
|
||||||
const { data, isLoading } = useYearlyWatchCount(year);
|
const { data, isLoading } = useYearlyWatchCount(year);
|
||||||
|
|
||||||
@@ -47,8 +66,8 @@ export function WatchActivityChart() {
|
|||||||
|
|
||||||
const years = Array.from({ length: 8 }, (_, i) => currentYear - i);
|
const years = Array.from({ length: 8 }, (_, i) => currentYear - i);
|
||||||
|
|
||||||
const showMovies = filter === 'all' || filter === 'movies';
|
const showMovies = filter === "all" || filter === "movies";
|
||||||
const showEpisodes = filter === 'all' || filter === 'episodes';
|
const showEpisodes = filter === "all" || filter === "episodes";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card>
|
<Card>
|
||||||
@@ -63,14 +82,14 @@ export function WatchActivityChart() {
|
|||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
{/* Filter tabs */}
|
{/* Filter tabs */}
|
||||||
<div className="flex rounded-md border border-border overflow-hidden text-xs">
|
<div className="flex rounded-md border border-border overflow-hidden text-xs">
|
||||||
{(['all', 'movies', 'episodes'] as Filter[]).map((f) => (
|
{(["all", "movies", "episodes"] as Filter[]).map((f) => (
|
||||||
<button
|
<button
|
||||||
key={f}
|
key={f}
|
||||||
onClick={() => setFilter(f)}
|
onClick={() => setFilter(f)}
|
||||||
className={`px-3 py-1.5 capitalize transition-colors ${
|
className={`px-3 py-1.5 capitalize transition-colors ${
|
||||||
filter === f
|
filter === f
|
||||||
? 'bg-primary text-primary-foreground'
|
? "bg-primary text-primary-foreground"
|
||||||
: 'text-muted-foreground hover:bg-accent'
|
: "text-muted-foreground hover:bg-accent"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{f}
|
{f}
|
||||||
@@ -84,7 +103,9 @@ export function WatchActivityChart() {
|
|||||||
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
|
className="rounded-md border border-border bg-card text-foreground text-xs px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-ring"
|
||||||
>
|
>
|
||||||
{years.map((y) => (
|
{years.map((y) => (
|
||||||
<option key={y} value={y}>{y}</option>
|
<option key={y} value={y}>
|
||||||
|
{y}
|
||||||
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
@@ -95,43 +116,72 @@ export function WatchActivityChart() {
|
|||||||
<Skeleton className="h-64 w-full" />
|
<Skeleton className="h-64 w-full" />
|
||||||
) : (
|
) : (
|
||||||
<ResponsiveContainer width="100%" height={260}>
|
<ResponsiveContainer width="100%" height={260}>
|
||||||
<AreaChart data={chartData} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
|
<AreaChart
|
||||||
|
data={chartData}
|
||||||
|
margin={{ top: 4, right: 8, left: -16, bottom: 0 }}
|
||||||
|
>
|
||||||
<defs>
|
<defs>
|
||||||
<linearGradient id="colorMovies" x1="0" y1="0" x2="0" y2="1">
|
<linearGradient id="colorMovies" x1="0" y1="0" x2="0" y2="1">
|
||||||
<stop offset="5%" stopColor="var(--color-chart-1)" stopOpacity={0.3} />
|
<stop
|
||||||
<stop offset="95%" stopColor="var(--color-chart-1)" stopOpacity={0} />
|
offset="5%"
|
||||||
|
stopColor="var(--color-chart-1)"
|
||||||
|
stopOpacity={0.3}
|
||||||
|
/>
|
||||||
|
<stop
|
||||||
|
offset="95%"
|
||||||
|
stopColor="var(--color-chart-1)"
|
||||||
|
stopOpacity={0}
|
||||||
|
/>
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
<linearGradient id="colorEpisodes" x1="0" y1="0" x2="0" y2="1">
|
<linearGradient id="colorEpisodes" x1="0" y1="0" x2="0" y2="1">
|
||||||
<stop offset="5%" stopColor="var(--color-chart-2)" stopOpacity={0.3} />
|
<stop
|
||||||
<stop offset="95%" stopColor="var(--color-chart-2)" stopOpacity={0} />
|
offset="5%"
|
||||||
|
stopColor="var(--color-chart-2)"
|
||||||
|
stopOpacity={0.3}
|
||||||
|
/>
|
||||||
|
<stop
|
||||||
|
offset="95%"
|
||||||
|
stopColor="var(--color-chart-2)"
|
||||||
|
stopOpacity={0}
|
||||||
|
/>
|
||||||
</linearGradient>
|
</linearGradient>
|
||||||
</defs>
|
</defs>
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
|
<CartesianGrid
|
||||||
|
strokeDasharray="3 3"
|
||||||
|
stroke="var(--color-border)"
|
||||||
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="month"
|
dataKey="month"
|
||||||
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
|
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
/>
|
/>
|
||||||
<YAxis
|
<YAxis
|
||||||
allowDecimals={false}
|
allowDecimals={false}
|
||||||
tick={{ fontSize: 12, fill: 'var(--color-muted-foreground)' }}
|
tick={{ fontSize: 12, fill: "var(--color-muted-foreground)" }}
|
||||||
axisLine={false}
|
axisLine={false}
|
||||||
tickLine={false}
|
tickLine={false}
|
||||||
/>
|
/>
|
||||||
<Tooltip
|
<Tooltip
|
||||||
contentStyle={{
|
contentStyle={{
|
||||||
backgroundColor: 'var(--color-card)',
|
backgroundColor: "var(--color-card)",
|
||||||
border: '1px solid var(--color-border)',
|
border: "1px solid var(--color-border)",
|
||||||
borderRadius: '8px',
|
borderRadius: "8px",
|
||||||
fontSize: '13px',
|
fontSize: "13px",
|
||||||
color: 'var(--color-card-foreground)',
|
color: "var(--color-card-foreground)",
|
||||||
}}
|
}}
|
||||||
cursor={{ stroke: 'var(--color-border)', strokeWidth: 1 }}
|
cursor={{ stroke: "var(--color-border)", strokeWidth: 1 }}
|
||||||
/>
|
/>
|
||||||
<Legend
|
<Legend
|
||||||
formatter={(value) => (
|
formatter={(value) => (
|
||||||
<span style={{ fontSize: 12, color: 'var(--color-muted-foreground)' }}>{value}</span>
|
<span
|
||||||
|
style={{
|
||||||
|
fontSize: 12,
|
||||||
|
color: "var(--color-muted-foreground)",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{value}
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
{showMovies && (
|
{showMovies && (
|
||||||
@@ -142,7 +192,11 @@ export function WatchActivityChart() {
|
|||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
fill="url(#colorMovies)"
|
fill="url(#colorMovies)"
|
||||||
dot={false}
|
dot={false}
|
||||||
activeDot={{ r: 4, strokeWidth: 0, fill: 'var(--color-chart-1)' }}
|
activeDot={{
|
||||||
|
r: 4,
|
||||||
|
strokeWidth: 0,
|
||||||
|
fill: "var(--color-chart-1)",
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{showEpisodes && (
|
{showEpisodes && (
|
||||||
@@ -153,7 +207,11 @@ export function WatchActivityChart() {
|
|||||||
strokeWidth={2}
|
strokeWidth={2}
|
||||||
fill="url(#colorEpisodes)"
|
fill="url(#colorEpisodes)"
|
||||||
dot={false}
|
dot={false}
|
||||||
activeDot={{ r: 4, strokeWidth: 0, fill: 'var(--color-chart-2)' }}
|
activeDot={{
|
||||||
|
r: 4,
|
||||||
|
strokeWidth: 0,
|
||||||
|
fill: "var(--color-chart-2)",
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</AreaChart>
|
</AreaChart>
|
||||||
|
|||||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user