Director field, search, and collection improvements
Backend: Added director column to Entry model, set during creation and refresh. Maintenance endpoint to scan/fix missing directors. Reverted expensive credit JOIN in getAllEntries. Frontend: @director: search prefix for Library and Watchlist. Director rendered on EntryDetailsPage via useEntryCredits. Fixed home page cards to link directly to EntryDetailsPage when entry is in library. Added TmdbCastsPage for TMDB cast browsing. Persisted collection sort order and gray-out-unseen toggle. Tooltip component now theme-aware.
This commit is contained in:
1 parent
8671184dc5
commit
5a0328a17f
16 files changed
+1650
-600
No files matched your search
@@ -1,9 +1,8 @@
|
|||||||
const maintenanceService = require('../services/maintenanceService');
|
const maintenanceService = require("../services/maintenanceService");
|
||||||
|
|
||||||
const _maintenanceService = maintenanceService;
|
const _maintenanceService = maintenanceService;
|
||||||
|
|
||||||
class MaintenanceController {
|
class MaintenanceController {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!MaintenanceController.instance) {
|
if (!MaintenanceController.instance) {
|
||||||
MaintenanceController.instance = this;
|
MaintenanceController.instance = this;
|
||||||
@@ -45,6 +44,15 @@ class MaintenanceController {
|
|||||||
return res.status(200).json(result);
|
return res.status(200).json(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getMissingDirectors(req, res) {
|
||||||
|
const result = await _maintenanceService.fixMissingDirectors(true);
|
||||||
|
return res.status(200).json(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fixMissingDirectors(req, res) {
|
||||||
|
const result = await _maintenanceService.fixMissingDirectors();
|
||||||
|
return res.status(200).json(result);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new MaintenanceController();
|
module.exports = new MaintenanceController();
|
||||||
+32
-21
@@ -1,14 +1,13 @@
|
|||||||
const { DataTypes } = require('sequelize');
|
const { DataTypes } = require("sequelize");
|
||||||
const sequelize = require('../config/database');
|
const sequelize = require("../config/database");
|
||||||
|
|
||||||
const Entry = sequelize.define("entry",
|
const Entry = sequelize.define("entry", {
|
||||||
{
|
|
||||||
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
|
||||||
|
|
||||||
title: { type: DataTypes.STRING(500) },
|
title: { type: DataTypes.STRING(500) },
|
||||||
original_title: { type: DataTypes.STRING(100), field: 'original_title' },
|
original_title: { type: DataTypes.STRING(100), field: "original_title" },
|
||||||
release_date: { type: DataTypes.DATE, field: 'release_date' },
|
release_date: { type: DataTypes.DATE, field: "release_date" },
|
||||||
release_status: { type: DataTypes.STRING(50), field: 'release_status' },
|
release_status: { type: DataTypes.STRING(50), field: "release_status" },
|
||||||
runtime: { type: DataTypes.INTEGER },
|
runtime: { type: DataTypes.INTEGER },
|
||||||
|
|
||||||
tagline: { type: DataTypes.STRING(200) },
|
tagline: { type: DataTypes.STRING(200) },
|
||||||
@@ -16,32 +15,44 @@ const Entry = sequelize.define("entry",
|
|||||||
country: { type: DataTypes.STRING(30) },
|
country: { type: DataTypes.STRING(30) },
|
||||||
|
|
||||||
certification: { type: DataTypes.INTEGER },
|
certification: { type: DataTypes.INTEGER },
|
||||||
network_studio: { type: DataTypes.STRING(40), field: 'network_studio' },
|
network_studio: { type: DataTypes.STRING(40), field: "network_studio" },
|
||||||
collection_id: { type: DataTypes.INTEGER, field: 'collection_id' },
|
collection_id: { type: DataTypes.INTEGER, field: "collection_id" },
|
||||||
max_cast: { type: DataTypes.INTEGER, field: 'max_cast', defaultValue: 10 },
|
max_cast: { type: DataTypes.INTEGER, field: "max_cast", defaultValue: 10 },
|
||||||
credit_fetched: { type: DataTypes.BOOLEAN, defaultValue: false, field: 'credit_fetched' },
|
credit_fetched: {
|
||||||
|
type: DataTypes.BOOLEAN,
|
||||||
|
defaultValue: false,
|
||||||
|
field: "credit_fetched",
|
||||||
|
},
|
||||||
|
|
||||||
watchlist: { type: DataTypes.BOOLEAN, defaultValue: false },
|
watchlist: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
favorit: { type: DataTypes.BOOLEAN, defaultValue: false },
|
favorit: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
hidden: { type: DataTypes.BOOLEAN, defaultValue: false },
|
hidden: { type: DataTypes.BOOLEAN, defaultValue: false },
|
||||||
showInCalendar: { type: DataTypes.BOOLEAN, defaultValue: true, field: 'show_in_calendar' },
|
showInCalendar: {
|
||||||
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: 'auto_sync' },
|
type: DataTypes.BOOLEAN,
|
||||||
|
defaultValue: true,
|
||||||
|
field: "show_in_calendar",
|
||||||
|
},
|
||||||
|
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: "auto_sync" },
|
||||||
|
|
||||||
note: { type: DataTypes.STRING(2000) },
|
note: { type: DataTypes.STRING(2000) },
|
||||||
|
|
||||||
is_tvseries: { type: DataTypes.BOOLEAN, field: 'is_tvseries' },
|
is_tvseries: { type: DataTypes.BOOLEAN, field: "is_tvseries" },
|
||||||
status: { type: DataTypes.STRING(20) },
|
status: { type: DataTypes.STRING(20) },
|
||||||
|
|
||||||
poster_path: { type: DataTypes.STRING(200), field: 'poster_path' },
|
poster_path: { type: DataTypes.STRING(200), field: "poster_path" },
|
||||||
banner_path: { type: DataTypes.STRING(200), field: 'banner_path' },
|
banner_path: { type: DataTypes.STRING(200), field: "banner_path" },
|
||||||
|
|
||||||
date_first_seen: { type: DataTypes.DATEONLY, field: 'date_first_seen' },
|
date_first_seen: { type: DataTypes.DATEONLY, field: "date_first_seen" },
|
||||||
date_last_seen: { type: DataTypes.DATEONLY, field: 'date_last_seen' },
|
date_last_seen: { type: DataTypes.DATEONLY, field: "date_last_seen" },
|
||||||
|
|
||||||
last_fetch: { type: DataTypes.DATEONLY },
|
last_fetch: { type: DataTypes.DATEONLY },
|
||||||
|
|
||||||
entry_sync_status: { type: DataTypes.STRING(50), field: 'entry_sync_status', allowNull: true },
|
entry_sync_status: {
|
||||||
}
|
type: DataTypes.STRING(50),
|
||||||
);
|
field: "entry_sync_status",
|
||||||
|
allowNull: true,
|
||||||
|
},
|
||||||
|
director: { type: DataTypes.STRING(200), allowNull: true },
|
||||||
|
});
|
||||||
|
|
||||||
module.exports = Entry;
|
module.exports = Entry;
|
||||||
@@ -1,25 +1,49 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const maintenanceRouter = express.Router();
|
const maintenanceRouter = express.Router();
|
||||||
|
|
||||||
const maintenanceController = require('../controllers/maintenanceController');
|
const maintenanceController = require("../controllers/maintenanceController");
|
||||||
|
|
||||||
// ! /maintenance
|
// ! /maintenance
|
||||||
// * GET - Orphan files
|
// * GET - Orphan files
|
||||||
maintenanceRouter.get('/orphan-files', maintenanceController.getOrpanFiles);
|
maintenanceRouter.get("/orphan-files", maintenanceController.getOrpanFiles);
|
||||||
|
|
||||||
// * GET - Missing files
|
// * GET - Missing files
|
||||||
maintenanceRouter.get('/orphan-media-records', maintenanceController.getOrphanMediaRecords);
|
maintenanceRouter.get(
|
||||||
|
"/orphan-media-records",
|
||||||
|
maintenanceController.getOrphanMediaRecords,
|
||||||
|
);
|
||||||
|
|
||||||
// * DELETE - Orphan files
|
// * DELETE - Orphan files
|
||||||
maintenanceRouter.delete('/orphan-files', maintenanceController.deleteOrpanFiles);
|
maintenanceRouter.delete(
|
||||||
|
"/orphan-files",
|
||||||
|
maintenanceController.deleteOrpanFiles,
|
||||||
|
);
|
||||||
|
|
||||||
// * DELETE - Missing files
|
// * DELETE - Missing files
|
||||||
maintenanceRouter.delete('/orphan-media-records', maintenanceController.deleteOrphanMediaRecords);
|
maintenanceRouter.delete(
|
||||||
|
"/orphan-media-records",
|
||||||
|
maintenanceController.deleteOrphanMediaRecords,
|
||||||
|
);
|
||||||
|
|
||||||
// * GET - Orphan people (dry run)
|
// * GET - Orphan people (dry run)
|
||||||
maintenanceRouter.get('/orphan-people', maintenanceController.getOrphanPeople);
|
maintenanceRouter.get("/orphan-people", maintenanceController.getOrphanPeople);
|
||||||
|
|
||||||
// * DELETE - Orphan people
|
// * DELETE - Orphan people
|
||||||
maintenanceRouter.delete('/orphan-people', maintenanceController.deleteOrphanPeople);
|
maintenanceRouter.delete(
|
||||||
|
"/orphan-people",
|
||||||
|
maintenanceController.deleteOrphanPeople,
|
||||||
|
);
|
||||||
|
|
||||||
|
// * GET - Missing directors count
|
||||||
|
maintenanceRouter.get(
|
||||||
|
"/missing-directors",
|
||||||
|
maintenanceController.getMissingDirectors,
|
||||||
|
);
|
||||||
|
|
||||||
|
// * POST - Fix missing directors
|
||||||
|
maintenanceRouter.post(
|
||||||
|
"/missing-directors",
|
||||||
|
maintenanceController.fixMissingDirectors,
|
||||||
|
);
|
||||||
|
|
||||||
module.exports = maintenanceRouter;
|
module.exports = maintenanceRouter;
|
||||||
+190
-104
@@ -17,9 +17,13 @@ const BadRequestError = require("../errors/BadRequestError");
|
|||||||
const NotFoundError = require("../errors/NotFoundError.js");
|
const NotFoundError = require("../errors/NotFoundError.js");
|
||||||
const ValidationError = require("../errors/ValidationError.js");
|
const ValidationError = require("../errors/ValidationError.js");
|
||||||
|
|
||||||
const { fetchEntryData, fetchSeasonData, fetchEntryCredits } = require("./tmdbService.js");
|
const {
|
||||||
|
fetchEntryData,
|
||||||
|
fetchSeasonData,
|
||||||
|
fetchEntryCredits,
|
||||||
|
} = require("./tmdbService.js");
|
||||||
const { logToFile } = require("./logService.js");
|
const { logToFile } = require("./logService.js");
|
||||||
const collectionManager = require('./collectionManager.js');
|
const collectionManager = require("./collectionManager.js");
|
||||||
const entryService = require("./entryService");
|
const entryService = require("./entryService");
|
||||||
const mediaManager = require("./mediaManager.js");
|
const mediaManager = require("./mediaManager.js");
|
||||||
const networkService = require("./networkService.js");
|
const networkService = require("./networkService.js");
|
||||||
@@ -30,7 +34,6 @@ const _entryService = entryService;
|
|||||||
const _mediaManager = mediaManager;
|
const _mediaManager = mediaManager;
|
||||||
const _networkService = networkService;
|
const _networkService = networkService;
|
||||||
class EntryManager {
|
class EntryManager {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EntryManager.instance) {
|
if (!EntryManager.instance) {
|
||||||
EntryManager.instance = this;
|
EntryManager.instance = this;
|
||||||
@@ -45,7 +48,9 @@ class EntryManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (typeof type !== "boolean") {
|
if (typeof type !== "boolean") {
|
||||||
throw new BadRequestError(`Invalid type: ${type}. Expected a boolean value.`);
|
throw new BadRequestError(
|
||||||
|
`Invalid type: ${type}. Expected a boolean value.`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// * 1 - fetch entry data
|
// * 1 - fetch entry data
|
||||||
@@ -57,10 +62,19 @@ class EntryManager {
|
|||||||
// * 2 - insert the entry into db
|
// * 2 - insert the entry into db
|
||||||
const entry = await _entryService.createEntry(entryData, plain);
|
const entry = await _entryService.createEntry(entryData, plain);
|
||||||
|
|
||||||
console.log('Entry created with ID:', entry.id, 'and title:', entry.title, 'and is_tvseries:', entry.is_tvseries);
|
console.log(
|
||||||
|
"Entry created with ID:",
|
||||||
|
entry.id,
|
||||||
|
"and title:",
|
||||||
|
entry.title,
|
||||||
|
"and is_tvseries:",
|
||||||
|
entry.is_tvseries,
|
||||||
|
);
|
||||||
// * 3 - created the related collection
|
// * 3 - created the related collection
|
||||||
if (entryData.belongs_to_collection && fetchCollection) {
|
if (entryData.belongs_to_collection && fetchCollection) {
|
||||||
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
|
await _collectionManager.fetchAndSaveCollection(
|
||||||
|
entryData.belongs_to_collection.id,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return entry;
|
return entry;
|
||||||
@@ -84,7 +98,10 @@ class EntryManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ? 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) {
|
if (!entryData) {
|
||||||
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
throw new InternalServerError(`Counldn't fetch data from TMDB`);
|
||||||
}
|
}
|
||||||
@@ -99,14 +116,17 @@ class EntryManager {
|
|||||||
|
|
||||||
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 _entryService.updateEntryById(id, newData, false);
|
const savedEntry = await _entryService.updateEntryById(id, newData, false);
|
||||||
@@ -119,11 +139,11 @@ class EntryManager {
|
|||||||
|
|
||||||
// * 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;
|
||||||
@@ -131,19 +151,20 @@ class EntryManager {
|
|||||||
// 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,
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// * networks
|
// * networks
|
||||||
if (entryData.networks) {
|
if (entryData.networks) {
|
||||||
const oldNetworksIds = oldEntry.networks.map(network => network.id);
|
const oldNetworksIds = oldEntry.networks.map((network) => network.id);
|
||||||
for (const networkData of entryData.networks) {
|
for (const networkData of entryData.networks) {
|
||||||
// If the entry already has this network, skip it
|
// If the entry already has this network, skip it
|
||||||
if (oldNetworksIds.includes(networkData.id)) continue;
|
if (oldNetworksIds.includes(networkData.id)) continue;
|
||||||
|
|
||||||
// Create or update the network
|
// Create or update the network
|
||||||
const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData);
|
const [oldNetwork, newNetwork] =
|
||||||
|
await _networkService.createOrUpdateNetwork(networkData);
|
||||||
let network = oldNetwork || newNetwork;
|
let network = oldNetwork || newNetwork;
|
||||||
if (!network) {
|
if (!network) {
|
||||||
throw new NotFoundError("Network not found");
|
throw new NotFoundError("Network not found");
|
||||||
@@ -162,16 +183,17 @@ class EntryManager {
|
|||||||
// * 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,
|
||||||
},
|
},
|
||||||
include: [
|
include: [{ model: Media, as: "medias" }],
|
||||||
{ model: Media, as: 'medias' }
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// If the season exists, update it; otherwise, create a new season
|
// If the season exists, update it; otherwise, create a new season
|
||||||
@@ -215,9 +237,7 @@ class EntryManager {
|
|||||||
where: {
|
where: {
|
||||||
tmdb_id: episode.id,
|
tmdb_id: episode.id,
|
||||||
},
|
},
|
||||||
include: [
|
include: [{ model: Media, as: "medias" }],
|
||||||
{ model: Media, as: 'medias' }
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// If the episode exists, update it; otherwise, create a new episode
|
// If the episode exists, update it; otherwise, create a new episode
|
||||||
@@ -259,32 +279,39 @@ class EntryManager {
|
|||||||
// * Credits
|
// * Credits
|
||||||
// if (!oldEntry.cast_fetched || oldEntry.credits.length === 0) {
|
// if (!oldEntry.cast_fetched || oldEntry.credits.length === 0) {
|
||||||
if (true) {
|
if (true) {
|
||||||
const creditData = await fetchEntryCredits(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
const creditData = await fetchEntryCredits(
|
||||||
|
oldEntry.entryId.tmdb_id,
|
||||||
|
oldEntry.is_tvseries,
|
||||||
|
);
|
||||||
|
|
||||||
if (!creditData) {
|
if (!creditData) {
|
||||||
throw new InternalServerError(`Couldn't fetch entry crew data`);
|
throw new InternalServerError(`Couldn't fetch entry crew data`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const allCredits = [
|
const allCredits = [
|
||||||
...creditData.cast.map(c => ({ ...c, cast_type: "cast" })),
|
...creditData.cast.map((c) => ({ ...c, cast_type: "cast" })),
|
||||||
...creditData.crew.map(c => ({ ...c, cast_type: "crew" }))
|
...creditData.crew.map((c) => ({ ...c, cast_type: "crew" })),
|
||||||
];
|
];
|
||||||
|
|
||||||
const tmdbIds = [...new Set(allCredits.map(c => c.id))];
|
const tmdbIds = [...new Set(allCredits.map((c) => c.id))];
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// FETCH EXISTING PEOPLE
|
// FETCH EXISTING PEOPLE
|
||||||
// -------------------------
|
// -------------------------
|
||||||
const existingPeopleList = await People.findAll({ where: { tmdb_id: tmdbIds } });
|
const existingPeopleList = await People.findAll({
|
||||||
const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p]));
|
where: { tmdb_id: tmdbIds },
|
||||||
|
});
|
||||||
|
const existingPeopleMap = Object.fromEntries(
|
||||||
|
existingPeopleList.map((p) => [p.tmdb_id, p]),
|
||||||
|
);
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// CREATE NEW PEOPLE
|
// CREATE NEW PEOPLE
|
||||||
// -------------------------
|
// -------------------------
|
||||||
const newPeopleData = tmdbIds
|
const newPeopleData = tmdbIds
|
||||||
.filter(id => !existingPeopleMap[id])
|
.filter((id) => !existingPeopleMap[id])
|
||||||
.map(id => {
|
.map((id) => {
|
||||||
const credit = allCredits.find(c => c.id === id);
|
const credit = allCredits.find((c) => c.id === id);
|
||||||
return {
|
return {
|
||||||
tmdb_id: credit.id,
|
tmdb_id: credit.id,
|
||||||
name: credit.name,
|
name: credit.name,
|
||||||
@@ -293,7 +320,7 @@ class EntryManager {
|
|||||||
known_for_department: credit.known_for_department || null,
|
known_for_department: credit.known_for_department || null,
|
||||||
profile_path: credit.profile_path,
|
profile_path: credit.profile_path,
|
||||||
adult: credit.adult || false,
|
adult: credit.adult || false,
|
||||||
last_fetch: new Date()
|
last_fetch: new Date(),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -304,7 +331,9 @@ class EntryManager {
|
|||||||
const createdPeople = await People.bulkCreate(newPeopleData);
|
const createdPeople = await People.bulkCreate(newPeopleData);
|
||||||
|
|
||||||
for (const person of createdPeople) {
|
for (const person of createdPeople) {
|
||||||
console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`);
|
console.log(
|
||||||
|
`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`,
|
||||||
|
);
|
||||||
existingPeopleMap[person.tmdb_id] = person;
|
existingPeopleMap[person.tmdb_id] = person;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -328,31 +357,36 @@ class EntryManager {
|
|||||||
|
|
||||||
if (peopleToUpdate.length) {
|
if (peopleToUpdate.length) {
|
||||||
await People.bulkCreate(
|
await People.bulkCreate(
|
||||||
peopleToUpdate.map(p => ({
|
peopleToUpdate.map((p) => ({
|
||||||
id: p.id,
|
id: p.id,
|
||||||
tmdb_id: p.tmdb_id,
|
tmdb_id: p.tmdb_id,
|
||||||
popularity: p.popularity,
|
popularity: p.popularity,
|
||||||
last_fetch: p.last_fetch
|
last_fetch: p.last_fetch,
|
||||||
})),
|
})),
|
||||||
{
|
{
|
||||||
updateOnDuplicate: ["popularity", "last_fetch"]
|
updateOnDuplicate: ["popularity", "last_fetch"],
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
console.log(`[PEOPLE] Updated popularity for ${peopleToUpdate.length} people`);
|
console.log(
|
||||||
|
`[PEOPLE] Updated popularity for ${peopleToUpdate.length} people`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
// FETCH EXISTING CREDITS FOR ENTRY
|
// FETCH EXISTING CREDITS FOR ENTRY
|
||||||
// -------------------------
|
// -------------------------
|
||||||
const existingCreditsList = await Credit.findAll({
|
const existingCreditsList = await Credit.findAll({
|
||||||
where: { entry_id: oldEntry.id }
|
where: { entry_id: oldEntry.id },
|
||||||
});
|
});
|
||||||
|
|
||||||
const existingCreditsMap = new Map();
|
const existingCreditsMap = new Map();
|
||||||
for (const credit of existingCreditsList) {
|
for (const credit of existingCreditsList) {
|
||||||
// unique key: people_id + cast_type (scoped to entry_id already)
|
// unique key: people_id + cast_type (scoped to entry_id already)
|
||||||
existingCreditsMap.set(`${credit.people_id}_${credit.cast_type}`, credit);
|
existingCreditsMap.set(
|
||||||
|
`${credit.people_id}_${credit.cast_type}`,
|
||||||
|
credit,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const creditsToInsert = [];
|
const creditsToInsert = [];
|
||||||
@@ -367,16 +401,24 @@ class EntryManager {
|
|||||||
|
|
||||||
// For TV series (aggregate_credits), character/job are nested inside roles[]/jobs[].
|
// For TV series (aggregate_credits), character/job are nested inside roles[]/jobs[].
|
||||||
// Detect TV format by presence of roles/jobs arrays rather than relying on is_tvseries.
|
// Detect TV format by presence of roles/jobs arrays rather than relying on is_tvseries.
|
||||||
const character = c.cast_type === "cast"
|
const character =
|
||||||
? (Array.isArray(c.roles)
|
c.cast_type === "cast"
|
||||||
? (c.roles.map(r => r.character).filter(Boolean).join("; ") || null)
|
? Array.isArray(c.roles)
|
||||||
: (c.character || null))
|
? c.roles
|
||||||
|
.map((r) => r.character)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join("; ") || null
|
||||||
|
: c.character || null
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const job = c.cast_type === "crew"
|
const job =
|
||||||
? (Array.isArray(c.jobs)
|
c.cast_type === "crew"
|
||||||
? (c.jobs.map(j => j.job).filter(Boolean).join("; ") || null)
|
? Array.isArray(c.jobs)
|
||||||
: (c.job || null))
|
? c.jobs
|
||||||
|
.map((j) => j.job)
|
||||||
|
.filter(Boolean)
|
||||||
|
.join("; ") || null
|
||||||
|
: c.job || null
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const tmdbCreditId = Array.isArray(c.roles)
|
const tmdbCreditId = Array.isArray(c.roles)
|
||||||
@@ -396,32 +438,35 @@ class EntryManager {
|
|||||||
adult: person.adult,
|
adult: person.adult,
|
||||||
cast_type: c.cast_type,
|
cast_type: c.cast_type,
|
||||||
department: c.cast_type === "crew" ? c.department || null : null,
|
department: c.cast_type === "crew" ? c.department || null : null,
|
||||||
job
|
job,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!existingCredit) {
|
if (!existingCredit) {
|
||||||
creditsToInsert.push(newCreditData);
|
creditsToInsert.push(newCreditData);
|
||||||
console.log(
|
console.log(
|
||||||
`[CREDIT] INSERT ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`
|
`[CREDIT] INSERT ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// check if update needed
|
// check if update needed
|
||||||
let changed = false;
|
let changed = false;
|
||||||
|
|
||||||
if (existingCredit.order !== newCreditData.order) changed = true;
|
if (existingCredit.order !== newCreditData.order) changed = true;
|
||||||
if (existingCredit.character !== newCreditData.character) changed = true;
|
if (existingCredit.character !== newCreditData.character)
|
||||||
if (existingCredit.department !== newCreditData.department) changed = true;
|
changed = true;
|
||||||
|
if (existingCredit.department !== newCreditData.department)
|
||||||
|
changed = true;
|
||||||
if (existingCredit.job !== newCreditData.job) changed = true;
|
if (existingCredit.job !== newCreditData.job) changed = true;
|
||||||
if (existingCredit.episode_count !== newCreditData.episode_count) changed = true;
|
if (existingCredit.episode_count !== newCreditData.episode_count)
|
||||||
|
changed = true;
|
||||||
|
|
||||||
if (changed) {
|
if (changed) {
|
||||||
creditsToUpdate.push({
|
creditsToUpdate.push({
|
||||||
id: existingCredit.id,
|
id: existingCredit.id,
|
||||||
...newCreditData
|
...newCreditData,
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
`[CREDIT] UPDATE ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`
|
`[CREDIT] UPDATE ${c.cast_type.toUpperCase()} -> ${person.name} (people_id=${person.id})`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -432,7 +477,9 @@ class EntryManager {
|
|||||||
// -------------------------
|
// -------------------------
|
||||||
if (creditsToInsert.length) {
|
if (creditsToInsert.length) {
|
||||||
await Credit.bulkCreate(creditsToInsert);
|
await Credit.bulkCreate(creditsToInsert);
|
||||||
console.log(`[CREDITS] Inserted ${creditsToInsert.length} new credits for entry ${oldEntry.id}`);
|
console.log(
|
||||||
|
`[CREDITS] Inserted ${creditsToInsert.length} new credits for entry ${oldEntry.id}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------
|
// -------------------------
|
||||||
@@ -440,15 +487,34 @@ class EntryManager {
|
|||||||
// -------------------------
|
// -------------------------
|
||||||
if (creditsToUpdate.length) {
|
if (creditsToUpdate.length) {
|
||||||
await Credit.bulkCreate(creditsToUpdate, {
|
await Credit.bulkCreate(creditsToUpdate, {
|
||||||
updateOnDuplicate: ["order", "character", "episode_count", "department", "job", "profile_path", "adult"]
|
updateOnDuplicate: [
|
||||||
|
"order",
|
||||||
|
"character",
|
||||||
|
"episode_count",
|
||||||
|
"department",
|
||||||
|
"job",
|
||||||
|
"profile_path",
|
||||||
|
"adult",
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(`[CREDITS] Updated ${creditsToUpdate.length} credits for entry ${oldEntry.id}`);
|
console.log(
|
||||||
|
`[CREDITS] Updated ${creditsToUpdate.length} credits for entry ${oldEntry.id}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!creditsToInsert.length && !creditsToUpdate.length) {
|
if (!creditsToInsert.length && !creditsToUpdate.length) {
|
||||||
console.log(`[CREDITS] No changes for entry ${oldEntry.id}`);
|
console.log(`[CREDITS] No changes for entry ${oldEntry.id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Set director from processed credits
|
||||||
|
const directorCredit = allCredits.find(
|
||||||
|
(c) => c.cast_type === "crew" && c.job === "Director",
|
||||||
|
);
|
||||||
|
if (directorCredit) {
|
||||||
|
oldEntry.director = directorCredit.name || null;
|
||||||
|
await oldEntry.save();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// * Media
|
// * Media
|
||||||
@@ -457,12 +523,12 @@ class EntryManager {
|
|||||||
|
|
||||||
// ? 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
|
||||||
@@ -473,25 +539,31 @@ class EntryManager {
|
|||||||
|
|
||||||
let downloadedImages;
|
let downloadedImages;
|
||||||
if (mediaToGet.length != 0) {
|
if (mediaToGet.length != 0) {
|
||||||
downloadedImages = await _mediaManager.getEntryMedia(entryData.id, oldEntry.is_tvseries, mediaToGet);
|
downloadedImages = await _mediaManager.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) {
|
||||||
await _collectionManager.fetchAndSaveCollection(entryData.belongs_to_collection.id);
|
await _collectionManager.fetchAndSaveCollection(
|
||||||
|
entryData.belongs_to_collection.id,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// + end of: refrech logic
|
// + end of: refrech logic
|
||||||
@@ -527,7 +599,10 @@ class EntryManager {
|
|||||||
const lastFetchDate = new Date(entry.last_fetch);
|
const lastFetchDate = new Date(entry.last_fetch);
|
||||||
const currentDate = new Date();
|
const currentDate = new Date();
|
||||||
const diffInHours = (currentDate - lastFetchDate) / (1000 * 60 * 60);
|
const diffInHours = (currentDate - lastFetchDate) / (1000 * 60 * 60);
|
||||||
if (diffInHours > 24 && !(entry.is_tvseries && entry.status === 'Ended')) {
|
if (
|
||||||
|
diffInHours > 24 &&
|
||||||
|
!(entry.is_tvseries && entry.status === "Ended")
|
||||||
|
) {
|
||||||
doRefrech = true;
|
doRefrech = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -543,19 +618,16 @@ class EntryManager {
|
|||||||
/** 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 SyncSeriesData() {
|
async 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'
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -563,7 +635,7 @@ class EntryManager {
|
|||||||
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 => this.SyncSerieData(entry.id))
|
entries.map((entry) => this.SyncSerieData(entry.id)),
|
||||||
);
|
);
|
||||||
logToFile(`Syncing Tv-Series Finished`);
|
logToFile(`Syncing Tv-Series Finished`);
|
||||||
|
|
||||||
@@ -573,31 +645,34 @@ class EntryManager {
|
|||||||
async SyncSerieData(entryId) {
|
async 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(oldEntry.entryId.tmdb_id, oldEntry.is_tvseries);
|
const entryData = await fetchEntryData(
|
||||||
|
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 = {
|
||||||
@@ -608,14 +683,17 @@ class EntryManager {
|
|||||||
|
|
||||||
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);
|
||||||
@@ -628,30 +706,39 @@ class EntryManager {
|
|||||||
|
|
||||||
// ! 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({
|
||||||
@@ -668,7 +755,7 @@ class EntryManager {
|
|||||||
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
|
||||||
@@ -706,7 +793,7 @@ class EntryManager {
|
|||||||
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
|
||||||
@@ -732,7 +819,6 @@ class EntryManager {
|
|||||||
|
|
||||||
return oldEntry;
|
return oldEntry;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new EntryManager();
|
module.exports = new EntryManager();
|
||||||
@@ -26,7 +26,6 @@ const _mediaOptimizerService = mediaOptimizerService;
|
|||||||
const _networkService = networkService;
|
const _networkService = networkService;
|
||||||
|
|
||||||
class EntryService {
|
class EntryService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!EntryService.instance) {
|
if (!EntryService.instance) {
|
||||||
EntryService.instance = this;
|
EntryService.instance = this;
|
||||||
@@ -37,26 +36,23 @@ class EntryService {
|
|||||||
async getAllEntries() {
|
async getAllEntries() {
|
||||||
const entries = await Entry.findAll({
|
const entries = await Entry.findAll({
|
||||||
include: [
|
include: [
|
||||||
{ model: EntryId, as: 'entryId' },
|
{ model: EntryId, as: "entryId" },
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
{ model: EntryRating, as: "entryRating" },
|
||||||
{ model: Media, as: 'medias' },
|
{ model: Media, as: "medias" },
|
||||||
{ model: Season, as: 'seasons' },
|
{ model: Season, as: "seasons" },
|
||||||
{ model: Network, as: 'networks' },
|
{ model: Network, as: "networks" },
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: "genres",
|
||||||
attributes: ['name'], // Only fetch the genre name
|
attributes: ["name"],
|
||||||
through: {
|
through: { attributes: [] },
|
||||||
attributes: [] // Do not fetch any attributes from the join table
|
},
|
||||||
}
|
],
|
||||||
}
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// converting genres from object list to string list
|
const entriesWithGenreNames = entries.map((entry) => ({
|
||||||
const entriesWithGenreNames = entries.map(entry => ({
|
|
||||||
...entry.get({ plain: true }),
|
...entry.get({ plain: true }),
|
||||||
genres: entry.genres.map(genre => genre.name) // Convert genre objects to string array
|
genres: entry.genres.map((genre) => genre.name),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return entriesWithGenreNames;
|
return entriesWithGenreNames;
|
||||||
@@ -78,31 +74,35 @@ class EntryService {
|
|||||||
|
|
||||||
let entry = await Entry.findByPk(id, {
|
let entry = await Entry.findByPk(id, {
|
||||||
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: Network, as: 'networks' },
|
{ model: Network, as: "networks" },
|
||||||
{
|
{
|
||||||
model: Cast, as: 'credits',
|
model: Cast,
|
||||||
where: { cast_type: 'cast' },
|
as: "credits",
|
||||||
order: [['episode_count', 'DESC']],
|
order: [
|
||||||
|
["cast_type", "ASC"],
|
||||||
|
["order", "ASC"],
|
||||||
|
],
|
||||||
limit: 10,
|
limit: 10,
|
||||||
include: [{ model: People, as: 'person' }]
|
include: [{ model: People, as: "person" }],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: Collection, as: 'collections',
|
model: Collection,
|
||||||
include: [{ model: Media, as: 'medias' }]
|
as: "collections",
|
||||||
|
include: [{ model: Media, as: "medias" }],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
model: Genre,
|
model: Genre,
|
||||||
as: 'genres',
|
as: "genres",
|
||||||
attributes: ['name', 'id'],
|
attributes: ["name", "id"],
|
||||||
through: { attributes: [] }
|
through: { attributes: [] },
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
order: [[{ model: EntrySeen, as: 'entrySeen' }, 'date_seen', 'DESC']]
|
order: [[{ model: EntrySeen, as: "entrySeen" }, "date_seen", "DESC"]],
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
@@ -111,7 +111,7 @@ class EntryService {
|
|||||||
|
|
||||||
if (plain) {
|
if (plain) {
|
||||||
const plainEntry = entry.get({ plain: true });
|
const plainEntry = entry.get({ plain: true });
|
||||||
plainEntry.genres = plainEntry.genres.map(g => g.name);
|
plainEntry.genres = plainEntry.genres.map((g) => g.name);
|
||||||
return plainEntry;
|
return plainEntry;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,28 +130,28 @@ class EntryService {
|
|||||||
throw new BadRequestError("Entry id not provided");
|
throw new BadRequestError("Entry id not provided");
|
||||||
}
|
}
|
||||||
|
|
||||||
const entry = await Entry.findByPk(id, { attributes: ['id'] });
|
const entry = await Entry.findByPk(id, { attributes: ["id"] });
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
throw new NotFoundError("Entry with the provided id was not found");
|
throw new NotFoundError("Entry with the provided id was not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const credits = await Credit.findAll({
|
const credits = await Credit.findAll({
|
||||||
where: { entry_id: id },
|
where: { entry_id: id },
|
||||||
include: [{ model: People, as: 'person' }],
|
include: [{ model: People, as: "person" }],
|
||||||
order: [
|
order: [
|
||||||
['cast_type', 'ASC'],
|
["cast_type", "ASC"],
|
||||||
['order', 'ASC'],
|
["order", "ASC"],
|
||||||
['episode_count', 'DESC'],
|
["episode_count", "DESC"],
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
return credits.map(c => c.get({ plain: true }));
|
return credits.map((c) => c.get({ plain: true }));
|
||||||
}
|
}
|
||||||
|
|
||||||
async createEntry(data, plain = true) {
|
async createEntry(data, plain = true) {
|
||||||
// creating the object
|
// creating the object
|
||||||
var is_tvseries = data.release_date == null ? true : false;
|
var is_tvseries = data.release_date == null ? true : false;
|
||||||
console.log('entryService > createEntry > is_tvseries: ', is_tvseries);
|
console.log("entryService > createEntry > is_tvseries: ", is_tvseries);
|
||||||
|
|
||||||
let movie = Entry.build({
|
let movie = Entry.build({
|
||||||
title: data.title || data.name,
|
title: data.title || data.name,
|
||||||
@@ -162,7 +162,10 @@ class EntryService {
|
|||||||
|
|
||||||
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,
|
||||||
@@ -173,12 +176,12 @@ class EntryService {
|
|||||||
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(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let savedEntry = await movie.save();
|
let savedEntry = await movie.save();
|
||||||
|
|
||||||
console.log('entryService > createEntry > savedEntry: ', savedEntry);
|
console.log("entryService > createEntry > savedEntry: ", savedEntry);
|
||||||
|
|
||||||
// ? ids
|
// ? ids
|
||||||
await EntryId.create({
|
await EntryId.create({
|
||||||
@@ -191,15 +194,16 @@ class EntryService {
|
|||||||
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,
|
||||||
})
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? networks
|
// ? networks
|
||||||
if (data.networks) {
|
if (data.networks) {
|
||||||
for (const networkData of data.networks) {
|
for (const networkData of data.networks) {
|
||||||
// Create or update the network
|
// Create or update the network
|
||||||
const [oldNetwork, newNetwork] = await _networkService.createOrUpdateNetwork(networkData);
|
const [oldNetwork, newNetwork] =
|
||||||
|
await _networkService.createOrUpdateNetwork(networkData);
|
||||||
let network = oldNetwork || newNetwork;
|
let network = oldNetwork || newNetwork;
|
||||||
if (!network) {
|
if (!network) {
|
||||||
throw new NotFoundError("Network not found");
|
throw new NotFoundError("Network not found");
|
||||||
@@ -239,7 +243,7 @@ class EntryService {
|
|||||||
|
|
||||||
poster_path: seasonData.poster_path,
|
poster_path: seasonData.poster_path,
|
||||||
banner_path: null,
|
banner_path: null,
|
||||||
})
|
});
|
||||||
|
|
||||||
_mediaManager.getSeasonMedia(savedSeason);
|
_mediaManager.getSeasonMedia(savedSeason);
|
||||||
|
|
||||||
@@ -269,10 +273,10 @@ class EntryService {
|
|||||||
|
|
||||||
// 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
|
||||||
|
|
||||||
@@ -283,21 +287,23 @@ class EntryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const allCredits = [
|
const allCredits = [
|
||||||
...creditData.cast.map(c => ({ ...c, cast_type: 'cast' })),
|
...creditData.cast.map((c) => ({ ...c, cast_type: "cast" })),
|
||||||
...creditData.crew.map(c => ({ ...c, cast_type: 'crew' })),
|
...creditData.crew.map((c) => ({ ...c, cast_type: "crew" })),
|
||||||
];
|
];
|
||||||
|
|
||||||
const tmdbIds = [...new Set(allCredits.map(c => c.id))];
|
const tmdbIds = [...new Set(allCredits.map((c) => c.id))];
|
||||||
|
|
||||||
const existingPeopleList = await People.findAll({
|
const existingPeopleList = await People.findAll({
|
||||||
where: { tmdb_id: tmdbIds },
|
where: { tmdb_id: tmdbIds },
|
||||||
});
|
});
|
||||||
const existingPeopleMap = Object.fromEntries(existingPeopleList.map(p => [p.tmdb_id, p]));
|
const existingPeopleMap = Object.fromEntries(
|
||||||
|
existingPeopleList.map((p) => [p.tmdb_id, p]),
|
||||||
|
);
|
||||||
|
|
||||||
const newPeopleData = tmdbIds
|
const newPeopleData = tmdbIds
|
||||||
.filter(id => !existingPeopleMap[id])
|
.filter((id) => !existingPeopleMap[id])
|
||||||
.map(id => {
|
.map((id) => {
|
||||||
const credit = allCredits.find(c => c.id === id);
|
const credit = allCredits.find((c) => c.id === id);
|
||||||
return {
|
return {
|
||||||
tmdb_id: credit.id,
|
tmdb_id: credit.id,
|
||||||
name: credit.name,
|
name: credit.name,
|
||||||
@@ -306,7 +312,7 @@ class EntryService {
|
|||||||
known_for_department: credit.known_for_department || null,
|
known_for_department: credit.known_for_department || null,
|
||||||
profile_path: credit.profile_path,
|
profile_path: credit.profile_path,
|
||||||
adult: credit.adult || false,
|
adult: credit.adult || false,
|
||||||
last_fetch: new Date()
|
last_fetch: new Date(),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -315,41 +321,55 @@ class EntryService {
|
|||||||
existingPeopleMap[person.tmdb_id] = person;
|
existingPeopleMap[person.tmdb_id] = person;
|
||||||
}
|
}
|
||||||
|
|
||||||
const newCredits = allCredits.map(c => {
|
const newCredits = allCredits.map((c) => {
|
||||||
const person = existingPeopleMap[c.id];
|
const person = existingPeopleMap[c.id];
|
||||||
return {
|
return {
|
||||||
entry_id: savedEntry.id,
|
entry_id: savedEntry.id,
|
||||||
people_id: person.id,
|
people_id: person.id,
|
||||||
tmdb_credit_id: c.credit_id,
|
tmdb_credit_id: c.credit_id,
|
||||||
character: c.cast_type === 'cast' ? c.character : null,
|
character: c.cast_type === "cast" ? c.character : null,
|
||||||
order: c.cast_type === 'cast' ? c.order : null,
|
order: c.cast_type === "cast" ? c.order : null,
|
||||||
profile_path: person.profile_path || null,
|
profile_path: person.profile_path || null,
|
||||||
adult: person.adult || false,
|
adult: person.adult || false,
|
||||||
cast_type: c.cast_type,
|
cast_type: c.cast_type,
|
||||||
department: c.cast_type === 'crew' ? c.department || null : null,
|
department: c.cast_type === "crew" ? c.department || null : null,
|
||||||
job: c.cast_type === 'crew' ? c.job || null : null,
|
job: c.cast_type === "crew" ? c.job || null : null,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
await Credit.bulkCreate(newCredits);
|
await Credit.bulkCreate(newCredits);
|
||||||
|
|
||||||
savedEntry.credit_fetched = true;
|
savedEntry.credit_fetched = true;
|
||||||
|
|
||||||
|
// Extract director name from credits
|
||||||
|
const directorData = allCredits.find(
|
||||||
|
(c) => c.cast_type === "crew" && c.job === "Director",
|
||||||
|
);
|
||||||
|
savedEntry.director = directorData?.name || null;
|
||||||
|
|
||||||
await savedEntry.save();
|
await savedEntry.save();
|
||||||
|
|
||||||
// ? media
|
// ? media
|
||||||
const downloadedImages = await _mediaManager.getEntryMedia(data.id, is_tvseries);
|
const downloadedImages = await _mediaManager.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,
|
||||||
});
|
});
|
||||||
|
|
||||||
_mediaOptimizerService.doGeneratePreview('entries', image.type + 's', image.path);
|
_mediaOptimizerService.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);
|
||||||
@@ -372,7 +392,7 @@ class EntryService {
|
|||||||
const oldEntry = await Entry.findByPk(id);
|
const oldEntry = await Entry.findByPk(id);
|
||||||
|
|
||||||
if (!oldEntry) {
|
if (!oldEntry) {
|
||||||
throw new NotFoundError("Entry with the provided id was not found")
|
throw new NotFoundError("Entry with the provided id was not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
await oldEntry.update(entryData);
|
await oldEntry.update(entryData);
|
||||||
@@ -388,23 +408,26 @@ class EntryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let entry = await Entry.findByPk(id, {
|
let entry = await Entry.findByPk(id, {
|
||||||
include: [
|
include: [{ model: EntryRating, as: "entryRating" }],
|
||||||
{ model: EntryRating, as: 'entryRating' },
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
throw new NotFoundError("Entry with the provided id was not found")
|
throw new NotFoundError("Entry with the provided id was not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (entry.entryRating.id != entryRatingsData.id) {
|
if (entry.entryRating.id != entryRatingsData.id) {
|
||||||
throw new BadRequestError("EntryRatings id does not match");
|
throw new BadRequestError("EntryRatings id does not match");
|
||||||
}
|
}
|
||||||
|
|
||||||
entry.entryRating.user_rating = entryRatingsData.user_rating ?? entry.entryRating.user_rating;
|
entry.entryRating.user_rating =
|
||||||
entry.entryRating.tmdb_rating = entryRatingsData.tmdb_rating ?? entry.entryRating.tmdb_rating;
|
entryRatingsData.user_rating ?? entry.entryRating.user_rating;
|
||||||
entry.entryRating.imdb_rating = entryRatingsData.imdb_rating ?? entry.entryRating.imdb_rating;
|
entry.entryRating.tmdb_rating =
|
||||||
entry.entryRating.rotten_tomatoes_rating = entryRatingsData.rotten_tomatoes_rating ?? entry.entryRating.rotten_tomatoes_rating;
|
entryRatingsData.tmdb_rating ?? entry.entryRating.tmdb_rating;
|
||||||
|
entry.entryRating.imdb_rating =
|
||||||
|
entryRatingsData.imdb_rating ?? entry.entryRating.imdb_rating;
|
||||||
|
entry.entryRating.rotten_tomatoes_rating =
|
||||||
|
entryRatingsData.rotten_tomatoes_rating ??
|
||||||
|
entry.entryRating.rotten_tomatoes_rating;
|
||||||
|
|
||||||
return await entry.entryRating.save();
|
return await entry.entryRating.save();
|
||||||
}
|
}
|
||||||
@@ -415,13 +438,11 @@ class EntryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let entry = await Entry.findByPk(id, {
|
let entry = await Entry.findByPk(id, {
|
||||||
include: [
|
include: [{ model: EntryId, as: "entryId" }],
|
||||||
{ model: EntryId, as: 'entryId' },
|
|
||||||
]
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
throw new NotFoundError("Entry with the provided id was not found")
|
throw new NotFoundError("Entry with the provided id was not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (entry.entryRating.id != entryRatingsData.id) {
|
if (entry.entryRating.id != entryRatingsData.id) {
|
||||||
@@ -441,11 +462,11 @@ class EntryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const deletedCount = await Entry.destroy({
|
const deletedCount = await Entry.destroy({
|
||||||
where: { id: id }
|
where: { id: id },
|
||||||
});
|
});
|
||||||
|
|
||||||
if (deletedCount == 0) {
|
if (deletedCount == 0) {
|
||||||
throw new NotFoundError("Entry with the provided id was not found")
|
throw new NotFoundError("Entry with the provided id was not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
return deletedCount;
|
return deletedCount;
|
||||||
@@ -458,30 +479,29 @@ class EntryService {
|
|||||||
|
|
||||||
const entry = await Entry.findByPk(id);
|
const entry = await Entry.findByPk(id);
|
||||||
if (!entry) {
|
if (!entry) {
|
||||||
throw new NotFoundError("Entry with the provided id was not found")
|
throw new NotFoundError("Entry with the provided id was not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
const seasons = await Season.findAll({
|
const seasons = await Season.findAll({
|
||||||
where: {
|
where: {
|
||||||
entry_id: id
|
entry_id: id,
|
||||||
},
|
},
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: Episode, as: 'episodes', include: [
|
model: Episode,
|
||||||
{ model: Media, as: 'medias' }
|
as: "episodes",
|
||||||
]
|
include: [{ model: Media, as: "medias" }],
|
||||||
},
|
},
|
||||||
{ model: Media, as: 'medias' }
|
{ model: Media, as: "medias" },
|
||||||
],
|
],
|
||||||
order: [
|
order: [
|
||||||
['season_number', 'ASC'],
|
["season_number", "ASC"],
|
||||||
[{ model: Episode, as: 'episodes' }, 'episode_number', 'ASC'],
|
[{ model: Episode, as: "episodes" }, "episode_number", "ASC"],
|
||||||
]
|
],
|
||||||
})
|
});
|
||||||
|
|
||||||
return seasons;
|
return seasons;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new EntryService();
|
module.exports = new EntryService();
|
||||||
@@ -1,18 +1,18 @@
|
|||||||
const path = require('path');
|
const path = require("path");
|
||||||
const fsPromises = require('fs').promises;
|
const fsPromises = require("fs").promises;
|
||||||
const fs = require('fs');
|
const fs = require("fs");
|
||||||
|
|
||||||
const Media = require("../models/Media");
|
const Media = require("../models/Media");
|
||||||
const People = require("../models/People");
|
const People = require("../models/People");
|
||||||
const Credit = require("../models/Credit");
|
const Credit = require("../models/Credit");
|
||||||
|
const Entry = require("../models/Entry");
|
||||||
|
|
||||||
const { logToFile } = require('./logService');
|
const { logToFile } = require("./logService");
|
||||||
const configService = require('./configService');
|
const configService = require("./configService");
|
||||||
|
|
||||||
const _configService = configService;
|
const _configService = configService;
|
||||||
|
|
||||||
class MaintenanceService {
|
class MaintenanceService {
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
if (!MaintenanceService.instance) {
|
if (!MaintenanceService.instance) {
|
||||||
MaintenanceService.instance = this;
|
MaintenanceService.instance = this;
|
||||||
@@ -32,15 +32,25 @@ class MaintenanceService {
|
|||||||
const dataPath = await _configService.getMediaFolder();
|
const dataPath = await _configService.getMediaFolder();
|
||||||
|
|
||||||
const mediaTypeFolder = {
|
const mediaTypeFolder = {
|
||||||
'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
"entry;poster": path.join(dataPath, "images", "entries", "posters"),
|
||||||
'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
"entry;logo": path.join(dataPath, "images", "entries", "logos"),
|
||||||
'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
|
"entry;backdrop": path.join(dataPath, "images", "entries", "backdrops"),
|
||||||
|
|
||||||
'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'),
|
"collection;poster": path.join(
|
||||||
'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops'),
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"posters",
|
||||||
|
),
|
||||||
|
"collection;backdrop": path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"backdrops",
|
||||||
|
),
|
||||||
|
|
||||||
'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'),
|
"season;poster": path.join(dataPath, "images", "seasons", "posters"),
|
||||||
'episode;still': path.join(dataPath, 'images', 'episodes', 'stills')
|
"episode;still": path.join(dataPath, "images", "episodes", "stills"),
|
||||||
};
|
};
|
||||||
|
|
||||||
let missingFiles = [];
|
let missingFiles = [];
|
||||||
@@ -49,26 +59,32 @@ class MaintenanceService {
|
|||||||
|
|
||||||
if (!mediaTypeFolder[folderType]) continue;
|
if (!mediaTypeFolder[folderType]) continue;
|
||||||
|
|
||||||
const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path)
|
const filePath = path.join(mediaTypeFolder[folderType], allMedia[i].path);
|
||||||
if (!fs.existsSync(filePath)) {
|
if (!fs.existsSync(filePath)) {
|
||||||
missingFiles.push(allMedia[i]);
|
missingFiles.push(allMedia[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let removed = {
|
let removed = {
|
||||||
'posters': 0,
|
posters: 0,
|
||||||
'logos': 0,
|
logos: 0,
|
||||||
'backdrops': 0,
|
backdrops: 0,
|
||||||
'stills': 0,
|
stills: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
for (let i = 0; i < missingFiles.length; i++) {
|
for (let i = 0; i < missingFiles.length; i++) {
|
||||||
removed[missingFiles[i].type + 's'] += 1;
|
removed[missingFiles[i].type + "s"] += 1;
|
||||||
if (!dry) missingFiles[i].destroy();
|
if (!dry) missingFiles[i].destroy();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dry) logToFile(`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
if (dry)
|
||||||
else logToFile(`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
logToFile(
|
||||||
|
`Run a dry missing files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`,
|
||||||
|
);
|
||||||
|
else
|
||||||
|
logToFile(
|
||||||
|
`Run an missing files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`,
|
||||||
|
);
|
||||||
|
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
@@ -83,30 +99,40 @@ class MaintenanceService {
|
|||||||
const dataPath = _configService.getMediaFolder();
|
const dataPath = _configService.getMediaFolder();
|
||||||
|
|
||||||
// ? Getting the name (without extention) of all media in database
|
// ? Getting the name (without extention) of all media in database
|
||||||
const allMedia = (await Media.findAll()).map(m => {
|
const allMedia = (await Media.findAll()).map((m) => {
|
||||||
return m.path.split('.')[0]
|
return m.path.split(".")[0];
|
||||||
});
|
});
|
||||||
|
|
||||||
// ? Loop trough the files of the images folder and check
|
// ? Loop trough the files of the images folder and check
|
||||||
// ? if a file doesnt exist in the allMedia array and mark it to delete
|
// ? if a file doesnt exist in the allMedia array and mark it to delete
|
||||||
const mediaTypeFolder = {
|
const mediaTypeFolder = {
|
||||||
'entry;poster': path.join(dataPath, 'images', 'entries', 'posters'),
|
"entry;poster": path.join(dataPath, "images", "entries", "posters"),
|
||||||
'entry;logo': path.join(dataPath, 'images', 'entries', 'logos'),
|
"entry;logo": path.join(dataPath, "images", "entries", "logos"),
|
||||||
'entry;backdrop': path.join(dataPath, 'images', 'entries', 'backdrops'),
|
"entry;backdrop": path.join(dataPath, "images", "entries", "backdrops"),
|
||||||
|
|
||||||
'collection;poster': path.join(dataPath, 'images', 'collections', 'posters'),
|
"collection;poster": path.join(
|
||||||
'collection;backdrop': path.join(dataPath, 'images', 'collections', 'backdrops'),
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"posters",
|
||||||
|
),
|
||||||
|
"collection;backdrop": path.join(
|
||||||
|
dataPath,
|
||||||
|
"images",
|
||||||
|
"collections",
|
||||||
|
"backdrops",
|
||||||
|
),
|
||||||
|
|
||||||
'season;poster': path.join(dataPath, 'images', 'seasons', 'posters'),
|
"season;poster": path.join(dataPath, "images", "seasons", "posters"),
|
||||||
'episode;still': path.join(dataPath, 'images', 'episodes', 'stills')
|
"episode;still": path.join(dataPath, "images", "episodes", "stills"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// * counter
|
// * counter
|
||||||
let removed = {
|
let removed = {
|
||||||
'posters': 0,
|
posters: 0,
|
||||||
'logos': 0,
|
logos: 0,
|
||||||
'backdrops': 0,
|
backdrops: 0,
|
||||||
'stills': 0,
|
stills: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Iterate over each media type directory and check for orphan files
|
// Iterate over each media type directory and check for orphan files
|
||||||
@@ -119,14 +145,13 @@ class MaintenanceService {
|
|||||||
|
|
||||||
// Check each file in the directory
|
// Check each file in the directory
|
||||||
for (let file of files) {
|
for (let file of files) {
|
||||||
|
|
||||||
// preparing the file name
|
// preparing the file name
|
||||||
const fileName = file.split('.')[0].replace("_preview", "");
|
const fileName = file.split(".")[0].replace("_preview", "");
|
||||||
const isInDatabase = allMedia.includes(fileName);
|
const isInDatabase = allMedia.includes(fileName);
|
||||||
|
|
||||||
// if the file isn't in database even on other extentions then delete it
|
// if the file isn't in database even on other extentions then delete it
|
||||||
if (!isInDatabase) {
|
if (!isInDatabase) {
|
||||||
removed[folderType.split(';')[1] + 's']++; // Increment the count of removed files
|
removed[folderType.split(";")[1] + "s"]++; // Increment the count of removed files
|
||||||
if (!dry) {
|
if (!dry) {
|
||||||
const filePath = path.join(directory, file);
|
const filePath = path.join(directory, file);
|
||||||
await fsPromises.unlink(filePath);
|
await fsPromises.unlink(filePath);
|
||||||
@@ -138,8 +163,14 @@ class MaintenanceService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (dry) logToFile(`Run a dry orphan files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
if (dry)
|
||||||
else logToFile(`Run an orphan files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`)
|
logToFile(
|
||||||
|
`Run a dry orphan files check, found: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`,
|
||||||
|
);
|
||||||
|
else
|
||||||
|
logToFile(
|
||||||
|
`Run an orphan files cleanup, deleted: {posters: ${removed.posters}, backdrops: ${removed.backdrops}, logos: ${removed.logos}}`,
|
||||||
|
);
|
||||||
|
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
@@ -151,18 +182,22 @@ class MaintenanceService {
|
|||||||
* @param {boolean} [dry=false] - if true only return the count
|
* @param {boolean} [dry=false] - if true only return the count
|
||||||
*/
|
*/
|
||||||
async deleteOrphanPeople(dry = false) {
|
async deleteOrphanPeople(dry = false) {
|
||||||
const { Sequelize } = require('sequelize');
|
const { Sequelize } = require("sequelize");
|
||||||
|
|
||||||
// Find all people who have no credits and are not pinned
|
// Find all people who have no credits and are not pinned
|
||||||
const allPeople = await People.findAll({
|
const allPeople = await People.findAll({
|
||||||
include: [{
|
include: [
|
||||||
|
{
|
||||||
model: Credit,
|
model: Credit,
|
||||||
as: 'roles',
|
as: "roles",
|
||||||
required: false,
|
required: false,
|
||||||
}],
|
},
|
||||||
|
],
|
||||||
});
|
});
|
||||||
|
|
||||||
const orphans = allPeople.filter(p => (!p.roles || p.roles.length === 0) && !p.pinned);
|
const orphans = allPeople.filter(
|
||||||
|
(p) => (!p.roles || p.roles.length === 0) && !p.pinned,
|
||||||
|
);
|
||||||
|
|
||||||
if (!dry) {
|
if (!dry) {
|
||||||
for (const person of orphans) {
|
for (const person of orphans) {
|
||||||
@@ -177,6 +212,43 @@ class MaintenanceService {
|
|||||||
return { count };
|
return { count };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count entries missing a director, and optionally fix them.
|
||||||
|
* @param {boolean} [dry=false] - if true only count, if false also fix
|
||||||
|
*/
|
||||||
|
async fixMissingDirectors(dry = false) {
|
||||||
|
const entries = await Entry.findAll({
|
||||||
|
where: { director: null },
|
||||||
|
include: [
|
||||||
|
{
|
||||||
|
model: Credit,
|
||||||
|
as: "credits",
|
||||||
|
where: { cast_type: "crew", job: "Director" },
|
||||||
|
include: [{ model: People, as: "person", attributes: ["name"] }],
|
||||||
|
required: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const count = entries.length;
|
||||||
|
let fixed = 0;
|
||||||
|
|
||||||
|
if (!dry) {
|
||||||
|
for (const entry of entries) {
|
||||||
|
const dirName = entry.credits?.[0]?.person?.name || null;
|
||||||
|
if (dirName) {
|
||||||
|
entry.director = dirName;
|
||||||
|
await entry.save();
|
||||||
|
fixed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dry) logToFile(`Dry missing directors check: ${count}`);
|
||||||
|
else logToFile(`Fixed missing directors: ${fixed} of ${count}`);
|
||||||
|
|
||||||
|
return { count, fixed };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = new MaintenanceService();
|
module.exports = new MaintenanceService();
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { api } from '@/lib/api';
|
import { api } from "@/lib/api";
|
||||||
|
|
||||||
export interface OrphanResult {
|
export interface OrphanResult {
|
||||||
posters: number;
|
posters: number;
|
||||||
@@ -13,20 +13,38 @@ export interface OrphanPeopleResult {
|
|||||||
|
|
||||||
export const maintenanceApi = {
|
export const maintenanceApi = {
|
||||||
scanOrphanFiles: () =>
|
scanOrphanFiles: () =>
|
||||||
api.get<OrphanResult>('/maintenance/orphan-files').then((r) => r.data),
|
api.get<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
|
||||||
|
|
||||||
deleteOrphanFiles: () =>
|
deleteOrphanFiles: () =>
|
||||||
api.delete<OrphanResult>('/maintenance/orphan-files').then((r) => r.data),
|
api.delete<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
|
||||||
|
|
||||||
scanOrphanMediaRecords: () =>
|
scanOrphanMediaRecords: () =>
|
||||||
api.get<OrphanResult>('/maintenance/orphan-media-records').then((r) => r.data),
|
api
|
||||||
|
.get<OrphanResult>("/maintenance/orphan-media-records")
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
deleteOrphanMediaRecords: () =>
|
deleteOrphanMediaRecords: () =>
|
||||||
api.delete<OrphanResult>('/maintenance/orphan-media-records').then((r) => r.data),
|
api
|
||||||
|
.delete<OrphanResult>("/maintenance/orphan-media-records")
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
scanOrphanPeople: () =>
|
scanOrphanPeople: () =>
|
||||||
api.get<OrphanPeopleResult>('/maintenance/orphan-people').then((r) => r.data),
|
api
|
||||||
|
.get<OrphanPeopleResult>("/maintenance/orphan-people")
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
deleteOrphanPeople: () =>
|
deleteOrphanPeople: () =>
|
||||||
api.delete<OrphanPeopleResult>('/maintenance/orphan-people').then((r) => r.data),
|
api
|
||||||
|
.delete<OrphanPeopleResult>("/maintenance/orphan-people")
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
|
scanMissingDirectors: () =>
|
||||||
|
api
|
||||||
|
.get<{ count: number; fixed: number }>("/maintenance/missing-directors")
|
||||||
|
.then((r) => r.data),
|
||||||
|
|
||||||
|
fixMissingDirectors: () =>
|
||||||
|
api
|
||||||
|
.post<{ count: number; fixed: number }>("/maintenance/missing-directors")
|
||||||
|
.then((r) => r.data),
|
||||||
};
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
|
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
function TooltipProvider({
|
function TooltipProvider({
|
||||||
delay = 0,
|
delay = 0,
|
||||||
@@ -12,15 +12,15 @@ function TooltipProvider({
|
|||||||
delay={delay}
|
delay={delay}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
|
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
|
||||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
|
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
|
||||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function TooltipContent({
|
function TooltipContent({
|
||||||
@@ -48,17 +48,17 @@ function TooltipContent({
|
|||||||
<TooltipPrimitive.Popup
|
<TooltipPrimitive.Popup
|
||||||
data-slot="tooltip-content"
|
data-slot="tooltip-content"
|
||||||
className={cn(
|
className={cn(
|
||||||
"z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
"z-50 block w-fit max-w-xs origin-(--transform-origin) rounded-md bg-popover px-3 py-1.5 text-xs text-popover-foreground shadow-md ring-1 ring-border has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||||
className
|
className,
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
|
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-popover fill-popover ring-1 ring-border data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
|
||||||
</TooltipPrimitive.Popup>
|
</TooltipPrimitive.Popup>
|
||||||
</TooltipPrimitive.Positioner>
|
</TooltipPrimitive.Positioner>
|
||||||
</TooltipPrimitive.Portal>
|
</TooltipPrimitive.Portal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||||
@@ -1,15 +1,16 @@
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { toast } from 'sonner';
|
import { toast } from "sonner";
|
||||||
import { entriesApi } from '@/api/entries';
|
import { entriesApi } from "@/api/entries";
|
||||||
import { useLibraryStore } from '@/stores/useLibraryStore';
|
import { useLibraryStore } from "@/stores/useLibraryStore";
|
||||||
import type { Entry } from '@/types';
|
import type { Entry } from "@/types";
|
||||||
|
|
||||||
export const entryKeys = {
|
export const entryKeys = {
|
||||||
all: ['entries'] as const,
|
all: ["entries"] as const,
|
||||||
detail: (id: number) => ['entries', id] as const,
|
detail: (id: number) => ["entries", id] as const,
|
||||||
seasons: (id: number) => ['entries', id, 'seasons'] as const,
|
seasons: (id: number) => ["entries", id, "seasons"] as const,
|
||||||
credits: (id: number) => ['entries', id, 'credits'] as const,
|
credits: (id: number) => ["entries", id, "credits"] as const,
|
||||||
tmdbPreview: (tmdbId: number, type: string) => ['entries', 'tmdb-preview', type, tmdbId] as const,
|
tmdbPreview: (tmdbId: number, type: string) =>
|
||||||
|
["entries", "tmdb-preview", type, tmdbId] as const,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function useLibrary() {
|
export function useLibrary() {
|
||||||
@@ -69,7 +70,7 @@ export function useCreateEntry() {
|
|||||||
toast.success(`"${entry.title}" added to library`);
|
toast.success(`"${entry.title}" added to library`);
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error('Failed to add entry to library');
|
toast.error("Failed to add entry to library");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -85,10 +86,10 @@ export function useUpdateEntry() {
|
|||||||
updateEntry(entry.id, entry);
|
updateEntry(entry.id, entry);
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entry.id) });
|
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entry.id) });
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.all });
|
queryClient.invalidateQueries({ queryKey: entryKeys.all });
|
||||||
toast.success('Entry updated');
|
toast.success("Entry updated");
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error('Failed to update entry');
|
toast.error("Failed to update entry");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -102,10 +103,10 @@ export function useDeleteEntry() {
|
|||||||
onSuccess: (_data, id) => {
|
onSuccess: (_data, id) => {
|
||||||
removeEntry(id);
|
removeEntry(id);
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.all });
|
queryClient.invalidateQueries({ queryKey: entryKeys.all });
|
||||||
toast.success('Entry removed from library');
|
toast.success("Entry removed from library");
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error('Failed to remove entry');
|
toast.error("Failed to remove entry");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -119,10 +120,10 @@ export function useRefreshEntry() {
|
|||||||
onSuccess: (entry) => {
|
onSuccess: (entry) => {
|
||||||
updateEntry(entry.id, entry);
|
updateEntry(entry.id, entry);
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entry.id) });
|
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entry.id) });
|
||||||
toast.success('Entry details refreshed');
|
toast.success("Entry details refreshed");
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error('Failed to refresh entry');
|
toast.error("Failed to refresh entry");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -141,10 +142,10 @@ export function useUpdateEntryRatings() {
|
|||||||
onSuccess: (_data, { id }) => {
|
onSuccess: (_data, { id }) => {
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.detail(id) });
|
queryClient.invalidateQueries({ queryKey: entryKeys.detail(id) });
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.all });
|
queryClient.invalidateQueries({ queryKey: entryKeys.all });
|
||||||
toast.success('Rating updated');
|
toast.success("Rating updated");
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error('Failed to update rating');
|
toast.error("Failed to update rating");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -157,15 +158,15 @@ export function useUploadMedia() {
|
|||||||
entriesApi.uploadMedia(id, formData),
|
entriesApi.uploadMedia(id, formData),
|
||||||
onSuccess: (_data, { id }) => {
|
onSuccess: (_data, { id }) => {
|
||||||
queryClient.invalidateQueries({ queryKey: entryKeys.detail(id) });
|
queryClient.invalidateQueries({ queryKey: entryKeys.detail(id) });
|
||||||
toast.success('Media uploaded successfully');
|
toast.success("Media uploaded successfully");
|
||||||
},
|
},
|
||||||
onError: () => {
|
onError: () => {
|
||||||
toast.error('Failed to upload media');
|
toast.error("Failed to upload media");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useTmdbPreview(tmdbId: number, type: 'movie' | 'tv') {
|
export function useTmdbPreview(tmdbId: number, type: "movie" | "tv") {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: entryKeys.tmdbPreview(tmdbId, type),
|
queryKey: entryKeys.tmdbPreview(tmdbId, type),
|
||||||
queryFn: () => entriesApi.previewTmdb(tmdbId, type),
|
queryFn: () => entriesApi.previewTmdb(tmdbId, type),
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
* - Genres come as string arrays from the backend mapper
|
* - Genres come as string arrays from the backend mapper
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { Entry, Collection, Media, Credit, Genre } from '@/types';
|
import type { Entry, Collection, Media, Credit, Genre } from "@/types";
|
||||||
|
|
||||||
/* ---------- Media ---------- */
|
/* ---------- Media ---------- */
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
@@ -51,7 +51,7 @@ export function normalizeCredit(raw: any): Credit {
|
|||||||
export function normalizeGenres(raw: any[]): Genre[] {
|
export function normalizeGenres(raw: any[]): Genre[] {
|
||||||
if (!Array.isArray(raw)) return [];
|
if (!Array.isArray(raw)) return [];
|
||||||
return raw.map((g, i) => {
|
return raw.map((g, i) => {
|
||||||
if (typeof g === 'string') return { id: i, name: g };
|
if (typeof g === "string") return { id: i, name: g };
|
||||||
return g as Genre;
|
return g as Genre;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,26 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from "react";
|
||||||
import { useParams, Link, useNavigate } from 'react-router-dom';
|
import { useParams, Link, useNavigate } from "react-router-dom";
|
||||||
import { useEntry, useEntrySeasons, useRefreshEntry } from '@/hooks/useEntries';
|
import {
|
||||||
import { useEntrySeenByEntry, useDeleteEntrySeen } from '@/hooks/useEntrySeen';
|
useEntry,
|
||||||
import { useCollections } from '@/hooks/useCollections';
|
useEntrySeasons,
|
||||||
import { useLibraryStore } from '@/stores/useLibraryStore';
|
useRefreshEntry,
|
||||||
import { useCommandPaletteStore } from '@/stores/useCommandPaletteStore';
|
useEntryCredits,
|
||||||
import { Badge } from '@/components/ui/badge';
|
} from "@/hooks/useEntries";
|
||||||
import { Button } from '@/components/ui/button';
|
import { useEntrySeenByEntry, useDeleteEntrySeen } from "@/hooks/useEntrySeen";
|
||||||
import { Separator } from '@/components/ui/separator';
|
import { useCollections } from "@/hooks/useCollections";
|
||||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
import { useLibraryStore } from "@/stores/useLibraryStore";
|
||||||
|
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Separator } from "@/components/ui/separator";
|
||||||
|
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from "@/components/ui/dropdown-menu";
|
||||||
import {
|
import {
|
||||||
Heart,
|
Heart,
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
@@ -29,25 +34,25 @@ import {
|
|||||||
History,
|
History,
|
||||||
Trash2,
|
Trash2,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
} from 'lucide-react';
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
TooltipContent,
|
TooltipContent,
|
||||||
TooltipProvider,
|
TooltipProvider,
|
||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from '@/components/ui/tooltip';
|
} from "@/components/ui/tooltip";
|
||||||
import { CastList } from '@/components/entries/CastList';
|
import { CastList } from "@/components/entries/CastList";
|
||||||
import { SeasonsContainer } from '@/components/entries/SeasonsContainer';
|
import { SeasonsContainer } from "@/components/entries/SeasonsContainer";
|
||||||
import { StreamingSection } from '@/components/streaming/StreamingSection';
|
import { StreamingSection } from "@/components/streaming/StreamingSection";
|
||||||
// EpisodeWatchHistory is available for future use
|
// EpisodeWatchHistory is available for future use
|
||||||
import { EntrySettingsDialog } from '@/components/dialogs/EntrySettingsDialog';
|
import { EntrySettingsDialog } from "@/components/dialogs/EntrySettingsDialog";
|
||||||
import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog';
|
import { EntrySeenDialog } from "@/components/dialogs/EntrySeenDialog";
|
||||||
import { EntryMediaDialog } from '@/components/dialogs/EntryMediaDialog';
|
import { EntryMediaDialog } from "@/components/dialogs/EntryMediaDialog";
|
||||||
import { AddEntryToCollectionDialog } from '@/components/dialogs/AddEntryToCollectionDialog';
|
import { AddEntryToCollectionDialog } from "@/components/dialogs/AddEntryToCollectionDialog";
|
||||||
import { RatingDialog } from '@/components/dialogs/RatingDialog';
|
import { RatingDialog } from "@/components/dialogs/RatingDialog";
|
||||||
import { MovieWatchHistoryDialog } from '@/components/dialogs/MovieWatchHistoryDialog';
|
import { MovieWatchHistoryDialog } from "@/components/dialogs/MovieWatchHistoryDialog";
|
||||||
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog';
|
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
|
||||||
import { EntryDetailsSkeleton } from '@/components/skeletons/PageSkeletons';
|
import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
|
||||||
import {
|
import {
|
||||||
getPosterUrl,
|
getPosterUrl,
|
||||||
getBackdropUrl,
|
getBackdropUrl,
|
||||||
@@ -55,9 +60,9 @@ import {
|
|||||||
getYear,
|
getYear,
|
||||||
formatRuntime,
|
formatRuntime,
|
||||||
formatDate,
|
formatDate,
|
||||||
} from '@/lib/media-utils';
|
} from "@/lib/media-utils";
|
||||||
import { useUpdateEntry, useDeleteEntry } from '@/hooks/useEntries';
|
import { useUpdateEntry, useDeleteEntry } from "@/hooks/useEntries";
|
||||||
import type { Collection, Entry } from '@/types';
|
import type { Collection, Entry } from "@/types";
|
||||||
|
|
||||||
export function EntryDetailsPage() {
|
export function EntryDetailsPage() {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
@@ -65,6 +70,7 @@ export function EntryDetailsPage() {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { data: entry, isLoading } = useEntry(entryId);
|
const { data: entry, isLoading } = useEntry(entryId);
|
||||||
const { data: seasons } = useEntrySeasons(entryId);
|
const { data: seasons } = useEntrySeasons(entryId);
|
||||||
|
const { data: allCredits = [] } = useEntryCredits(entryId);
|
||||||
const { data: watchHistory = [] } = useEntrySeenByEntry(entryId);
|
const { data: watchHistory = [] } = useEntrySeenByEntry(entryId);
|
||||||
const updateEntry = useUpdateEntry();
|
const updateEntry = useUpdateEntry();
|
||||||
const refreshEntry = useRefreshEntry();
|
const refreshEntry = useRefreshEntry();
|
||||||
@@ -73,7 +79,8 @@ export function EntryDetailsPage() {
|
|||||||
|
|
||||||
// Merge library entry with detail entry so we get both library flags AND full details (credits, etc.)
|
// Merge library entry with detail entry so we get both library flags AND full details (credits, etc.)
|
||||||
const libraryEntry = useLibraryStore((s) => s.entries.get(entryId));
|
const libraryEntry = useLibraryStore((s) => s.entries.get(entryId));
|
||||||
const displayEntry = libraryEntry && entry
|
const displayEntry =
|
||||||
|
libraryEntry && entry
|
||||||
? { ...libraryEntry, ...entry, isInLibrary: true }
|
? { ...libraryEntry, ...entry, isInLibrary: true }
|
||||||
: entry || libraryEntry;
|
: entry || libraryEntry;
|
||||||
|
|
||||||
@@ -92,7 +99,7 @@ export function EntryDetailsPage() {
|
|||||||
addRecentlyViewed({
|
addRecentlyViewed({
|
||||||
id: `lib-${entryId}`,
|
id: `lib-${entryId}`,
|
||||||
title: displayEntry.title,
|
title: displayEntry.title,
|
||||||
type: displayEntry.is_tvseries ? 'tv' : 'movie',
|
type: displayEntry.is_tvseries ? "tv" : "movie",
|
||||||
poster_path: displayEntry.poster_path,
|
poster_path: displayEntry.poster_path,
|
||||||
libraryId: entryId,
|
libraryId: entryId,
|
||||||
tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined,
|
tmdbId: displayEntry.entryIds?.tmdb_id ?? undefined,
|
||||||
@@ -105,10 +112,13 @@ export function EntryDetailsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const e = displayEntry;
|
const e = displayEntry;
|
||||||
|
// Use useEntryCredits (allCredits) which includes both cast AND crew (director).
|
||||||
|
// e.credits from useEntry is a limited preview (10 items).
|
||||||
|
const credits = allCredits.length > 0 ? allCredits : e.credits || [];
|
||||||
const backdrop = getBackdropUrl(e);
|
const backdrop = getBackdropUrl(e);
|
||||||
const poster = getPosterUrl(e);
|
const poster = getPosterUrl(e);
|
||||||
const director = e.credits?.find(
|
const director = credits.find(
|
||||||
(c) => c.cast_type === 'crew' && c.job === 'Director'
|
(c) => c.cast_type === "crew" && c.job === "Director",
|
||||||
);
|
);
|
||||||
|
|
||||||
const toggleFavorite = () => {
|
const toggleFavorite = () => {
|
||||||
@@ -152,16 +162,23 @@ export function EntryDetailsPage() {
|
|||||||
Rate this
|
Rate this
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
{!e.is_tvseries && (
|
{!e.is_tvseries && (
|
||||||
<DropdownMenuItem onClick={() => setShowWatchHistoryDialog(true)}>
|
<DropdownMenuItem
|
||||||
|
onClick={() => setShowWatchHistoryDialog(true)}
|
||||||
|
>
|
||||||
<History className="mr-2 h-4 w-4" />
|
<History className="mr-2 h-4 w-4" />
|
||||||
Watch History
|
Watch History
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
)}
|
)}
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
{/* Organize */}
|
{/* Organize */}
|
||||||
<DropdownMenuItem onClick={toggleFavorite} disabled={updateEntry.isPending}>
|
<DropdownMenuItem
|
||||||
<Heart className={`mr-2 h-4 w-4 ${e.favorit ? 'fill-current' : ''}`} />
|
onClick={toggleFavorite}
|
||||||
{e.favorit ? 'Unfavorite' : 'Favorite'}
|
disabled={updateEntry.isPending}
|
||||||
|
>
|
||||||
|
<Heart
|
||||||
|
className={`mr-2 h-4 w-4 ${e.favorit ? "fill-current" : ""}`}
|
||||||
|
/>
|
||||||
|
{e.favorit ? "Unfavorite" : "Favorite"}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setShowCollectionDialog(true)}>
|
<DropdownMenuItem onClick={() => setShowCollectionDialog(true)}>
|
||||||
<FolderPlus className="mr-2 h-4 w-4" />
|
<FolderPlus className="mr-2 h-4 w-4" />
|
||||||
@@ -173,13 +190,18 @@ export function EntryDetailsPage() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<EyeOff className="mr-2 h-4 w-4" />
|
<EyeOff className="mr-2 h-4 w-4" />
|
||||||
{e.hidden ? 'Unhide' : 'Hide'}
|
{e.hidden ? "Unhide" : "Hide"}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
{/* Manage */}
|
{/* Manage */}
|
||||||
<DropdownMenuItem onClick={() => refreshEntry.mutate(e.id)} disabled={refreshEntry.isPending}>
|
<DropdownMenuItem
|
||||||
<RefreshCw className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? 'animate-spin' : ''}`} />
|
onClick={() => refreshEntry.mutate(e.id)}
|
||||||
{refreshEntry.isPending ? 'Refreshing...' : 'Refresh details'}
|
disabled={refreshEntry.isPending}
|
||||||
|
>
|
||||||
|
<RefreshCw
|
||||||
|
className={`mr-2 h-4 w-4 ${refreshEntry.isPending ? "animate-spin" : ""}`}
|
||||||
|
/>
|
||||||
|
{refreshEntry.isPending ? "Refreshing..." : "Refresh details"}
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
<DropdownMenuItem onClick={() => setShowMediaDialog(true)}>
|
<DropdownMenuItem onClick={() => setShowMediaDialog(true)}>
|
||||||
<ImageIcon className="mr-2 h-4 w-4" />
|
<ImageIcon className="mr-2 h-4 w-4" />
|
||||||
@@ -218,7 +240,7 @@ export function EntryDetailsPage() {
|
|||||||
<div className="flex items-center justify-center gap-3 mt-3">
|
<div className="flex items-center justify-center gap-3 mt-3">
|
||||||
{e.entryIds.tmdb_id && (
|
{e.entryIds.tmdb_id && (
|
||||||
<a
|
<a
|
||||||
href={`https://www.themoviedb.org/${e.is_tvseries ? 'tv' : 'movie'}/${e.entryIds.tmdb_id}`}
|
href={`https://www.themoviedb.org/${e.is_tvseries ? "tv" : "movie"}/${e.entryIds.tmdb_id}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||||
@@ -249,7 +271,7 @@ export function EntryDetailsPage() {
|
|||||||
<h1 className="text-3xl font-bold leading-tight">{e.title}</h1>
|
<h1 className="text-3xl font-bold leading-tight">{e.title}</h1>
|
||||||
{director?.people?.name && (
|
{director?.people?.name && (
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
by{' '}
|
by{" "}
|
||||||
<Link
|
<Link
|
||||||
to={`/people/${director.people_id}`}
|
to={`/people/${director.people_id}`}
|
||||||
className="font-medium text-foreground hover:underline"
|
className="font-medium text-foreground hover:underline"
|
||||||
@@ -331,8 +353,14 @@ export function EntryDetailsPage() {
|
|||||||
{e.genres && e.genres.length > 0 && (
|
{e.genres && e.genres.length > 0 && (
|
||||||
<div className="flex flex-wrap gap-1.5">
|
<div className="flex flex-wrap gap-1.5">
|
||||||
{e.genres.map((g) => (
|
{e.genres.map((g) => (
|
||||||
<Link key={g.id} to={`/library?genre=${encodeURIComponent(g.name)}`}>
|
<Link
|
||||||
<Badge variant="outline" className="text-xs cursor-pointer hover:bg-accent transition-colors">
|
key={g.id}
|
||||||
|
to={`/library?genre=${encodeURIComponent(g.name)}`}
|
||||||
|
>
|
||||||
|
<Badge
|
||||||
|
variant="outline"
|
||||||
|
className="text-xs cursor-pointer hover:bg-accent transition-colors"
|
||||||
|
>
|
||||||
{g.name}
|
{g.name}
|
||||||
</Badge>
|
</Badge>
|
||||||
</Link>
|
</Link>
|
||||||
@@ -385,16 +413,20 @@ export function EntryDetailsPage() {
|
|||||||
disabled={updateEntry.isPending}
|
disabled={updateEntry.isPending}
|
||||||
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors ${
|
className={`inline-flex items-center gap-1 rounded-full border px-3 py-1 text-sm font-medium transition-colors ${
|
||||||
e.favorit
|
e.favorit
|
||||||
? 'bg-yellow-500/15 border-yellow-500/30 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/25'
|
? "bg-yellow-500/15 border-yellow-500/30 text-yellow-600 dark:text-yellow-400 hover:bg-yellow-500/25"
|
||||||
: 'border-dashed border-border text-muted-foreground hover:border-yellow-500/40 hover:text-yellow-500'
|
: "border-dashed border-border text-muted-foreground hover:border-yellow-500/40 hover:text-yellow-500"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<Star className={`h-3.5 w-3.5 ${e.favorit ? 'fill-yellow-400 text-yellow-400' : ''}`} />
|
<Star
|
||||||
|
className={`h-3.5 w-3.5 ${e.favorit ? "fill-yellow-400 text-yellow-400" : ""}`}
|
||||||
|
/>
|
||||||
Favorit
|
Favorit
|
||||||
</button>
|
</button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>
|
<TooltipContent>
|
||||||
<p>{e.favorit ? 'Remove from favorites' : 'Add to favorites'}</p>
|
<p>
|
||||||
|
{e.favorit ? "Remove from favorites" : "Add to favorites"}
|
||||||
|
</p>
|
||||||
</TooltipContent>
|
</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
@@ -414,10 +446,14 @@ export function EntryDetailsPage() {
|
|||||||
{/* Streaming player */}
|
{/* Streaming player */}
|
||||||
<StreamingSection entry={e} seasons={seasons} />
|
<StreamingSection entry={e} seasons={seasons} />
|
||||||
|
|
||||||
{e.credits && e.credits.length > 0 && (
|
{credits.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<Separator />
|
<Separator />
|
||||||
<CastList credits={e.credits} entryId={e.id} isTvSeries={e.is_tvseries} />
|
<CastList
|
||||||
|
credits={credits}
|
||||||
|
entryId={e.id}
|
||||||
|
isTvSeries={e.is_tvseries}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -503,7 +539,7 @@ export function EntryDetailsPage() {
|
|||||||
variant="destructive"
|
variant="destructive"
|
||||||
onConfirm={() => {
|
onConfirm={() => {
|
||||||
deleteEntry.mutate(e.id, {
|
deleteEntry.mutate(e.id, {
|
||||||
onSuccess: () => navigate('/library'),
|
onSuccess: () => navigate("/library"),
|
||||||
});
|
});
|
||||||
setShowDeleteConfirm(false);
|
setShowDeleteConfirm(false);
|
||||||
}}
|
}}
|
||||||
@@ -517,7 +553,7 @@ function EntryCollectionsSection({ entryId }: { entryId: number }) {
|
|||||||
const { data: allCollections = [], isLoading } = useCollections();
|
const { data: allCollections = [], isLoading } = useCollections();
|
||||||
|
|
||||||
const collections = allCollections.filter((col: Collection) =>
|
const collections = allCollections.filter((col: Collection) =>
|
||||||
col.entries?.some((e: Entry) => e.id === entryId)
|
col.entries?.some((e: Entry) => e.id === entryId),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isLoading || collections.length === 0) return null;
|
if (isLoading || collections.length === 0) return null;
|
||||||
@@ -549,7 +585,8 @@ function EntryCollectionsSection({ entryId }: { entryId: number }) {
|
|||||||
</p>
|
</p>
|
||||||
{col.entries && (
|
{col.entries && (
|
||||||
<p className="text-xs text-white/70 mt-0.5">
|
<p className="text-xs text-white/70 mt-0.5">
|
||||||
{col.entries.length} {col.entries.length === 1 ? 'title' : 'titles'}
|
{col.entries.length}{" "}
|
||||||
|
{col.entries.length === 1 ? "title" : "titles"}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from "react";
|
||||||
import {
|
import {
|
||||||
useTrendingMovies,
|
useTrendingMovies,
|
||||||
useTrendingTv,
|
useTrendingTv,
|
||||||
@@ -7,9 +7,9 @@ import {
|
|||||||
useTopRatedMovies,
|
useTopRatedMovies,
|
||||||
useTopRatedTv,
|
useTopRatedTv,
|
||||||
useUpcomingMovies,
|
useUpcomingMovies,
|
||||||
} from '@/hooks/useTmdb';
|
} from "@/hooks/useTmdb";
|
||||||
import { useLibrary } from '@/hooks/useEntries';
|
import { useLibrary } from "@/hooks/useEntries";
|
||||||
import { TrendingUp, Play, Award, Calendar } from 'lucide-react';
|
import { TrendingUp, Play, Award, Calendar } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
HeroSlider,
|
HeroSlider,
|
||||||
BackdropCard,
|
BackdropCard,
|
||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
UpcomingCard,
|
UpcomingCard,
|
||||||
SectionHeader,
|
SectionHeader,
|
||||||
PopularBelt,
|
PopularBelt,
|
||||||
} from '@/components/home';
|
} from "@/components/home";
|
||||||
|
|
||||||
export function HomePage() {
|
export function HomePage() {
|
||||||
useLibrary();
|
useLibrary();
|
||||||
@@ -31,31 +31,43 @@ export function HomePage() {
|
|||||||
const topRatedTv = useTopRatedTv();
|
const topRatedTv = useTopRatedTv();
|
||||||
const upcomingMovies = useUpcomingMovies();
|
const upcomingMovies = useUpcomingMovies();
|
||||||
|
|
||||||
const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
const trendingMovieEntries =
|
||||||
const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
|
trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
const popularMovieEntries = popularMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
const trendingTvEntries =
|
||||||
const popularTvEntries = popularTv.data?.pages.flatMap((p) => p.results) ?? [];
|
trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
const topRatedMovieEntries = topRatedMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
const popularMovieEntries =
|
||||||
const topRatedTvEntries = topRatedTv.data?.pages.flatMap((p) => p.results) ?? [];
|
popularMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
const upcomingMovieEntries = upcomingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
const popularTvEntries =
|
||||||
|
popularTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
|
const topRatedMovieEntries =
|
||||||
|
topRatedMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
|
const topRatedTvEntries =
|
||||||
|
topRatedTv.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
|
const upcomingMovieEntries =
|
||||||
|
upcomingMovies.data?.pages.flatMap((p) => p.results) ?? [];
|
||||||
|
|
||||||
// Trending grid auto-rotation: exit -> swap -> enter
|
// Trending grid auto-rotation: exit -> swap -> enter
|
||||||
const [trendingIdx, setTrendingIdx] = useState(0);
|
const [trendingIdx, setTrendingIdx] = useState(0);
|
||||||
const [trendingPhase, setTrendingPhase] = useState<'idle' | 'exit' | 'enter'>('idle');
|
const [trendingPhase, setTrendingPhase] = useState<"idle" | "exit" | "enter">(
|
||||||
|
"idle",
|
||||||
|
);
|
||||||
const trendingPool = trendingMovieEntries.slice(2);
|
const trendingPool = trendingMovieEntries.slice(2);
|
||||||
const visibleTrending =
|
const visibleTrending =
|
||||||
trendingPool.length >= 4
|
trendingPool.length >= 4
|
||||||
? [0, 1, 2, 3].map((offset) => trendingPool[(trendingIdx + offset) % trendingPool.length])
|
? [0, 1, 2, 3].map(
|
||||||
|
(offset) =>
|
||||||
|
trendingPool[(trendingIdx + offset) % trendingPool.length],
|
||||||
|
)
|
||||||
: trendingPool;
|
: trendingPool;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (trendingPool.length <= 4) return;
|
if (trendingPool.length <= 4) return;
|
||||||
const timer = setInterval(() => {
|
const timer = setInterval(() => {
|
||||||
setTrendingPhase('exit');
|
setTrendingPhase("exit");
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setTrendingIdx((i) => i + 1);
|
setTrendingIdx((i) => i + 1);
|
||||||
setTrendingPhase('enter');
|
setTrendingPhase("enter");
|
||||||
setTimeout(() => setTrendingPhase('idle'), 600);
|
setTimeout(() => setTrendingPhase("idle"), 600);
|
||||||
}, 380);
|
}, 380);
|
||||||
}, 7000);
|
}, 7000);
|
||||||
return () => clearInterval(timer);
|
return () => clearInterval(timer);
|
||||||
@@ -91,19 +103,27 @@ export function HomePage() {
|
|||||||
<div
|
<div
|
||||||
className="xl:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-4 overflow-hidden"
|
className="xl:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-4 overflow-hidden"
|
||||||
style={{
|
style={{
|
||||||
opacity: trendingPhase === 'exit' ? 0 : 1,
|
opacity: trendingPhase === "exit" ? 0 : 1,
|
||||||
transform: trendingPhase === 'exit' ? 'translateX(-28px)' : 'translateX(0)',
|
transform:
|
||||||
transition: trendingPhase === 'exit'
|
trendingPhase === "exit"
|
||||||
? 'opacity 380ms ease, transform 380ms ease'
|
? "translateX(-28px)"
|
||||||
: 'none',
|
: "translateX(0)",
|
||||||
|
transition:
|
||||||
|
trendingPhase === "exit"
|
||||||
|
? "opacity 380ms ease, transform 380ms ease"
|
||||||
|
: "none",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{visibleTrending.map((item, i) => (
|
{visibleTrending.map((item, i) => (
|
||||||
<BackdropCard
|
<BackdropCard
|
||||||
key={`${item.id}-${trendingIdx}`}
|
key={`${item.id}-${trendingIdx}`}
|
||||||
entry={item}
|
entry={item}
|
||||||
animClass={trendingPhase === 'enter' ? 'animate-slide-from-right' : undefined}
|
animClass={
|
||||||
animDelay={trendingPhase === 'enter' ? i * 90 : 0}
|
trendingPhase === "enter"
|
||||||
|
? "animate-slide-from-right"
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
animDelay={trendingPhase === "enter" ? i * 90 : 0}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -126,7 +146,10 @@ export function HomePage() {
|
|||||||
title="Popular Right Now"
|
title="Popular Right Now"
|
||||||
category="popular"
|
category="popular"
|
||||||
/>
|
/>
|
||||||
<PopularBelt movieEntries={popularMovieEntries} tvEntries={popularTvEntries} />
|
<PopularBelt
|
||||||
|
movieEntries={popularMovieEntries}
|
||||||
|
tvEntries={popularTvEntries}
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{/* Top Rated */}
|
{/* Top Rated */}
|
||||||
@@ -172,7 +195,12 @@ export function HomePage() {
|
|||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
className="flex gap-3 overflow-x-auto pb-2"
|
className="flex gap-3 overflow-x-auto pb-2"
|
||||||
style={{ scrollbarWidth: 'none', msOverflowStyle: 'none' } as React.CSSProperties}
|
style={
|
||||||
|
{
|
||||||
|
scrollbarWidth: "none",
|
||||||
|
msOverflowStyle: "none",
|
||||||
|
} as React.CSSProperties
|
||||||
|
}
|
||||||
>
|
>
|
||||||
{upcomingMovieEntries.slice(0, 14).map((item) => (
|
{upcomingMovieEntries.slice(0, 14).map((item) => (
|
||||||
<UpcomingCard key={item.id} entry={item} />
|
<UpcomingCard key={item.id} entry={item} />
|
||||||
@@ -187,13 +215,22 @@ function HomeLoadingSkeleton() {
|
|||||||
return (
|
return (
|
||||||
<div className="animate-pulse space-y-12 pb-12">
|
<div className="animate-pulse space-y-12 pb-12">
|
||||||
<div className="-mx-4 -mt-18 md:-mx-6 md:-mt-6">
|
<div className="-mx-4 -mt-18 md:-mx-6 md:-mt-6">
|
||||||
<div className="w-full bg-muted" style={{ aspectRatio: '16/9', maxHeight: '70vh' }} />
|
<div
|
||||||
|
className="w-full bg-muted"
|
||||||
|
style={{ aspectRatio: "16/9", maxHeight: "70vh" }}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="h-6 w-48 rounded bg-muted" />
|
<div className="h-6 w-48 rounded bg-muted" />
|
||||||
<div className="grid grid-cols-2 gap-4">
|
<div className="grid grid-cols-2 gap-4">
|
||||||
<div className="rounded-xl bg-muted" style={{ aspectRatio: '16/9' }} />
|
<div
|
||||||
<div className="rounded-xl bg-muted" style={{ aspectRatio: '16/9' }} />
|
className="rounded-xl bg-muted"
|
||||||
|
style={{ aspectRatio: "16/9" }}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className="rounded-xl bg-muted"
|
||||||
|
style={{ aspectRatio: "16/9" }}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,49 +1,82 @@
|
|||||||
import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
|
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
|
||||||
import { useSearchParams, useNavigationType } from 'react-router-dom';
|
import { useSearchParams, useNavigationType } from "react-router-dom";
|
||||||
import { useLibrary } from '@/hooks/useEntries';
|
import { useLibrary } from "@/hooks/useEntries";
|
||||||
import { useLibraryEntries } from '@/stores/useLibraryStore';
|
import { useLibraryEntries } from "@/stores/useLibraryStore";
|
||||||
import { useLibraryFiltersStore, defaultFilters } from '@/stores/useLibraryFiltersStore';
|
import {
|
||||||
import type { FilterTab, SortField, SortDir, Filters } from '@/stores/useLibraryFiltersStore';
|
useLibraryFiltersStore,
|
||||||
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
|
defaultFilters,
|
||||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
} from "@/stores/useLibraryFiltersStore";
|
||||||
import { Input } from '@/components/ui/input';
|
import type {
|
||||||
import { Button } from '@/components/ui/button';
|
FilterTab,
|
||||||
import { Badge } from '@/components/ui/badge';
|
SortField,
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
SortDir,
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
Filters,
|
||||||
import { Search, X, SlidersHorizontal, ArrowUpDown } from 'lucide-react';
|
} from "@/stores/useLibraryFiltersStore";
|
||||||
import type { Entry } from '@/types';
|
import { EntryLibraryGrid } from "@/components/entries/EntryLibraryGrid";
|
||||||
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import {
|
||||||
|
Popover,
|
||||||
|
PopoverContent,
|
||||||
|
PopoverTrigger,
|
||||||
|
} from "@/components/ui/popover";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Search, X, SlidersHorizontal, ArrowUpDown, Info } from "lucide-react";
|
||||||
|
import type { Entry } from "@/types";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipProvider,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/components/ui/tooltip";
|
||||||
|
|
||||||
const sortLabels: Record<SortField, string> = {
|
const sortLabels: Record<SortField, string> = {
|
||||||
date_last_seen: 'Last Watched',
|
date_last_seen: "Last Watched",
|
||||||
createdAt: 'Date Added',
|
createdAt: "Date Added",
|
||||||
title: 'Title',
|
title: "Title",
|
||||||
release_date: 'Release Date',
|
release_date: "Release Date",
|
||||||
rating: 'Rating',
|
rating: "Rating",
|
||||||
};
|
};
|
||||||
|
|
||||||
function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[] {
|
function sortEntries(
|
||||||
|
entries: Entry[],
|
||||||
|
field: SortField,
|
||||||
|
dir: SortDir,
|
||||||
|
): Entry[] {
|
||||||
return [...entries].sort((a, b) => {
|
return [...entries].sort((a, b) => {
|
||||||
let cmp = 0;
|
let cmp = 0;
|
||||||
switch (field) {
|
switch (field) {
|
||||||
case 'title':
|
case "title":
|
||||||
cmp = a.title.localeCompare(b.title);
|
cmp = a.title.localeCompare(b.title);
|
||||||
break;
|
break;
|
||||||
case 'release_date':
|
case "release_date":
|
||||||
cmp = new Date(a.release_date || '1900').getTime() - new Date(b.release_date || '1900').getTime();
|
cmp =
|
||||||
|
new Date(a.release_date || "1900").getTime() -
|
||||||
|
new Date(b.release_date || "1900").getTime();
|
||||||
break;
|
break;
|
||||||
case 'rating':
|
case "rating":
|
||||||
cmp = (a.entryRatings?.user_rating ?? 0) -
|
cmp =
|
||||||
|
(a.entryRatings?.user_rating ?? 0) -
|
||||||
(b.entryRatings?.user_rating ?? 0);
|
(b.entryRatings?.user_rating ?? 0);
|
||||||
break;
|
break;
|
||||||
case 'date_last_seen':
|
case "date_last_seen":
|
||||||
cmp = new Date(a.date_last_seen || '1900').getTime() - new Date(b.date_last_seen || '1900').getTime();
|
cmp =
|
||||||
|
new Date(a.date_last_seen || "1900").getTime() -
|
||||||
|
new Date(b.date_last_seen || "1900").getTime();
|
||||||
break;
|
break;
|
||||||
case 'createdAt':
|
case "createdAt":
|
||||||
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
return dir === 'desc' ? -cmp : cmp;
|
return dir === "desc" ? -cmp : cmp;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,7 +110,7 @@ export function LibraryPage() {
|
|||||||
|
|
||||||
// Reset filters when navigating TO the library (not when pressing back)
|
// Reset filters when navigating TO the library (not when pressing back)
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (navigationType !== 'POP') {
|
if (navigationType !== "POP") {
|
||||||
resetAll();
|
resetAll();
|
||||||
}
|
}
|
||||||
// Only run on mount
|
// Only run on mount
|
||||||
@@ -88,11 +121,16 @@ export function LibraryPage() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (filtersInitialized.current) return;
|
if (filtersInitialized.current) return;
|
||||||
filtersInitialized.current = true;
|
filtersInitialized.current = true;
|
||||||
const genre = searchParams.get('genre') || '';
|
const genre = searchParams.get("genre") || "";
|
||||||
const ratingMin = searchParams.get('ratingMin') || '';
|
const ratingMin = searchParams.get("ratingMin") || "";
|
||||||
const ratingMax = searchParams.get('ratingMax') || '';
|
const ratingMax = searchParams.get("ratingMax") || "";
|
||||||
if (genre || ratingMin || ratingMax) {
|
if (genre || ratingMin || ratingMax) {
|
||||||
const newFilters = { ...defaultFilters, genre, userRatingMin: ratingMin, userRatingMax: ratingMax };
|
const newFilters = {
|
||||||
|
...defaultFilters,
|
||||||
|
genre,
|
||||||
|
userRatingMin: ratingMin,
|
||||||
|
userRatingMax: ratingMax,
|
||||||
|
};
|
||||||
setFilters(newFilters);
|
setFilters(newFilters);
|
||||||
setDebouncedFilters(newFilters);
|
setDebouncedFilters(newFilters);
|
||||||
// Clear URL params after applying
|
// Clear URL params after applying
|
||||||
@@ -124,17 +162,28 @@ export function LibraryPage() {
|
|||||||
return Array.from(set).sort();
|
return Array.from(set).sort();
|
||||||
}, [allEntries]);
|
}, [allEntries]);
|
||||||
|
|
||||||
const hasActiveFilters = filters.genre || filters.tmdbRatingMin || filters.tmdbRatingMax || filters.userRatingMin || filters.userRatingMax || filters.yearMin || filters.yearMax;
|
const hasActiveFilters =
|
||||||
|
filters.genre ||
|
||||||
|
filters.tmdbRatingMin ||
|
||||||
|
filters.tmdbRatingMax ||
|
||||||
|
filters.userRatingMin ||
|
||||||
|
filters.userRatingMax ||
|
||||||
|
filters.yearMin ||
|
||||||
|
filters.yearMax;
|
||||||
|
|
||||||
const baseEntries = useMemo(() => {
|
const baseEntries = useMemo(() => {
|
||||||
switch (activeTab) {
|
switch (activeTab) {
|
||||||
case 'movies':
|
case "movies":
|
||||||
return allEntries.filter((e) => !e.is_tvseries && !e.watchlist && !e.hidden);
|
return allEntries.filter(
|
||||||
case 'tv':
|
(e) => !e.is_tvseries && !e.watchlist && !e.hidden,
|
||||||
return allEntries.filter((e) => e.is_tvseries && !e.watchlist && !e.hidden);
|
);
|
||||||
case 'favorites':
|
case "tv":
|
||||||
|
return allEntries.filter(
|
||||||
|
(e) => e.is_tvseries && !e.watchlist && !e.hidden,
|
||||||
|
);
|
||||||
|
case "favorites":
|
||||||
return allEntries.filter((e) => e.favorit && !e.watchlist && !e.hidden);
|
return allEntries.filter((e) => e.favorit && !e.watchlist && !e.hidden);
|
||||||
case 'hidden':
|
case "hidden":
|
||||||
return allEntries.filter((e) => e.hidden);
|
return allEntries.filter((e) => e.hidden);
|
||||||
default:
|
default:
|
||||||
return allEntries.filter((e) => !e.watchlist && !e.hidden);
|
return allEntries.filter((e) => !e.watchlist && !e.hidden);
|
||||||
@@ -146,11 +195,23 @@ export function LibraryPage() {
|
|||||||
|
|
||||||
if (debouncedSearch) {
|
if (debouncedSearch) {
|
||||||
const q = debouncedSearch.toLowerCase();
|
const q = debouncedSearch.toLowerCase();
|
||||||
|
const directorPrefix = "@director:";
|
||||||
|
if (q.startsWith(directorPrefix)) {
|
||||||
|
const dirQuery = q.slice(directorPrefix.length).trim();
|
||||||
|
if (dirQuery) {
|
||||||
|
result = result.filter(
|
||||||
|
(e) => e.director && e.director.toLowerCase().includes(dirQuery),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
result = result.filter((e) => e.title.toLowerCase().includes(q));
|
result = result.filter((e) => e.title.toLowerCase().includes(q));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (debouncedFilters.genre) {
|
if (debouncedFilters.genre) {
|
||||||
result = result.filter((e) => e.genres?.some((g) => g.name === debouncedFilters.genre));
|
result = result.filter((e) =>
|
||||||
|
e.genres?.some((g) => g.name === debouncedFilters.genre),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (debouncedFilters.tmdbRatingMin) {
|
if (debouncedFilters.tmdbRatingMin) {
|
||||||
const min = parseFloat(debouncedFilters.tmdbRatingMin);
|
const min = parseFloat(debouncedFilters.tmdbRatingMin);
|
||||||
@@ -170,11 +231,15 @@ export function LibraryPage() {
|
|||||||
}
|
}
|
||||||
if (debouncedFilters.yearMin) {
|
if (debouncedFilters.yearMin) {
|
||||||
const min = parseInt(debouncedFilters.yearMin);
|
const min = parseInt(debouncedFilters.yearMin);
|
||||||
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() >= min);
|
result = result.filter(
|
||||||
|
(e) => e.release_date && new Date(e.release_date).getFullYear() >= min,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (debouncedFilters.yearMax) {
|
if (debouncedFilters.yearMax) {
|
||||||
const max = parseInt(debouncedFilters.yearMax);
|
const max = parseInt(debouncedFilters.yearMax);
|
||||||
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() <= max);
|
result = result.filter(
|
||||||
|
(e) => e.release_date && new Date(e.release_date).getFullYear() <= max,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return sortEntries(result, sortField, sortDir);
|
return sortEntries(result, sortField, sortDir);
|
||||||
@@ -182,7 +247,7 @@ export function LibraryPage() {
|
|||||||
|
|
||||||
const paginatedEntries = useMemo(
|
const paginatedEntries = useMemo(
|
||||||
() => filteredEntries.slice(0, visibleCount),
|
() => filteredEntries.slice(0, visibleCount),
|
||||||
[filteredEntries, visibleCount]
|
[filteredEntries, visibleCount],
|
||||||
);
|
);
|
||||||
const hasMore = visibleCount < filteredEntries.length;
|
const hasMore = visibleCount < filteredEntries.length;
|
||||||
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
|
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
|
||||||
@@ -207,7 +272,7 @@ export function LibraryPage() {
|
|||||||
/>
|
/>
|
||||||
{search && (
|
{search && (
|
||||||
<button
|
<button
|
||||||
onClick={() => setSearch('')}
|
onClick={() => setSearch("")}
|
||||||
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
|
||||||
>
|
>
|
||||||
<X className="h-4 w-4" />
|
<X className="h-4 w-4" />
|
||||||
@@ -215,18 +280,56 @@ export function LibraryPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Search tips */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger>
|
||||||
|
<Info className="h-4 w-4 text-muted-foreground hover:text-foreground cursor-pointer shrink-0" />
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent
|
||||||
|
side="bottom"
|
||||||
|
className="w-56 text-xs"
|
||||||
|
align="start"
|
||||||
|
>
|
||||||
|
<p className="font-semibold mb-1.5">Search prefixes</p>
|
||||||
|
<p className="mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@director:name
|
||||||
|
</code>{" "}
|
||||||
|
— by director
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@country:name
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@year:year
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
{/* Sort (icon + popover on mobile) */}
|
{/* Sort (icon + popover on mobile) */}
|
||||||
<Popover>
|
<Popover>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button variant="outline" size="icon" className="h-9 w-9 shrink-0 relative">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="h-9 w-9 shrink-0 relative"
|
||||||
|
>
|
||||||
<ArrowUpDown className="h-4 w-4" />
|
<ArrowUpDown className="h-4 w-4" />
|
||||||
{sortField !== 'date_last_seen' && (
|
{sortField !== "date_last_seen" && (
|
||||||
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
||||||
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Sort by</p>
|
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Sort by
|
||||||
|
</p>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{Object.entries(sortLabels).map(([value, label]) => (
|
{Object.entries(sortLabels).map(([value, label]) => (
|
||||||
<button
|
<button
|
||||||
@@ -234,8 +337,8 @@ export function LibraryPage() {
|
|||||||
onClick={() => setSortField(value as SortField)}
|
onClick={() => setSortField(value as SortField)}
|
||||||
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
||||||
sortField === value
|
sortField === value
|
||||||
? 'bg-accent text-accent-foreground font-medium'
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
: 'hover:bg-accent/50'
|
: "hover:bg-accent/50"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
@@ -244,18 +347,18 @@ export function LibraryPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="flex gap-1 pt-1 border-t border-border">
|
<div className="flex gap-1 pt-1 border-t border-border">
|
||||||
<Button
|
<Button
|
||||||
variant={sortDir === 'desc' ? 'default' : 'outline'}
|
variant={sortDir === "desc" ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
className="flex-1 h-8 text-xs"
|
className="flex-1 h-8 text-xs"
|
||||||
onClick={() => setSortDir('desc')}
|
onClick={() => setSortDir("desc")}
|
||||||
>
|
>
|
||||||
↓ Desc
|
↓ Desc
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
variant={sortDir === 'asc' ? 'default' : 'outline'}
|
variant={sortDir === "asc" ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
className="flex-1 h-8 text-xs"
|
className="flex-1 h-8 text-xs"
|
||||||
onClick={() => setSortDir('asc')}
|
onClick={() => setSortDir("asc")}
|
||||||
>
|
>
|
||||||
↑ Asc
|
↑ Asc
|
||||||
</Button>
|
</Button>
|
||||||
@@ -266,7 +369,11 @@ export function LibraryPage() {
|
|||||||
{/* Filter */}
|
{/* Filter */}
|
||||||
<Popover>
|
<Popover>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button variant="outline" size="icon" className="h-9 w-9 shrink-0 relative">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="h-9 w-9 shrink-0 relative"
|
||||||
|
>
|
||||||
<SlidersHorizontal className="h-4 w-4" />
|
<SlidersHorizontal className="h-4 w-4" />
|
||||||
{hasActiveFilters && (
|
{hasActiveFilters && (
|
||||||
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
||||||
@@ -276,40 +383,137 @@ export function LibraryPage() {
|
|||||||
<PopoverContent className="w-72 space-y-4" align="end">
|
<PopoverContent className="w-72 space-y-4" align="end">
|
||||||
<div className="">
|
<div className="">
|
||||||
<label className="text-sm font-medium">Genre</label>
|
<label className="text-sm font-medium">Genre</label>
|
||||||
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}>
|
<Select
|
||||||
<SelectTrigger className="h-9"><SelectValue placeholder="All genres" /></SelectTrigger>
|
value={filters.genre}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
setFilters((f) => ({
|
||||||
|
...f,
|
||||||
|
genre: v === "_all" ? "" : v || "",
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="h-9">
|
||||||
|
<SelectValue placeholder="All genres" />
|
||||||
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="_all">All genres</SelectItem>
|
<SelectItem value="_all">All genres</SelectItem>
|
||||||
{allGenres.map((g) => <SelectItem key={g} value={g}>{g}</SelectItem>)}
|
{allGenres.map((g) => (
|
||||||
|
<SelectItem key={g} value={g}>
|
||||||
|
{g}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="">
|
<div className="">
|
||||||
<label className="text-sm font-medium">TMDB Rating</label>
|
<label className="text-sm font-medium">TMDB Rating</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.tmdbRatingMin} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Min"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.tmdbRatingMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({
|
||||||
|
...f,
|
||||||
|
tmdbRatingMin: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.tmdbRatingMax} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Max"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.tmdbRatingMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({
|
||||||
|
...f,
|
||||||
|
tmdbRatingMax: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="">
|
<div className="">
|
||||||
<label className="text-sm font-medium">User Rating</label>
|
<label className="text-sm font-medium">User Rating</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.userRatingMin} onChange={(e) => setFilters((f) => ({ ...f, userRatingMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Min"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.userRatingMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({
|
||||||
|
...f,
|
||||||
|
userRatingMin: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.userRatingMax} onChange={(e) => setFilters((f) => ({ ...f, userRatingMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Max"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.userRatingMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({
|
||||||
|
...f,
|
||||||
|
userRatingMax: e.target.value,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="">
|
<div className="">
|
||||||
<label className="text-sm font-medium">Year Range</label>
|
<label className="text-sm font-medium">Year Range</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="From" min={1950} max={2100} value={filters.yearMin} onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="From"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="To" min={1950} max={2100} value={filters.yearMax} onChange={(e) => setFilters((f) => ({ ...f, yearMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="To"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{hasActiveFilters && (
|
{hasActiveFilters && (
|
||||||
<Button variant="ghost" size="sm" className="w-full" onClick={clearFilters}>Clear Filters</Button>
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-full"
|
||||||
|
onClick={clearFilters}
|
||||||
|
>
|
||||||
|
Clear Filters
|
||||||
|
</Button>
|
||||||
)}
|
)}
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@@ -317,7 +521,10 @@ export function LibraryPage() {
|
|||||||
|
|
||||||
{/* Row 2: scrollable type tabs */}
|
{/* Row 2: scrollable type tabs */}
|
||||||
<div className="overflow-x-auto pb-1">
|
<div className="overflow-x-auto pb-1">
|
||||||
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as FilterTab)}>
|
<Tabs
|
||||||
|
value={activeTab}
|
||||||
|
onValueChange={(v) => setActiveTab(v as FilterTab)}
|
||||||
|
>
|
||||||
<TabsList className="w-max">
|
<TabsList className="w-max">
|
||||||
<TabsTrigger value="all">All</TabsTrigger>
|
<TabsTrigger value="all">All</TabsTrigger>
|
||||||
<TabsTrigger value="movies">Movies</TabsTrigger>
|
<TabsTrigger value="movies">Movies</TabsTrigger>
|
||||||
@@ -342,8 +549,36 @@ export function LibraryPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Search tips */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger>
|
||||||
|
<Info className="h-4 w-4 text-muted-foreground hover:text-foreground cursor-pointer shrink-0" />
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent side="bottom" className="w-56 text-xs" align="start">
|
||||||
|
<p className="font-semibold mb-1.5">Search prefixes</p>
|
||||||
|
<p className="mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@director:name
|
||||||
|
</code>{" "}
|
||||||
|
— by director
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@country:name
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@year:year
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
{search && (
|
{search && (
|
||||||
<Button variant="ghost" size="sm" onClick={() => setSearch('')}>
|
<Button variant="ghost" size="sm" onClick={() => setSearch("")}>
|
||||||
<X className="mr-1 h-4 w-4" /> Clear
|
<X className="mr-1 h-4 w-4" /> Clear
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
@@ -356,11 +591,15 @@ export function LibraryPage() {
|
|||||||
<Button variant="outline" size="sm" className="h-9 gap-1.5">
|
<Button variant="outline" size="sm" className="h-9 gap-1.5">
|
||||||
<ArrowUpDown className="h-4 w-4" />
|
<ArrowUpDown className="h-4 w-4" />
|
||||||
{sortLabels[sortField]}
|
{sortLabels[sortField]}
|
||||||
<span className="text-xs opacity-60">{sortDir === 'desc' ? '↓' : '↑'}</span>
|
<span className="text-xs opacity-60">
|
||||||
|
{sortDir === "desc" ? "↓" : "↑"}
|
||||||
|
</span>
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
||||||
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Sort by</p>
|
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Sort by
|
||||||
|
</p>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{Object.entries(sortLabels).map(([value, label]) => (
|
{Object.entries(sortLabels).map(([value, label]) => (
|
||||||
<button
|
<button
|
||||||
@@ -368,8 +607,8 @@ export function LibraryPage() {
|
|||||||
onClick={() => setSortField(value as SortField)}
|
onClick={() => setSortField(value as SortField)}
|
||||||
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
||||||
sortField === value
|
sortField === value
|
||||||
? 'bg-accent text-accent-foreground font-medium'
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
: 'hover:bg-accent/50'
|
: "hover:bg-accent/50"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
@@ -377,8 +616,22 @@ export function LibraryPage() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-1 pt-1 border-t border-border">
|
<div className="flex gap-1 pt-1 border-t border-border">
|
||||||
<Button variant={sortDir === 'desc' ? 'default' : 'outline'} size="sm" className="flex-1 h-8 text-xs" onClick={() => setSortDir('desc')}>↓ Desc</Button>
|
<Button
|
||||||
<Button variant={sortDir === 'asc' ? 'default' : 'outline'} size="sm" className="flex-1 h-8 text-xs" onClick={() => setSortDir('asc')}>↑ Asc</Button>
|
variant={sortDir === "desc" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
className="flex-1 h-8 text-xs"
|
||||||
|
onClick={() => setSortDir("desc")}
|
||||||
|
>
|
||||||
|
↓ Desc
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={sortDir === "asc" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
className="flex-1 h-8 text-xs"
|
||||||
|
onClick={() => setSortDir("asc")}
|
||||||
|
>
|
||||||
|
↑ Asc
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@@ -389,52 +642,147 @@ export function LibraryPage() {
|
|||||||
<Button variant="outline" size="sm" className="h-9 gap-1">
|
<Button variant="outline" size="sm" className="h-9 gap-1">
|
||||||
<SlidersHorizontal className="h-4 w-4" />
|
<SlidersHorizontal className="h-4 w-4" />
|
||||||
Filter
|
Filter
|
||||||
{hasActiveFilters && <Badge variant="secondary" className="ml-1 h-5 px-1 text-[10px]">Active</Badge>}
|
{hasActiveFilters && (
|
||||||
|
<Badge
|
||||||
|
variant="secondary"
|
||||||
|
className="ml-1 h-5 px-1 text-[10px]"
|
||||||
|
>
|
||||||
|
Active
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-72 space-y-4" align="end">
|
<PopoverContent className="w-72 space-y-4" align="end">
|
||||||
<div className="space-y-2 mb-0">
|
<div className="space-y-2 mb-0">
|
||||||
<label className="text-sm font-medium">Genre</label>
|
<label className="text-sm font-medium">Genre</label>
|
||||||
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}>
|
<Select
|
||||||
<SelectTrigger className="h-9 w-full"><SelectValue placeholder="All genres" /></SelectTrigger>
|
value={filters.genre}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
setFilters((f) => ({
|
||||||
|
...f,
|
||||||
|
genre: v === "_all" ? "" : v || "",
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="h-9 w-full">
|
||||||
|
<SelectValue placeholder="All genres" />
|
||||||
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="_all">All genres</SelectItem>
|
<SelectItem value="_all">All genres</SelectItem>
|
||||||
{allGenres.map((g) => <SelectItem key={g} value={g}>{g}</SelectItem>)}
|
{allGenres.map((g) => (
|
||||||
|
<SelectItem key={g} value={g}>
|
||||||
|
{g}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 mb-0">
|
<div className="space-y-2 mb-0">
|
||||||
<label className="text-sm font-medium">TMDB Rating</label>
|
<label className="text-sm font-medium">TMDB Rating</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.tmdbRatingMin} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Min"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.tmdbRatingMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, tmdbRatingMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.tmdbRatingMax} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Max"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.tmdbRatingMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, tmdbRatingMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2 mb-0">
|
<div className="space-y-2 mb-0">
|
||||||
<label className="text-sm font-medium">User Rating</label>
|
<label className="text-sm font-medium">User Rating</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.userRatingMin} onChange={(e) => setFilters((f) => ({ ...f, userRatingMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Min"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.userRatingMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, userRatingMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.userRatingMax} onChange={(e) => setFilters((f) => ({ ...f, userRatingMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Max"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={1}
|
||||||
|
value={filters.userRatingMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, userRatingMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Year Range</label>
|
<label className="text-sm font-medium">Year Range</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="From" min={1950} max={2100} value={filters.yearMin} onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="From"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="To" min={1950} max={2100} value={filters.yearMax} onChange={(e) => setFilters((f) => ({ ...f, yearMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="To"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{hasActiveFilters && (
|
{hasActiveFilters && (
|
||||||
<Button variant="ghost" size="sm" className="w-full" onClick={clearFilters}>Clear Filters</Button>
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-full"
|
||||||
|
onClick={clearFilters}
|
||||||
|
>
|
||||||
|
Clear Filters
|
||||||
|
</Button>
|
||||||
)}
|
)}
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
|
|
||||||
{/* Tabs */}
|
{/* Tabs */}
|
||||||
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as FilterTab)}>
|
<Tabs
|
||||||
|
value={activeTab}
|
||||||
|
onValueChange={(v) => setActiveTab(v as FilterTab)}
|
||||||
|
>
|
||||||
<TabsList>
|
<TabsList>
|
||||||
<TabsTrigger value="all">All</TabsTrigger>
|
<TabsTrigger value="all">All</TabsTrigger>
|
||||||
<TabsTrigger value="movies">Movies</TabsTrigger>
|
<TabsTrigger value="movies">Movies</TabsTrigger>
|
||||||
|
|||||||
@@ -1,20 +1,26 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from "react";
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { settingsApi } from '@/api/settings';
|
import { settingsApi } from "@/api/settings";
|
||||||
import { maintenanceApi, type OrphanResult } from '@/api/maintenance';
|
import { maintenanceApi, type OrphanResult } from "@/api/maintenance";
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from "react-hook-form";
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import { z } from 'zod';
|
import { z } from "zod";
|
||||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
import {
|
||||||
import { Input } from '@/components/ui/input';
|
Card,
|
||||||
import { Label } from '@/components/ui/label';
|
CardContent,
|
||||||
import { Button } from '@/components/ui/button';
|
CardHeader,
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
CardTitle,
|
||||||
import { Save, Search, Trash2, Loader2 } from 'lucide-react';
|
CardDescription,
|
||||||
import type { Settings } from '@/types';
|
} from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
|
import { Save, Search, Trash2, Loader2 } from "lucide-react";
|
||||||
|
import type { Settings } from "@/types";
|
||||||
|
|
||||||
const settingsSchema = z.object({
|
const settingsSchema = z.object({
|
||||||
tmdbApiKey: z.string().min(1, 'TMDB API key is required'),
|
tmdbApiKey: z.string().min(1, "TMDB API key is required"),
|
||||||
backPort: z.coerce.number().int().positive(),
|
backPort: z.coerce.number().int().positive(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -24,7 +30,7 @@ function formatOrphanResult(result: OrphanResult): string {
|
|||||||
if (result.logos) parts.push(`${result.logos} logo(s)`);
|
if (result.logos) parts.push(`${result.logos} logo(s)`);
|
||||||
if (result.backdrops) parts.push(`${result.backdrops} backdrop(s)`);
|
if (result.backdrops) parts.push(`${result.backdrops} backdrop(s)`);
|
||||||
if (result.stills) parts.push(`${result.stills} still(s)`);
|
if (result.stills) parts.push(`${result.stills} still(s)`);
|
||||||
return parts.length > 0 ? parts.join(', ') : 'None found';
|
return parts.length > 0 ? parts.join(", ") : "None found";
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasOrphans(result: OrphanResult | null): boolean {
|
function hasOrphans(result: OrphanResult | null): boolean {
|
||||||
@@ -32,22 +38,83 @@ function hasOrphans(result: OrphanResult | null): boolean {
|
|||||||
return result.posters + result.logos + result.backdrops + result.stills > 0;
|
return result.posters + result.logos + result.backdrops + result.stills > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function MissingDirectorsSection() {
|
||||||
|
const [result, setResult] = useState<{ count: number; fixed: number } | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
|
||||||
|
const scan = useMutation({
|
||||||
|
mutationFn: maintenanceApi.scanMissingDirectors,
|
||||||
|
onSuccess: (data) => setResult(data),
|
||||||
|
});
|
||||||
|
|
||||||
|
const fix = useMutation({
|
||||||
|
mutationFn: maintenanceApi.fixMissingDirectors,
|
||||||
|
onSuccess: (data) => setResult(data),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => scan.mutate()}
|
||||||
|
disabled={scan.isPending}
|
||||||
|
>
|
||||||
|
{scan.isPending ? (
|
||||||
|
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Search className="mr-1.5 h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
Scan
|
||||||
|
</Button>
|
||||||
|
{result && result.count > 0 && (
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => fix.mutate()}
|
||||||
|
disabled={fix.isPending}
|
||||||
|
>
|
||||||
|
{fix.isPending ? (
|
||||||
|
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Save className="mr-1.5 h-3.5 w-3.5" />
|
||||||
|
)}
|
||||||
|
Fix All
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{result && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{result.count === 0
|
||||||
|
? "All entries have directors."
|
||||||
|
: result.fixed > 0
|
||||||
|
? `Fixed ${result.fixed} of ${result.count} missing directors.`
|
||||||
|
: `${result.count} entries missing director.`}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function SettingsPage() {
|
export function SettingsPage() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { data: settings, isLoading } = useQuery({
|
const { data: settings, isLoading } = useQuery({
|
||||||
queryKey: ['settings'],
|
queryKey: ["settings"],
|
||||||
queryFn: settingsApi.get,
|
queryFn: settingsApi.get,
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateSettings = useMutation({
|
const updateSettings = useMutation({
|
||||||
mutationFn: (data: Partial<Settings>) => settingsApi.update(data),
|
mutationFn: (data: Partial<Settings>) => settingsApi.update(data),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['settings'] });
|
queryClient.invalidateQueries({ queryKey: ["settings"] });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Orphan files cleanup
|
// Orphan files cleanup
|
||||||
const [orphanFilesResult, setOrphanFilesResult] = useState<OrphanResult | null>(null);
|
const [orphanFilesResult, setOrphanFilesResult] =
|
||||||
|
useState<OrphanResult | null>(null);
|
||||||
const scanOrphanFiles = useMutation({
|
const scanOrphanFiles = useMutation({
|
||||||
mutationFn: maintenanceApi.scanOrphanFiles,
|
mutationFn: maintenanceApi.scanOrphanFiles,
|
||||||
onSuccess: (data) => setOrphanFilesResult(data),
|
onSuccess: (data) => setOrphanFilesResult(data),
|
||||||
@@ -60,7 +127,8 @@ export function SettingsPage() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Orphan media records cleanup
|
// Orphan media records cleanup
|
||||||
const [orphanRecordsResult, setOrphanRecordsResult] = useState<OrphanResult | null>(null);
|
const [orphanRecordsResult, setOrphanRecordsResult] =
|
||||||
|
useState<OrphanResult | null>(null);
|
||||||
const scanOrphanRecords = useMutation({
|
const scanOrphanRecords = useMutation({
|
||||||
mutationFn: maintenanceApi.scanOrphanMediaRecords,
|
mutationFn: maintenanceApi.scanOrphanMediaRecords,
|
||||||
onSuccess: (data) => setOrphanRecordsResult(data),
|
onSuccess: (data) => setOrphanRecordsResult(data),
|
||||||
@@ -111,7 +179,7 @@ export function SettingsPage() {
|
|||||||
<Input
|
<Input
|
||||||
id="tmdbApiKey"
|
id="tmdbApiKey"
|
||||||
type="password"
|
type="password"
|
||||||
{...register('tmdbApiKey')}
|
{...register("tmdbApiKey")}
|
||||||
/>
|
/>
|
||||||
{errors.tmdbApiKey && (
|
{errors.tmdbApiKey && (
|
||||||
<p className="text-xs text-destructive">
|
<p className="text-xs text-destructive">
|
||||||
@@ -122,11 +190,7 @@ export function SettingsPage() {
|
|||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="backPort">Backend Port</Label>
|
<Label htmlFor="backPort">Backend Port</Label>
|
||||||
<Input
|
<Input id="backPort" type="number" {...register("backPort")} />
|
||||||
id="backPort"
|
|
||||||
type="number"
|
|
||||||
{...register('backPort')}
|
|
||||||
/>
|
|
||||||
{errors.backPort && (
|
{errors.backPort && (
|
||||||
<p className="text-xs text-destructive">
|
<p className="text-xs text-destructive">
|
||||||
{errors.backPort.message}
|
{errors.backPort.message}
|
||||||
@@ -134,9 +198,12 @@ export function SettingsPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Button type="submit" disabled={!isDirty || updateSettings.isPending}>
|
<Button
|
||||||
|
type="submit"
|
||||||
|
disabled={!isDirty || updateSettings.isPending}
|
||||||
|
>
|
||||||
<Save className="mr-2 h-4 w-4" />
|
<Save className="mr-2 h-4 w-4" />
|
||||||
{updateSettings.isPending ? 'Saving...' : 'Save Settings'}
|
{updateSettings.isPending ? "Saving..." : "Save Settings"}
|
||||||
</Button>
|
</Button>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -145,9 +212,10 @@ export function SettingsPage() {
|
|||||||
{/* Cleanup Section */}
|
{/* Cleanup Section */}
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>Cleanup</CardTitle>
|
<CardTitle>Media Cleanup</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Scan and remove orphan files or database records that no longer have a matching counterpart.
|
Scan and remove orphan files or database records that no longer have
|
||||||
|
a matching counterpart.
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-6">
|
<CardContent className="space-y-6">
|
||||||
@@ -238,6 +306,20 @@ export function SettingsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Missing Directors */}
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Missing Directors</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Populate the director field for entries that don't have one yet,
|
||||||
|
using existing credit data.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<MissingDirectorsSection />
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,20 +1,41 @@
|
|||||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
import { useState, useMemo, useCallback, useEffect } from "react";
|
||||||
import { useLibrary } from '@/hooks/useEntries';
|
import { useLibrary } from "@/hooks/useEntries";
|
||||||
import { useLibraryEntries } from '@/stores/useLibraryStore';
|
import { useLibraryEntries } from "@/stores/useLibraryStore";
|
||||||
import { useDebounce } from '@/hooks/useDebounce';
|
import { useDebounce } from "@/hooks/useDebounce";
|
||||||
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
|
import { EntryLibraryGrid } from "@/components/entries/EntryLibraryGrid";
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from "@/components/ui/input";
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from "@/components/ui/button";
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
import {
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
Popover,
|
||||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
PopoverContent,
|
||||||
import { Search, SlidersHorizontal, ArrowUpDown } from 'lucide-react';
|
PopoverTrigger,
|
||||||
import type { Entry } from '@/types';
|
} from "@/components/ui/popover";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
|
import { Search, SlidersHorizontal, ArrowUpDown, Info } from "lucide-react";
|
||||||
|
import {
|
||||||
|
Tooltip,
|
||||||
|
TooltipContent,
|
||||||
|
TooltipProvider,
|
||||||
|
TooltipTrigger,
|
||||||
|
} from "@/components/ui/tooltip";
|
||||||
|
import type { Entry } from "@/types";
|
||||||
|
|
||||||
type SortField = 'createdAt' | 'date_last_seen' | 'title' | 'release_date' | 'rating';
|
type SortField =
|
||||||
type SortDir = 'asc' | 'desc';
|
| "createdAt"
|
||||||
type TypeFilter = 'all' | 'movies' | 'tv';
|
| "date_last_seen"
|
||||||
|
| "title"
|
||||||
|
| "release_date"
|
||||||
|
| "rating";
|
||||||
|
type SortDir = "asc" | "desc";
|
||||||
|
type TypeFilter = "all" | "movies" | "tv";
|
||||||
|
|
||||||
interface Filters {
|
interface Filters {
|
||||||
genre: string;
|
genre: string;
|
||||||
@@ -24,38 +45,53 @@ interface Filters {
|
|||||||
yearMax: string;
|
yearMax: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const defaultFilters: Filters = { genre: '', ratingMin: '', ratingMax: '', yearMin: '', yearMax: '' };
|
const defaultFilters: Filters = {
|
||||||
|
genre: "",
|
||||||
const sortLabels: Record<SortField, string> = {
|
ratingMin: "",
|
||||||
createdAt: 'Date Added',
|
ratingMax: "",
|
||||||
date_last_seen: 'Last Watched',
|
yearMin: "",
|
||||||
title: 'Title',
|
yearMax: "",
|
||||||
release_date: 'Release Date',
|
|
||||||
rating: 'Rating',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[] {
|
const sortLabels: Record<SortField, string> = {
|
||||||
|
createdAt: "Date Added",
|
||||||
|
date_last_seen: "Last Watched",
|
||||||
|
title: "Title",
|
||||||
|
release_date: "Release Date",
|
||||||
|
rating: "Rating",
|
||||||
|
};
|
||||||
|
|
||||||
|
function sortEntries(
|
||||||
|
entries: Entry[],
|
||||||
|
field: SortField,
|
||||||
|
dir: SortDir,
|
||||||
|
): Entry[] {
|
||||||
return [...entries].sort((a, b) => {
|
return [...entries].sort((a, b) => {
|
||||||
let cmp = 0;
|
let cmp = 0;
|
||||||
switch (field) {
|
switch (field) {
|
||||||
case 'title':
|
case "title":
|
||||||
cmp = a.title.localeCompare(b.title);
|
cmp = a.title.localeCompare(b.title);
|
||||||
break;
|
break;
|
||||||
case 'release_date':
|
case "release_date":
|
||||||
cmp = new Date(a.release_date || '1900').getTime() - new Date(b.release_date || '1900').getTime();
|
cmp =
|
||||||
|
new Date(a.release_date || "1900").getTime() -
|
||||||
|
new Date(b.release_date || "1900").getTime();
|
||||||
break;
|
break;
|
||||||
case 'rating':
|
case "rating":
|
||||||
cmp = (a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0) -
|
cmp =
|
||||||
|
(a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0) -
|
||||||
(b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0);
|
(b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0);
|
||||||
break;
|
break;
|
||||||
case 'date_last_seen':
|
case "date_last_seen":
|
||||||
cmp = new Date(a.date_last_seen || '1900').getTime() - new Date(b.date_last_seen || '1900').getTime();
|
cmp =
|
||||||
|
new Date(a.date_last_seen || "1900").getTime() -
|
||||||
|
new Date(b.date_last_seen || "1900").getTime();
|
||||||
break;
|
break;
|
||||||
case 'createdAt':
|
case "createdAt":
|
||||||
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
return dir === 'desc' ? -cmp : cmp;
|
return dir === "desc" ? -cmp : cmp;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,15 +99,18 @@ const PAGE_SIZE = 28;
|
|||||||
|
|
||||||
export function WatchlistPage() {
|
export function WatchlistPage() {
|
||||||
const { isLoading } = useLibrary();
|
const { isLoading } = useLibrary();
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState("");
|
||||||
const debouncedSearch = useDebounce(search, 300);
|
const debouncedSearch = useDebounce(search, 300);
|
||||||
const [sortField, setSortField] = useState<SortField>('createdAt');
|
const [sortField, setSortField] = useState<SortField>("createdAt");
|
||||||
const [sortDir, setSortDir] = useState<SortDir>('desc');
|
const [sortDir, setSortDir] = useState<SortDir>("desc");
|
||||||
const [filters, setFilters] = useState<Filters>(defaultFilters);
|
const [filters, setFilters] = useState<Filters>(defaultFilters);
|
||||||
const [typeFilter, setTypeFilter] = useState<TypeFilter>('all');
|
const [typeFilter, setTypeFilter] = useState<TypeFilter>("all");
|
||||||
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
|
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
|
||||||
const allEntries = useLibraryEntries();
|
const allEntries = useLibraryEntries();
|
||||||
const watchlist = useMemo(() => allEntries.filter((e) => e.watchlist), [allEntries]);
|
const watchlist = useMemo(
|
||||||
|
() => allEntries.filter((e) => e.watchlist),
|
||||||
|
[allEntries],
|
||||||
|
);
|
||||||
|
|
||||||
const allGenres = useMemo(() => {
|
const allGenres = useMemo(() => {
|
||||||
const set = new Set<string>();
|
const set = new Set<string>();
|
||||||
@@ -79,40 +118,69 @@ export function WatchlistPage() {
|
|||||||
return Array.from(set).sort();
|
return Array.from(set).sort();
|
||||||
}, [watchlist]);
|
}, [watchlist]);
|
||||||
|
|
||||||
const hasActiveFilters = filters.genre || filters.ratingMin || filters.ratingMax || filters.yearMin || filters.yearMax;
|
const hasActiveFilters =
|
||||||
|
filters.genre ||
|
||||||
|
filters.ratingMin ||
|
||||||
|
filters.ratingMax ||
|
||||||
|
filters.yearMin ||
|
||||||
|
filters.yearMax;
|
||||||
|
|
||||||
const filtered = useMemo(() => {
|
const filtered = useMemo(() => {
|
||||||
let result = watchlist;
|
let result = watchlist;
|
||||||
|
|
||||||
if (typeFilter === 'movies') {
|
if (typeFilter === "movies") {
|
||||||
result = result.filter((e) => !e.is_tvseries);
|
result = result.filter((e) => !e.is_tvseries);
|
||||||
} else if (typeFilter === 'tv') {
|
} else if (typeFilter === "tv") {
|
||||||
result = result.filter((e) => e.is_tvseries);
|
result = result.filter((e) => e.is_tvseries);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (debouncedSearch) {
|
if (debouncedSearch) {
|
||||||
const q = debouncedSearch.toLowerCase();
|
const q = debouncedSearch.toLowerCase();
|
||||||
|
const directorPrefix = "@director:";
|
||||||
|
if (q.startsWith(directorPrefix)) {
|
||||||
|
const dirQuery = q.slice(directorPrefix.length).trim();
|
||||||
|
if (dirQuery) {
|
||||||
|
result = result.filter(
|
||||||
|
(e) => e.director && e.director.toLowerCase().includes(dirQuery),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
result = result.filter((e) => e.title.toLowerCase().includes(q));
|
result = result.filter((e) => e.title.toLowerCase().includes(q));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (filters.genre) {
|
if (filters.genre) {
|
||||||
result = result.filter((e) => e.genres?.some((g) => g.name === filters.genre));
|
result = result.filter((e) =>
|
||||||
|
e.genres?.some((g) => g.name === filters.genre),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (filters.ratingMin) {
|
if (filters.ratingMin) {
|
||||||
const min = parseFloat(filters.ratingMin);
|
const min = parseFloat(filters.ratingMin);
|
||||||
result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) >= min);
|
result = result.filter(
|
||||||
|
(e) =>
|
||||||
|
(e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) >=
|
||||||
|
min,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (filters.ratingMax) {
|
if (filters.ratingMax) {
|
||||||
const max = parseFloat(filters.ratingMax);
|
const max = parseFloat(filters.ratingMax);
|
||||||
result = result.filter((e) => (e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) <= max);
|
result = result.filter(
|
||||||
|
(e) =>
|
||||||
|
(e.entryRatings?.user_rating || e.entryRatings?.tmdb_rating || 0) <=
|
||||||
|
max,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (filters.yearMin) {
|
if (filters.yearMin) {
|
||||||
const min = parseInt(filters.yearMin);
|
const min = parseInt(filters.yearMin);
|
||||||
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() >= min);
|
result = result.filter(
|
||||||
|
(e) => e.release_date && new Date(e.release_date).getFullYear() >= min,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (filters.yearMax) {
|
if (filters.yearMax) {
|
||||||
const max = parseInt(filters.yearMax);
|
const max = parseInt(filters.yearMax);
|
||||||
result = result.filter((e) => e.release_date && new Date(e.release_date).getFullYear() <= max);
|
result = result.filter(
|
||||||
|
(e) => e.release_date && new Date(e.release_date).getFullYear() <= max,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return sortEntries(result, sortField, sortDir);
|
return sortEntries(result, sortField, sortDir);
|
||||||
@@ -125,7 +193,7 @@ export function WatchlistPage() {
|
|||||||
|
|
||||||
const paginatedEntries = useMemo(
|
const paginatedEntries = useMemo(
|
||||||
() => filtered.slice(0, visibleCount),
|
() => filtered.slice(0, visibleCount),
|
||||||
[filtered, visibleCount]
|
[filtered, visibleCount],
|
||||||
);
|
);
|
||||||
const hasMore = visibleCount < filtered.length;
|
const hasMore = visibleCount < filtered.length;
|
||||||
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
|
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
|
||||||
@@ -150,18 +218,56 @@ export function WatchlistPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Search tips */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger>
|
||||||
|
<Info className="h-4 w-4 text-muted-foreground hover:text-foreground cursor-pointer shrink-0" />
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent
|
||||||
|
side="bottom"
|
||||||
|
className="w-56 text-xs"
|
||||||
|
align="start"
|
||||||
|
>
|
||||||
|
<p className="font-semibold mb-1.5">Search prefixes</p>
|
||||||
|
<p className="mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@director:name
|
||||||
|
</code>{" "}
|
||||||
|
— by director
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@country:name
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@year:year
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
{/* Sort popover */}
|
{/* Sort popover */}
|
||||||
<Popover>
|
<Popover>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button variant="outline" size="icon" className="h-9 w-9 shrink-0 relative">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="h-9 w-9 shrink-0 relative"
|
||||||
|
>
|
||||||
<ArrowUpDown className="h-4 w-4" />
|
<ArrowUpDown className="h-4 w-4" />
|
||||||
{sortField !== 'createdAt' && (
|
{sortField !== "createdAt" && (
|
||||||
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
||||||
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Sort by</p>
|
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Sort by
|
||||||
|
</p>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{Object.entries(sortLabels).map(([value, label]) => (
|
{Object.entries(sortLabels).map(([value, label]) => (
|
||||||
<button
|
<button
|
||||||
@@ -169,8 +275,8 @@ export function WatchlistPage() {
|
|||||||
onClick={() => setSortField(value as SortField)}
|
onClick={() => setSortField(value as SortField)}
|
||||||
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
||||||
sortField === value
|
sortField === value
|
||||||
? 'bg-accent text-accent-foreground font-medium'
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
: 'hover:bg-accent/50'
|
: "hover:bg-accent/50"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
@@ -178,8 +284,22 @@ export function WatchlistPage() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-1 pt-1 border-t border-border">
|
<div className="flex gap-1 pt-1 border-t border-border">
|
||||||
<Button variant={sortDir === 'desc' ? 'default' : 'outline'} size="sm" className="flex-1 h-8 text-xs" onClick={() => setSortDir('desc')}>↓ Desc</Button>
|
<Button
|
||||||
<Button variant={sortDir === 'asc' ? 'default' : 'outline'} size="sm" className="flex-1 h-8 text-xs" onClick={() => setSortDir('asc')}>↑ Asc</Button>
|
variant={sortDir === "desc" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
className="flex-1 h-8 text-xs"
|
||||||
|
onClick={() => setSortDir("desc")}
|
||||||
|
>
|
||||||
|
↓ Desc
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={sortDir === "asc" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
className="flex-1 h-8 text-xs"
|
||||||
|
onClick={() => setSortDir("asc")}
|
||||||
|
>
|
||||||
|
↑ Asc
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@@ -187,7 +307,11 @@ export function WatchlistPage() {
|
|||||||
{/* Filter popover */}
|
{/* Filter popover */}
|
||||||
<Popover>
|
<Popover>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
<Button variant="outline" size="icon" className="h-9 w-9 shrink-0 relative">
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
className="h-9 w-9 shrink-0 relative"
|
||||||
|
>
|
||||||
<SlidersHorizontal className="h-4 w-4" />
|
<SlidersHorizontal className="h-4 w-4" />
|
||||||
{hasActiveFilters && (
|
{hasActiveFilters && (
|
||||||
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
<span className="absolute -top-1 -right-1 h-2 w-2 rounded-full bg-primary" />
|
||||||
@@ -197,32 +321,92 @@ export function WatchlistPage() {
|
|||||||
<PopoverContent className="w-72 space-y-4" align="end">
|
<PopoverContent className="w-72 space-y-4" align="end">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Genre</label>
|
<label className="text-sm font-medium">Genre</label>
|
||||||
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : v }))}>
|
<Select
|
||||||
<SelectTrigger className="h-9"><SelectValue placeholder="All genres" /></SelectTrigger>
|
value={filters.genre}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
setFilters((f) => ({ ...f, genre: v === "_all" ? "" : v }))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="h-9">
|
||||||
|
<SelectValue placeholder="All genres" />
|
||||||
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="_all">All genres</SelectItem>
|
<SelectItem value="_all">All genres</SelectItem>
|
||||||
{allGenres.map((g) => <SelectItem key={g} value={g}>{g}</SelectItem>)}
|
{allGenres.map((g) => (
|
||||||
|
<SelectItem key={g} value={g}>
|
||||||
|
{g}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Rating Range</label>
|
<label className="text-sm font-medium">Rating Range</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="Min" min={0} max={10} step={0.1} value={filters.ratingMin} onChange={(e) => setFilters((f) => ({ ...f, ratingMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Min"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={0.1}
|
||||||
|
value={filters.ratingMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, ratingMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="Max" min={0} max={10} step={0.1} value={filters.ratingMax} onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Max"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={0.1}
|
||||||
|
value={filters.ratingMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, ratingMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Year Range</label>
|
<label className="text-sm font-medium">Year Range</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="From" min={1950} max={2100} value={filters.yearMin} onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="From"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="To" min={1950} max={2100} value={filters.yearMax} onChange={(e) => setFilters((f) => ({ ...f, yearMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="To"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{hasActiveFilters && (
|
{hasActiveFilters && (
|
||||||
<Button variant="ghost" size="sm" className="w-full" onClick={clearFilters}>Clear Filters</Button>
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-full"
|
||||||
|
onClick={clearFilters}
|
||||||
|
>
|
||||||
|
Clear Filters
|
||||||
|
</Button>
|
||||||
)}
|
)}
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@@ -230,7 +414,10 @@ export function WatchlistPage() {
|
|||||||
|
|
||||||
{/* Row 2: type filter tabs */}
|
{/* Row 2: type filter tabs */}
|
||||||
<div className="overflow-x-auto pb-1">
|
<div className="overflow-x-auto pb-1">
|
||||||
<Tabs value={typeFilter} onValueChange={(v) => setTypeFilter(v as TypeFilter)}>
|
<Tabs
|
||||||
|
value={typeFilter}
|
||||||
|
onValueChange={(v) => setTypeFilter(v as TypeFilter)}
|
||||||
|
>
|
||||||
<TabsList className="w-max">
|
<TabsList className="w-max">
|
||||||
<TabsTrigger value="all">All</TabsTrigger>
|
<TabsTrigger value="all">All</TabsTrigger>
|
||||||
<TabsTrigger value="movies">Movies</TabsTrigger>
|
<TabsTrigger value="movies">Movies</TabsTrigger>
|
||||||
@@ -253,6 +440,34 @@ export function WatchlistPage() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Search tips */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger>
|
||||||
|
<Info className="h-4 w-4 text-muted-foreground hover:text-foreground cursor-pointer shrink-0" />
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent side="bottom" className="w-56 text-xs" align="start">
|
||||||
|
<p className="font-semibold mb-1.5">Search prefixes</p>
|
||||||
|
<p className="mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@director:name
|
||||||
|
</code>{" "}
|
||||||
|
— by director
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground mb-0.5">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@country:name
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
<code className="bg-accent px-1 rounded text-[11px]">
|
||||||
|
@year:year
|
||||||
|
</code>{" "}
|
||||||
|
— coming soon
|
||||||
|
</p>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
<div className="flex-1" />
|
<div className="flex-1" />
|
||||||
|
|
||||||
{/* Sort */}
|
{/* Sort */}
|
||||||
@@ -261,11 +476,15 @@ export function WatchlistPage() {
|
|||||||
<Button variant="outline" size="sm" className="h-9 gap-1.5">
|
<Button variant="outline" size="sm" className="h-9 gap-1.5">
|
||||||
<ArrowUpDown className="h-4 w-4" />
|
<ArrowUpDown className="h-4 w-4" />
|
||||||
{sortLabels[sortField]}
|
{sortLabels[sortField]}
|
||||||
<span className="text-xs opacity-60">{sortDir === 'desc' ? '↓' : '↑'}</span>
|
<span className="text-xs opacity-60">
|
||||||
|
{sortDir === "desc" ? "↓" : "↑"}
|
||||||
|
</span>
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
<PopoverContent className="w-52 space-y-3 p-3" align="end">
|
||||||
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">Sort by</p>
|
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Sort by
|
||||||
|
</p>
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
{Object.entries(sortLabels).map(([value, label]) => (
|
{Object.entries(sortLabels).map(([value, label]) => (
|
||||||
<button
|
<button
|
||||||
@@ -273,8 +492,8 @@ export function WatchlistPage() {
|
|||||||
onClick={() => setSortField(value as SortField)}
|
onClick={() => setSortField(value as SortField)}
|
||||||
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
|
||||||
sortField === value
|
sortField === value
|
||||||
? 'bg-accent text-accent-foreground font-medium'
|
? "bg-accent text-accent-foreground font-medium"
|
||||||
: 'hover:bg-accent/50'
|
: "hover:bg-accent/50"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
@@ -282,8 +501,22 @@ export function WatchlistPage() {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-1 pt-1 border-t border-border">
|
<div className="flex gap-1 pt-1 border-t border-border">
|
||||||
<Button variant={sortDir === 'desc' ? 'default' : 'outline'} size="sm" className="flex-1 h-8 text-xs" onClick={() => setSortDir('desc')}>↓ Desc</Button>
|
<Button
|
||||||
<Button variant={sortDir === 'asc' ? 'default' : 'outline'} size="sm" className="flex-1 h-8 text-xs" onClick={() => setSortDir('asc')}>↑ Asc</Button>
|
variant={sortDir === "desc" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
className="flex-1 h-8 text-xs"
|
||||||
|
onClick={() => setSortDir("desc")}
|
||||||
|
>
|
||||||
|
↓ Desc
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={sortDir === "asc" ? "default" : "outline"}
|
||||||
|
size="sm"
|
||||||
|
className="flex-1 h-8 text-xs"
|
||||||
|
onClick={() => setSortDir("asc")}
|
||||||
|
>
|
||||||
|
↑ Asc
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@@ -294,40 +527,103 @@ export function WatchlistPage() {
|
|||||||
<Button variant="outline" size="sm" className="h-9 gap-1">
|
<Button variant="outline" size="sm" className="h-9 gap-1">
|
||||||
<SlidersHorizontal className="h-4 w-4" />
|
<SlidersHorizontal className="h-4 w-4" />
|
||||||
Filter
|
Filter
|
||||||
{hasActiveFilters && <Badge variant="secondary" className="ml-1 h-5 px-1 text-[10px]">Active</Badge>}
|
{hasActiveFilters && (
|
||||||
|
<Badge
|
||||||
|
variant="secondary"
|
||||||
|
className="ml-1 h-5 px-1 text-[10px]"
|
||||||
|
>
|
||||||
|
Active
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent className="w-72 space-y-4" align="end">
|
<PopoverContent className="w-72 space-y-4" align="end">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Genre</label>
|
<label className="text-sm font-medium">Genre</label>
|
||||||
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : v }))}>
|
<Select
|
||||||
<SelectTrigger className="h-9"><SelectValue placeholder="All genres" /></SelectTrigger>
|
value={filters.genre}
|
||||||
|
onValueChange={(v) =>
|
||||||
|
setFilters((f) => ({ ...f, genre: v === "_all" ? "" : v }))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="h-9">
|
||||||
|
<SelectValue placeholder="All genres" />
|
||||||
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="_all">All genres</SelectItem>
|
<SelectItem value="_all">All genres</SelectItem>
|
||||||
{allGenres.map((g) => <SelectItem key={g} value={g}>{g}</SelectItem>)}
|
{allGenres.map((g) => (
|
||||||
|
<SelectItem key={g} value={g}>
|
||||||
|
{g}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Rating Range</label>
|
<label className="text-sm font-medium">Rating Range</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="Min" min={0} max={10} step={0.1} value={filters.ratingMin} onChange={(e) => setFilters((f) => ({ ...f, ratingMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Min"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={0.1}
|
||||||
|
value={filters.ratingMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, ratingMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="Max" min={0} max={10} step={0.1} value={filters.ratingMax} onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="Max"
|
||||||
|
min={0}
|
||||||
|
max={10}
|
||||||
|
step={0.1}
|
||||||
|
value={filters.ratingMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, ratingMax: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Year Range</label>
|
<label className="text-sm font-medium">Year Range</label>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Input type="number" placeholder="From" min={1950} max={2100} value={filters.yearMin} onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))} className="h-9" />
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="From"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMin}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, yearMin: e.target.value }))
|
||||||
|
}
|
||||||
|
className="h-9"
|
||||||
|
/>
|
||||||
<span className="text-muted-foreground">–</span>
|
<span className="text-muted-foreground">–</span>
|
||||||
<Input type="number" placeholder="To" min={1950} max={2100} value={filters.yearMax} onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))}
|
<Input
|
||||||
|
type="number"
|
||||||
|
placeholder="To"
|
||||||
|
min={1950}
|
||||||
|
max={2100}
|
||||||
|
value={filters.yearMax}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilters((f) => ({ ...f, ratingMax: e.target.value }))
|
||||||
|
}
|
||||||
className="h-9"
|
className="h-9"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{hasActiveFilters && (
|
{hasActiveFilters && (
|
||||||
<Button variant="ghost" size="sm" className="w-full" onClick={clearFilters}>
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="w-full"
|
||||||
|
onClick={clearFilters}
|
||||||
|
>
|
||||||
Clear Filters
|
Clear Filters
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
@@ -335,7 +631,10 @@ export function WatchlistPage() {
|
|||||||
</Popover>
|
</Popover>
|
||||||
|
|
||||||
{/* Type filter */}
|
{/* Type filter */}
|
||||||
<Tabs value={typeFilter} onValueChange={(v) => setTypeFilter(v as TypeFilter)}>
|
<Tabs
|
||||||
|
value={typeFilter}
|
||||||
|
onValueChange={(v) => setTypeFilter(v as TypeFilter)}
|
||||||
|
>
|
||||||
<TabsList>
|
<TabsList>
|
||||||
<TabsTrigger value="all">All</TabsTrigger>
|
<TabsTrigger value="all">All</TabsTrigger>
|
||||||
<TabsTrigger value="movies">Movies</TabsTrigger>
|
<TabsTrigger value="movies">Movies</TabsTrigger>
|
||||||
@@ -344,7 +643,12 @@ export function WatchlistPage() {
|
|||||||
</Tabs>
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<EntryLibraryGrid entries={paginatedEntries} isLoading={isLoading} hasMore={hasMore} onLoadMore={loadMore} />
|
<EntryLibraryGrid
|
||||||
|
entries={paginatedEntries}
|
||||||
|
isLoading={isLoading}
|
||||||
|
hasMore={hasMore}
|
||||||
|
onLoadMore={loadMore}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -15,9 +15,9 @@ export interface EntryRatings {
|
|||||||
|
|
||||||
export interface Media {
|
export interface Media {
|
||||||
id: number;
|
id: number;
|
||||||
mediaable: 'entry' | 'people' | 'collection' | 'season' | 'episode';
|
mediaable: "entry" | "people" | "collection" | "season" | "episode";
|
||||||
mediaable_id: number;
|
mediaable_id: number;
|
||||||
type: 'poster' | 'backdrop' | 'logo' | 'still' | 'profile';
|
type: "poster" | "backdrop" | "logo" | "still" | "profile";
|
||||||
path: string;
|
path: string;
|
||||||
is_local: boolean;
|
is_local: boolean;
|
||||||
is_selected: boolean;
|
is_selected: boolean;
|
||||||
@@ -53,6 +53,8 @@ export interface Entry {
|
|||||||
medias?: Media[];
|
medias?: Media[];
|
||||||
genres?: Genre[];
|
genres?: Genre[];
|
||||||
credits?: Credit[];
|
credits?: Credit[];
|
||||||
|
/** Computed — director name string for search (not persisted in DB) */
|
||||||
|
director?: string | null;
|
||||||
seasons?: Season[];
|
seasons?: Season[];
|
||||||
entrySeens?: EntrySeen[];
|
entrySeens?: EntrySeen[];
|
||||||
episodeSeens?: EpisodeSeen[];
|
episodeSeens?: EpisodeSeen[];
|
||||||
@@ -102,7 +104,7 @@ export interface Episode {
|
|||||||
season?: Season;
|
season?: Season;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SeenAccuracy = 'EXACT' | 'ESTIMATED' | 'UNKNOWN';
|
export type SeenAccuracy = "EXACT" | "ESTIMATED" | "UNKNOWN";
|
||||||
|
|
||||||
export interface EntrySeen {
|
export interface EntrySeen {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -166,7 +168,7 @@ export interface Credit {
|
|||||||
entry_id: number;
|
entry_id: number;
|
||||||
people_id: number;
|
people_id: number;
|
||||||
character: string | null; // might contain multiple separated by ;
|
character: string | null; // might contain multiple separated by ;
|
||||||
cast_type: 'cast' | 'crew';
|
cast_type: "cast" | "crew";
|
||||||
department: string | null;
|
department: string | null;
|
||||||
job: string | null;
|
job: string | null;
|
||||||
episode_count?: number | null;
|
episode_count?: number | null;
|
||||||
@@ -248,7 +250,7 @@ export interface TmdbPaginatedResponse<T> {
|
|||||||
|
|
||||||
export interface TmdbPreviewCredit {
|
export interface TmdbPreviewCredit {
|
||||||
id: string | number;
|
id: string | number;
|
||||||
cast_type: 'cast';
|
cast_type: "cast";
|
||||||
character: string | null;
|
character: string | null;
|
||||||
people_id: number;
|
people_id: number;
|
||||||
people: {
|
people: {
|
||||||
|
|||||||
Reference in new issue
Block a user