Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4d88747649 | ||
|
|
1aa0a84f4d | ||
|
|
e660b1ec87 | ||
|
|
63aca7e7b8 | ||
|
|
ec9498cac0 | ||
|
|
0a79ee9768 | ||
|
|
c6a838a91c | ||
|
|
d12d7cb627 | ||
|
|
c09f70054c | ||
|
|
ea91c6011a |
No files matched your search
@@ -0,0 +1,62 @@
|
||||
const Entry = require("../models/Entry");
|
||||
const Collection = require("../models/Collection");
|
||||
const { Op } = require("sequelize");
|
||||
|
||||
class HomepageIntegrationController {
|
||||
constructor() {
|
||||
if (!HomepageIntegrationController.instance) {
|
||||
HomepageIntegrationController.instance = this;
|
||||
}
|
||||
return HomepageIntegrationController.instance;
|
||||
}
|
||||
|
||||
async getStats(req, res) {
|
||||
try {
|
||||
const notSeries = { is_tvseries: { [Op.or]: [false, null] } };
|
||||
const isSeries = { is_tvseries: true };
|
||||
|
||||
const [
|
||||
totalEntries,
|
||||
library,
|
||||
libraryMovies,
|
||||
librarySeries,
|
||||
watchlist,
|
||||
watchlistMovies,
|
||||
watchlistSeries,
|
||||
collections,
|
||||
favorits,
|
||||
] = await Promise.all([
|
||||
Entry.count(),
|
||||
Entry.count({ where: { watchlist: { [Op.or]: [false, null] } } }),
|
||||
Entry.count({
|
||||
where: { watchlist: { [Op.or]: [false, null] }, ...notSeries },
|
||||
}),
|
||||
Entry.count({
|
||||
where: { watchlist: { [Op.or]: [false, null] }, ...isSeries },
|
||||
}),
|
||||
Entry.count({ where: { watchlist: true } }),
|
||||
Entry.count({ where: { watchlist: true, ...notSeries } }),
|
||||
Entry.count({ where: { watchlist: true, ...isSeries } }),
|
||||
Collection.count(),
|
||||
Entry.count({ where: { favorit: true } }),
|
||||
]);
|
||||
|
||||
return res.status(200).json({
|
||||
totalEntries,
|
||||
library,
|
||||
libraryMovies,
|
||||
librarySeries,
|
||||
watchlist,
|
||||
watchlistMovies,
|
||||
watchlistSeries,
|
||||
collections,
|
||||
favorits,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Homepage integration error:", error);
|
||||
return res.status(500).json({ error: "Failed to fetch library stats" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new HomepageIntegrationController();
|
||||
@@ -1,6 +1,9 @@
|
||||
const Episode = require("../models/Episode");
|
||||
const EpisodeSeen = require("../models/EpisodeSeen");
|
||||
const Season = require("../models/Season");
|
||||
const Entry = require("../models/Entry");
|
||||
const EntryId = require("../models/EntryId");
|
||||
const { fetchSeasonData } = require("../services/tmdbService");
|
||||
|
||||
class SeasonController {
|
||||
constructor() {
|
||||
@@ -88,6 +91,48 @@ class SeasonController {
|
||||
}
|
||||
}
|
||||
|
||||
async refreshSeason(req, res) {
|
||||
try {
|
||||
const season = await Season.findByPk(req.params.id, {
|
||||
include: [
|
||||
{
|
||||
model: Entry,
|
||||
as: "entry",
|
||||
include: [{ model: EntryId, as: "entryId" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
if (!season) {
|
||||
return res.status(404).send("Season not found");
|
||||
}
|
||||
|
||||
const tmdbTvId = season.entry?.entryId?.tmdb_id;
|
||||
if (!tmdbTvId) {
|
||||
return res.status(400).send("Entry has no TMDB ID");
|
||||
}
|
||||
|
||||
const seasonData = await fetchSeasonData(tmdbTvId, season.season_number);
|
||||
if (!seasonData) {
|
||||
return res.status(500).send("Couldn't fetch data from TMDB");
|
||||
}
|
||||
|
||||
await season.update({
|
||||
name: seasonData.name,
|
||||
overview: seasonData.overview,
|
||||
episode_count: seasonData.episodes?.length ?? season.episode_count,
|
||||
air_date: seasonData.air_date,
|
||||
tmdb_rating: seasonData.vote_average,
|
||||
poster_path: seasonData.poster_path,
|
||||
});
|
||||
|
||||
const refreshedSeason = await Season.findByPk(req.params.id);
|
||||
res.send(refreshedSeason);
|
||||
} catch (error) {
|
||||
res.status(500).send(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteSeason(req, res) {
|
||||
try {
|
||||
const deleted = await Season.destroy({
|
||||
|
||||
@@ -1,6 +1,45 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
const configService = require("../services/configService");
|
||||
|
||||
function validateToken(tokenValue) {
|
||||
const settings = configService.getSettings();
|
||||
const jwtSecret = settings.jwtSecret || "showy-default-secret";
|
||||
|
||||
// 1. Check dedicated dashboardToken
|
||||
if (settings.dashboardToken && settings.dashboardToken === tokenValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Check named tokens (supports expiration)
|
||||
const namedTokens = configService.getNamedTokens();
|
||||
if (namedTokens.some((t) => t.value === tokenValue)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. Try JWT
|
||||
try {
|
||||
jwt.verify(tokenValue, jwtSecret);
|
||||
return true;
|
||||
} catch {
|
||||
// not a valid JWT
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractToken(req) {
|
||||
// Authorization: Bearer <token>
|
||||
const auth = req.headers.authorization;
|
||||
if (auth && auth.startsWith("Bearer ")) {
|
||||
return auth.slice(7);
|
||||
}
|
||||
// ?token= query parameter
|
||||
if (req.query.token) {
|
||||
return req.query.token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function authMiddleware(req, res, next) {
|
||||
// Skip auth for login/verify/media endpoints
|
||||
if (
|
||||
@@ -11,20 +50,16 @@ function authMiddleware(req, res, next) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const auth = req.headers.authorization;
|
||||
if (!auth || !auth.startsWith("Bearer ")) {
|
||||
const tokenValue = extractToken(req);
|
||||
if (!tokenValue) {
|
||||
return res.status(401).json({ error: "Authentication required" });
|
||||
}
|
||||
|
||||
const settings = configService.getSettings();
|
||||
const jwtSecret = settings.jwtSecret || "showy-default-secret";
|
||||
|
||||
try {
|
||||
jwt.verify(auth.slice(7), jwtSecret);
|
||||
next();
|
||||
} catch {
|
||||
if (!validateToken(tokenValue)) {
|
||||
return res.status(401).json({ error: "Invalid or expired token" });
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = authMiddleware;
|
||||
@@ -0,0 +1,8 @@
|
||||
const express = require("express");
|
||||
const homepageIntegrationRouter = express.Router();
|
||||
|
||||
const homepageIntegrationController = require("../controllers/homepageIntegrationController");
|
||||
|
||||
homepageIntegrationRouter.get("/", homepageIntegrationController.getStats);
|
||||
|
||||
module.exports = homepageIntegrationRouter;
|
||||
+35
-33
@@ -1,39 +1,41 @@
|
||||
const express = require('express');
|
||||
const collectionRouter = require('./collection.routes');
|
||||
const entrySeenRouter = require('./entry-seen.routes');
|
||||
const entryRouter = require('./entry.routes');
|
||||
const seasonRouter = require('./season.routes');
|
||||
const episodeSeenRouter = require('./episode-seen.routes');
|
||||
const settingsRouter = require('./settings.routes');
|
||||
const maintenanceRouter = require('./maintenance.routes');
|
||||
const statisticsRouter = require('./statistics.routes');
|
||||
const mediaRouter = require('./media.routes');
|
||||
const episodeRouter = require('./episode.routes');
|
||||
const pingRouter = require('./ping.routes');
|
||||
const importRouter = require('./import.routes');
|
||||
const peopleRouter = require('./people.routes');
|
||||
const aiQueryRouter = require('./ai-query.routes');
|
||||
const authRouter = require('./auth.routes');
|
||||
const watchBuddyRouter = require('./watch-buddy.routes');
|
||||
const express = require("express");
|
||||
const collectionRouter = require("./collection.routes");
|
||||
const entrySeenRouter = require("./entry-seen.routes");
|
||||
const entryRouter = require("./entry.routes");
|
||||
const seasonRouter = require("./season.routes");
|
||||
const episodeSeenRouter = require("./episode-seen.routes");
|
||||
const settingsRouter = require("./settings.routes");
|
||||
const maintenanceRouter = require("./maintenance.routes");
|
||||
const statisticsRouter = require("./statistics.routes");
|
||||
const mediaRouter = require("./media.routes");
|
||||
const episodeRouter = require("./episode.routes");
|
||||
const pingRouter = require("./ping.routes");
|
||||
const importRouter = require("./import.routes");
|
||||
const peopleRouter = require("./people.routes");
|
||||
const aiQueryRouter = require("./ai-query.routes");
|
||||
const authRouter = require("./auth.routes");
|
||||
const watchBuddyRouter = require("./watch-buddy.routes");
|
||||
const homepageIntegrationRouter = require("./homepage-integration.routes");
|
||||
|
||||
const router = express.Router();
|
||||
router.use('/auth', authRouter);
|
||||
router.use('/watch-buddies', watchBuddyRouter);
|
||||
router.use('/media', mediaRouter);
|
||||
router.use('/entries', entryRouter);
|
||||
router.use('/collections', collectionRouter);
|
||||
router.use('/entry-seen', entrySeenRouter);
|
||||
router.use("/auth", authRouter);
|
||||
router.use("/watch-buddies", watchBuddyRouter);
|
||||
router.use("/media", mediaRouter);
|
||||
router.use("/entries", entryRouter);
|
||||
router.use("/collections", collectionRouter);
|
||||
router.use("/entry-seen", entrySeenRouter);
|
||||
|
||||
router.use('/seasons', seasonRouter);
|
||||
router.use('/episodes', episodeRouter);
|
||||
router.use('/episode-seen', episodeSeenRouter);
|
||||
router.use("/seasons", seasonRouter);
|
||||
router.use("/episodes", episodeRouter);
|
||||
router.use("/episode-seen", episodeSeenRouter);
|
||||
|
||||
router.use('/import', importRouter);
|
||||
router.use('/statistics', statisticsRouter);
|
||||
router.use('/settings', settingsRouter);
|
||||
router.use('/maintenance', maintenanceRouter);
|
||||
router.use('/ping', pingRouter);
|
||||
router.use('/people', peopleRouter);
|
||||
router.use('/ai-query', aiQueryRouter);
|
||||
router.use("/import", importRouter);
|
||||
router.use("/statistics", statisticsRouter);
|
||||
router.use("/settings", settingsRouter);
|
||||
router.use("/maintenance", maintenanceRouter);
|
||||
router.use("/ping", pingRouter);
|
||||
router.use("/people", peopleRouter);
|
||||
router.use("/ai-query", aiQueryRouter);
|
||||
router.use("/homepage-integration", homepageIntegrationRouter);
|
||||
|
||||
module.exports = router;
|
||||
@@ -19,6 +19,9 @@ seasonRouter.get("/:id/episodes", seasonController.getSeasonEpisodes);
|
||||
// * PUT - Update a season
|
||||
seasonRouter.put("/:id", seasonController.updateSeason);
|
||||
|
||||
// * PUT - Refresh a season from TMDB
|
||||
seasonRouter.put("/:id/refresh", seasonController.refreshSeason);
|
||||
|
||||
// * DELETE - Delete a season
|
||||
seasonRouter.delete("/:id", seasonController.deleteSeason);
|
||||
|
||||
|
||||
+1
-1
@@ -51,7 +51,7 @@ app.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
// ? other api routes
|
||||
// ? API routes
|
||||
app.use("/api/v1", authMiddleware, routes);
|
||||
|
||||
// ? Error handling middleware
|
||||
|
||||
@@ -138,6 +138,19 @@ class ConfigService {
|
||||
getTmdbApiKey() {
|
||||
return this.settings.tmdbApiKey;
|
||||
}
|
||||
|
||||
getNamedTokens() {
|
||||
const tokens = this.settings.namedTokens || [];
|
||||
const now = new Date();
|
||||
return tokens.filter((token) => {
|
||||
if (!token.value) return false;
|
||||
if (token.endDate) {
|
||||
const end = new Date(token.endDate);
|
||||
if (end < now) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// const instance = new ConfigService();
|
||||
|
||||
@@ -513,10 +513,12 @@ class EntryManager {
|
||||
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",
|
||||
);
|
||||
// Set director from processed credits (handles both movie & TV aggregate format)
|
||||
const directorCredit = allCredits.find((c) => {
|
||||
if (c.cast_type !== "crew") return false;
|
||||
const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job];
|
||||
return jobs.includes("Director");
|
||||
});
|
||||
if (directorCredit) {
|
||||
oldEntry.director = directorCredit.name || null;
|
||||
await oldEntry.save();
|
||||
|
||||
@@ -293,6 +293,7 @@ class EntryService {
|
||||
|
||||
const tmdbIds = [...new Set(allCredits.map((c) => c.id))];
|
||||
|
||||
// — FETCH EXISTING PEOPLE —
|
||||
const existingPeopleList = await People.findAll({
|
||||
where: { tmdb_id: tmdbIds },
|
||||
});
|
||||
@@ -300,6 +301,7 @@ class EntryService {
|
||||
existingPeopleList.map((p) => [p.tmdb_id, p]),
|
||||
);
|
||||
|
||||
// — CREATE NEW PEOPLE —
|
||||
const newPeopleData = tmdbIds
|
||||
.filter((id) => !existingPeopleMap[id])
|
||||
.map((id) => {
|
||||
@@ -316,36 +318,80 @@ class EntryService {
|
||||
};
|
||||
});
|
||||
|
||||
if (newPeopleData.length) {
|
||||
console.log(`[PEOPLE] Adding ${newPeopleData.length} new people...`);
|
||||
}
|
||||
|
||||
const createdPeople = await People.bulkCreate(newPeopleData);
|
||||
|
||||
for (const person of createdPeople) {
|
||||
console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`);
|
||||
existingPeopleMap[person.tmdb_id] = person;
|
||||
}
|
||||
|
||||
const newCredits = allCredits.map((c) => {
|
||||
// — BUILD NEW CREDITS —
|
||||
const newCredits = [];
|
||||
|
||||
for (const c of allCredits) {
|
||||
const person = existingPeopleMap[c.id];
|
||||
return {
|
||||
if (!person) continue;
|
||||
|
||||
// Detect TV aggregate format (roles/jobs arrays) vs movie flat format.
|
||||
const character =
|
||||
c.cast_type === "cast"
|
||||
? Array.isArray(c.roles)
|
||||
? c.roles
|
||||
.map((r) => r.character)
|
||||
.filter(Boolean)
|
||||
.join("; ") || null
|
||||
: c.character || null
|
||||
: null;
|
||||
|
||||
const job =
|
||||
c.cast_type === "crew"
|
||||
? Array.isArray(c.jobs)
|
||||
? c.jobs
|
||||
.map((j) => j.job)
|
||||
.filter(Boolean)
|
||||
.join("; ") || null
|
||||
: c.job || null
|
||||
: null;
|
||||
|
||||
const tmdbCreditId = Array.isArray(c.roles)
|
||||
? c.roles?.[0]?.credit_id
|
||||
: Array.isArray(c.jobs)
|
||||
? c.jobs?.[0]?.credit_id
|
||||
: c.credit_id;
|
||||
|
||||
newCredits.push({
|
||||
entry_id: savedEntry.id,
|
||||
people_id: person.id,
|
||||
tmdb_credit_id: c.credit_id,
|
||||
character: c.cast_type === "cast" ? c.character : null,
|
||||
tmdb_credit_id: tmdbCreditId,
|
||||
character,
|
||||
order: c.cast_type === "cast" ? c.order : null,
|
||||
profile_path: person.profile_path || null,
|
||||
adult: person.adult || false,
|
||||
episode_count: c.total_episode_count ?? null,
|
||||
profile_path: person.profile_path,
|
||||
adult: person.adult,
|
||||
cast_type: c.cast_type,
|
||||
department: c.cast_type === "crew" ? c.department || null : null,
|
||||
job: c.cast_type === "crew" ? c.job || null : null,
|
||||
};
|
||||
});
|
||||
job,
|
||||
});
|
||||
}
|
||||
|
||||
await Credit.bulkCreate(newCredits);
|
||||
console.log(
|
||||
`[CREDITS] Inserted ${newCredits.length} credits for entry ${savedEntry.id}`,
|
||||
);
|
||||
|
||||
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;
|
||||
// Extract director name from processed credits (handles both movie & TV aggregate format)
|
||||
const directorCredit = allCredits.find((c) => {
|
||||
if (c.cast_type !== "crew") return false;
|
||||
const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job];
|
||||
return jobs.includes("Director");
|
||||
});
|
||||
savedEntry.director = directorCredit?.name || null;
|
||||
|
||||
await savedEntry.save();
|
||||
|
||||
|
||||
@@ -252,14 +252,18 @@ class MaintenanceService {
|
||||
|
||||
/**
|
||||
* Find and optionally remove duplicate credits.
|
||||
* A duplicate is the same person in the same entry with the same role.
|
||||
* For cast: same character. For crew: same job.
|
||||
*
|
||||
* Pass 1: Role-level — same (entry, person, type, role).
|
||||
* Pass 2: Type-level — same (entry, person, type) but different roles.
|
||||
* Keeps the credit WITH a role; if both have roles, keeps newest ID.
|
||||
*
|
||||
* @param {boolean} [dry=false] - if true only count, if false also delete
|
||||
*/
|
||||
async cleanDuplicateCredits(dry = false) {
|
||||
const { Sequelize } = require("sequelize");
|
||||
|
||||
const duplicates = await Credit.findAll({
|
||||
// ── Pass 1: Exact role-level duplicates ──
|
||||
const duplicateGroups = await Credit.findAll({
|
||||
attributes: [
|
||||
"entry_id",
|
||||
"people_id",
|
||||
@@ -274,11 +278,11 @@ class MaintenanceService {
|
||||
raw: true,
|
||||
});
|
||||
|
||||
let duplicateGroups = duplicates.length;
|
||||
let pass1Groups = duplicateGroups.length;
|
||||
let deletedCount = 0;
|
||||
|
||||
if (!dry) {
|
||||
for (const row of duplicates) {
|
||||
for (const row of duplicateGroups) {
|
||||
const idList = row.ids
|
||||
.split(",")
|
||||
.map(Number)
|
||||
@@ -290,24 +294,112 @@ class MaintenanceService {
|
||||
}
|
||||
}
|
||||
|
||||
const totalDupes = duplicates.reduce(
|
||||
const pass1Dupes = duplicateGroups.reduce(
|
||||
(sum, r) => sum + parseInt(r.cnt) - 1,
|
||||
0,
|
||||
);
|
||||
|
||||
if (dry)
|
||||
// ── Pass 2: Type-level duplicates (same person/entry/type, different roles) ──
|
||||
const typeDupes = await Credit.findAll({
|
||||
attributes: [
|
||||
"entry_id",
|
||||
"people_id",
|
||||
"cast_type",
|
||||
[Sequelize.fn("COUNT", Sequelize.col("id")), "cnt"],
|
||||
[Sequelize.fn("GROUP_CONCAT", Sequelize.col("id")), "ids"],
|
||||
[
|
||||
Sequelize.fn(
|
||||
"GROUP_CONCAT",
|
||||
Sequelize.fn(
|
||||
"COALESCE",
|
||||
Sequelize.col("character"),
|
||||
Sequelize.col("job"),
|
||||
),
|
||||
),
|
||||
"roles",
|
||||
],
|
||||
],
|
||||
group: ["entry_id", "people_id", "cast_type"],
|
||||
having: Sequelize.literal("COUNT(id) > 1"),
|
||||
raw: true,
|
||||
});
|
||||
|
||||
let pass2Groups = typeDupes.length;
|
||||
let pass2Deleted = 0;
|
||||
|
||||
if (!dry) {
|
||||
for (const row of typeDupes) {
|
||||
const idList = row.ids.split(",").map(Number);
|
||||
|
||||
// Fetch these credits to inspect their roles
|
||||
const credits = await Credit.findAll({
|
||||
where: { id: idList },
|
||||
order: [["id", "DESC"]],
|
||||
});
|
||||
|
||||
// Separate: credits with roles vs without
|
||||
const withRole = credits.filter((c) => {
|
||||
if (c.cast_type === "cast") return c.character && c.character.trim();
|
||||
return c.job && c.job.trim();
|
||||
});
|
||||
const withoutRole = credits.filter((c) => {
|
||||
if (c.cast_type === "cast")
|
||||
return !c.character || !c.character.trim();
|
||||
return !c.job || !c.job.trim();
|
||||
});
|
||||
|
||||
let keep;
|
||||
const toDelete = [];
|
||||
|
||||
if (withRole.length > 0 && withoutRole.length > 0) {
|
||||
// Prefer the one WITH a role; keep the newest among those with roles.
|
||||
// Delete all without-role entries.
|
||||
keep = withRole[0]; // already sorted by id DESC
|
||||
toDelete.push(...withoutRole.map((c) => c.id));
|
||||
// If there are multiple with-role, delete the older ones
|
||||
if (withRole.length > 1) {
|
||||
toDelete.push(...withRole.slice(1).map((c) => c.id));
|
||||
}
|
||||
} else if (withRole.length > 1) {
|
||||
// All have roles — keep newest, delete older
|
||||
keep = withRole[0];
|
||||
toDelete.push(...withRole.slice(1).map((c) => c.id));
|
||||
} else {
|
||||
// None have roles — keep newest, delete older
|
||||
keep = withoutRole[0];
|
||||
toDelete.push(...withoutRole.slice(1).map((c) => c.id));
|
||||
}
|
||||
|
||||
if (toDelete.length > 0) {
|
||||
await Credit.destroy({ where: { id: toDelete } });
|
||||
pass2Deleted += toDelete.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pass2Dupes = typeDupes.reduce(
|
||||
(sum, r) => sum + parseInt(r.cnt) - 1,
|
||||
0,
|
||||
);
|
||||
|
||||
const totalGroups = pass1Groups + pass2Groups;
|
||||
const totalDupes = pass1Dupes + pass2Dupes;
|
||||
const totalDeleted = deletedCount + pass2Deleted;
|
||||
|
||||
if (dry) {
|
||||
logToFile(
|
||||
`Dry duplicate credits check: ${duplicateGroups} groups, ${totalDupes} duplicates`,
|
||||
`Dry duplicate credits: Pass1=${pass1Groups} groups (${pass1Dupes} dupes), Pass2=${pass2Groups} groups (${pass2Dupes} dupes) → ${totalGroups} groups, ${totalDupes} duplicates`,
|
||||
);
|
||||
else
|
||||
} else {
|
||||
logToFile(
|
||||
`Cleaned duplicate credits: ${deletedCount} removed from ${duplicateGroups} groups`,
|
||||
`Cleaned duplicate credits: Pass1=${pass1Groups} groups (${deletedCount} deleted), Pass2=${pass2Groups} groups (${pass2Deleted} deleted) → ${totalDeleted} total removed`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
groups: duplicateGroups,
|
||||
groups: totalGroups,
|
||||
duplicates: totalDupes,
|
||||
deleted: deletedCount,
|
||||
deleted: totalDeleted,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -13,5 +13,13 @@
|
||||
"episodesViewMode": "grid-2",
|
||||
"favoritsViewMode": "",
|
||||
"authPassword": "",
|
||||
"jwtSecret": "change-me-to-a-random-string"
|
||||
"jwtSecret": "change-me-to-a-random-string",
|
||||
"dashboardToken": "your-dashboard-token-here",
|
||||
"namedTokens": [
|
||||
{
|
||||
"name": "homepage-widget",
|
||||
"value": "generate-a-secure-random-string",
|
||||
"endDate": "2027-12-31"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
# Showy Dashboard — Homepage Widget
|
||||
|
||||
Displays Showy library stats on your Homepage dashboard.
|
||||
|
||||
## Setup
|
||||
|
||||
### 1. Showy Access Token
|
||||
|
||||
In your Showy settings pages you can generate a token. Copy it and use it in the widget configuration below.
|
||||
|
||||
The endpoint will be available at `GET /homepage-integration?token=your-secret-token-here`
|
||||
|
||||
### 2. Copy widget into your Homepage install
|
||||
|
||||
Copy this folder (`showydashboard/`) into your Homepage's `src/widgets/` directory.
|
||||
|
||||
### 3. Register the widget
|
||||
|
||||
**`src/widgets/widgets.js`** — add:
|
||||
|
||||
```js
|
||||
import showydashboard from "./showydashboard/widget";
|
||||
|
||||
const widgets = {
|
||||
// ...
|
||||
showydashboard: showydashboard,
|
||||
};
|
||||
```
|
||||
|
||||
**`src/widgets/components.js`** — add:
|
||||
|
||||
```js
|
||||
const components = {
|
||||
// ...
|
||||
showydashboard: dynamic(() => import("./showydashboard/component")),
|
||||
};
|
||||
```
|
||||
|
||||
### 4. Add to your Homepage services.yaml
|
||||
|
||||
```yaml
|
||||
- Showy Library:
|
||||
icon: /icons/showy.png
|
||||
description: Movies & TV-Series Tracking library
|
||||
widget:
|
||||
type: showydashboard
|
||||
url: http://YOUR-SHOWY-HOST:4000
|
||||
dashboardToken: your-secret-token-here
|
||||
fields: ["library", "libraryMovies", "librarySeries", "watchlist", "watchlistMovies", "watchlistSeries"]
|
||||
```
|
||||
|
||||
### Available fields
|
||||
|
||||
| Field | Description |
|
||||
|---|---|
|
||||
| `totalEntries` | All entries in the library |
|
||||
| `library` | Entries not in watchlist |
|
||||
| `libraryMovies` | Movies not in watchlist |
|
||||
| `librarySeries` | TV series not in watchlist |
|
||||
| `watchlist` | Entries in watchlist |
|
||||
| `watchlistMovies` | Movies in watchlist |
|
||||
| `watchlistSeries` | TV series in watchlist |
|
||||
| `collections` | Total collections |
|
||||
| `favorits` | Favorite entries |
|
||||
|
||||
Omit `fields` to show all 9. `url` is just the host base — the widget appends `/api/v1/homepage-integration?token=...` automatically.
|
||||
@@ -0,0 +1,47 @@
|
||||
import Block from "components/services/widget/block";
|
||||
import Container from "components/services/widget/container";
|
||||
|
||||
import useWidgetAPI from "utils/proxy/use-widget-api";
|
||||
|
||||
export default function Component({ service }) {
|
||||
const { widget } = service;
|
||||
|
||||
const { data: showyStats, error: showyStatsError } = useWidgetAPI(
|
||||
widget,
|
||||
"stats",
|
||||
);
|
||||
|
||||
if (showyStatsError) {
|
||||
return <Container service={service} error={showyStatsError} />;
|
||||
}
|
||||
|
||||
if (!showyStats) {
|
||||
return (
|
||||
<Container service={service}>
|
||||
{/* <Block label="Total Entries" />*/}
|
||||
<Block label="Library" />
|
||||
{/* <Block label="Library Movies" />
|
||||
<Block label="Library Series" />*/}
|
||||
<Block label="Watchlist" />
|
||||
{/* <Block label="Watchlist Movies" />
|
||||
<Block label="Watchlist Series" />
|
||||
<Block label="Collections" />
|
||||
<Block label="Favorites" />*/}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container service={service}>
|
||||
{/* <Block label="Total Entries" value={showyStats.totalEntries} />*/}
|
||||
<Block label="Library" value={showyStats.library} />
|
||||
{/* <Block label="Library Movies" value={showyStats.libraryMovies} />*/}
|
||||
{/* <Block label="Library Series" value={showyStats.librarySeries} />*/}
|
||||
<Block label="Watchlist" value={showyStats.watchlist} />
|
||||
{/* <Block label="Watchlist Movies" value={showyStats.watchlistMovies} />*/}
|
||||
{/* <Block label="Watchlist Series" value={showyStats.watchlistSeries} />*/}
|
||||
{/* <Block label="Collections" value={showyStats.collections} />*/}
|
||||
{/* <Block label="Favorites" value={showyStats.favorits} />*/}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { asJson } from "utils/proxy/api-helpers";
|
||||
import genericProxyHandler from "utils/proxy/handlers/generic";
|
||||
|
||||
const widget = {
|
||||
api: "{url}/api/v1/{endpoint}?token={dashboardToken}",
|
||||
proxyHandler: genericProxyHandler,
|
||||
|
||||
mappings: {
|
||||
totals: {
|
||||
endpoint: "homepage-integration",
|
||||
map: (data) => ({
|
||||
totalEntries: asJson(data).totalEntries,
|
||||
collections: asJson(data).collections,
|
||||
favorits: asJson(data).favorits,
|
||||
}),
|
||||
},
|
||||
library: {
|
||||
endpoint: "homepage-integration",
|
||||
map: (data) => ({
|
||||
library: asJson(data).library,
|
||||
libraryMovies: asJson(data).libraryMovies,
|
||||
librarySeries: asJson(data).librarySeries,
|
||||
}),
|
||||
},
|
||||
watchlist: {
|
||||
endpoint: "homepage-integration",
|
||||
map: (data) => ({
|
||||
watchlist: asJson(data).watchlist,
|
||||
watchlistMovies: asJson(data).watchlistMovies,
|
||||
watchlistSeries: asJson(data).watchlistSeries,
|
||||
}),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default widget;
|
||||
@@ -17,4 +17,7 @@ export const seasonsApi = {
|
||||
api.put<Season>(`/seasons/${id}`, data).then((r) => r.data),
|
||||
|
||||
delete: (id: number) => api.delete(`/seasons/${id}`).then((r) => r.data),
|
||||
|
||||
refresh: (id: number) =>
|
||||
api.put<Season>(`/seasons/${id}/refresh`).then((r) => r.data),
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { StarRating } from "@/components/ui/star-rating";
|
||||
import { useUpdateSeason } from "@/hooks/useSeasons";
|
||||
import type { Season } from "@/types";
|
||||
|
||||
interface SeasonRatingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
season: Season;
|
||||
}
|
||||
|
||||
export function SeasonRatingDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
season,
|
||||
}: SeasonRatingDialogProps) {
|
||||
const currentRating = season.user_rating ?? 0;
|
||||
const [selected, setSelected] = useState<number>(currentRating);
|
||||
const updateSeason = useUpdateSeason();
|
||||
|
||||
useEffect(() => {
|
||||
if (open) setSelected(season.user_rating ?? 0);
|
||||
}, [open, season.user_rating]);
|
||||
|
||||
const handleRate = (rating: number) => {
|
||||
setSelected(rating);
|
||||
updateSeason.mutate({
|
||||
id: season.id,
|
||||
data: { user_rating: rating || null },
|
||||
});
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
setSelected(0);
|
||||
updateSeason.mutate({
|
||||
id: season.id,
|
||||
data: { user_rating: null },
|
||||
});
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="w-auto sm:max-w-none">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Rate Season</DialogTitle>
|
||||
<p className="text-sm text-muted-foreground line-clamp-1">
|
||||
{season.name}
|
||||
</p>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col items-center gap-4 py-2">
|
||||
<StarRating value={selected} onChange={handleRate} size="lg" />
|
||||
|
||||
<p className="text-xl font-semibold tabular-nums">
|
||||
{selected > 0 ? `${selected} / 10` : "—"}
|
||||
</p>
|
||||
|
||||
{(selected > 0 || currentRating > 0) && (
|
||||
<Button variant="ghost" size="sm" onClick={handleClear}>
|
||||
Clear rating
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { seasonsApi } from "@/api/seasons";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export const seasonKeys = {
|
||||
all: ["seasons"] as const,
|
||||
@@ -22,3 +23,42 @@ export function useSeasonEpisodes(id: number) {
|
||||
enabled: !!id,
|
||||
});
|
||||
}
|
||||
|
||||
export function useRefreshSeason() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (id: number) => seasonsApi.refresh(id),
|
||||
onSuccess: (season) => {
|
||||
queryClient.invalidateQueries({ queryKey: seasonKeys.detail(season.id) });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: seasonKeys.episodes(season.id),
|
||||
});
|
||||
toast.success("Season refreshed");
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to refresh season");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateSeason() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({
|
||||
id,
|
||||
data,
|
||||
}: {
|
||||
id: number;
|
||||
data: Partial<Parameters<typeof seasonsApi.update>[1]>;
|
||||
}) => seasonsApi.update(id, data),
|
||||
onSuccess: (season) => {
|
||||
queryClient.invalidateQueries({ queryKey: seasonKeys.detail(season.id) });
|
||||
toast.success("Season updated");
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("Failed to update season");
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -61,6 +61,9 @@ export function normalizeGenres(raw: any[]): Genre[] {
|
||||
export function normalizeEntry(raw: any): Entry {
|
||||
return {
|
||||
...raw,
|
||||
// Map Sequelize camelCase property names → snake_case for frontend consistency
|
||||
show_in_calendar: raw.show_in_calendar ?? raw.showInCalendar ?? true,
|
||||
auto_sync: raw.auto_sync ?? raw.autoSync ?? true,
|
||||
// Singular → plural aliases (coerce tmdb_id to number for store comparisons)
|
||||
entryIds: (() => {
|
||||
const ids = raw.entryIds ?? raw.entryId;
|
||||
|
||||
@@ -125,6 +125,52 @@ export function CollectionDetailsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// ── Computed stats (from already-fetched data) ──
|
||||
const stats = useMemo(() => {
|
||||
const movies = entries.filter((e) => !e.is_tvseries);
|
||||
const tvEntries = entries.filter((e) => e.is_tvseries);
|
||||
const seasonCount = tvEntries.reduce(
|
||||
(sum, e) => sum + (e.seasons?.length || 0),
|
||||
0,
|
||||
);
|
||||
const episodeCount = tvEntries.reduce(
|
||||
(sum, e) =>
|
||||
sum +
|
||||
(e.seasons?.reduce((s, season) => s + (season.episode_count || 0), 0) ||
|
||||
0),
|
||||
0,
|
||||
);
|
||||
const typeParts: string[] = [];
|
||||
if (movies.length > 0) typeParts.push(`${movies.length} movies`);
|
||||
if (tvEntries.length > 0) typeParts.push(`${tvEntries.length} series`);
|
||||
const typeStr = typeParts.join(" & ");
|
||||
|
||||
const subParts: string[] = [];
|
||||
if (seasonCount > 0) subParts.push(`${seasonCount} seasons`);
|
||||
if (episodeCount > 0) subParts.push(`${episodeCount} episodes`);
|
||||
const subStr = subParts.length > 0 ? ` (${subParts.join("/")})` : "";
|
||||
|
||||
const summary = `${entries.length} entries - ${typeStr}${subStr}`;
|
||||
|
||||
const watchMinutes = entries.reduce((sum, e) => {
|
||||
if (e.is_tvseries) {
|
||||
const eps =
|
||||
e.seasons?.reduce(
|
||||
(s, season) => s + (season.episode_count || 0),
|
||||
0,
|
||||
) || 0;
|
||||
const epRuntime = e.runtime || 42;
|
||||
return sum + eps * epRuntime;
|
||||
}
|
||||
return sum + (e.runtime || 0);
|
||||
}, 0);
|
||||
const hours = Math.floor(watchMinutes / 60);
|
||||
const mins = watchMinutes % 60;
|
||||
const watchTime = hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
|
||||
|
||||
return { summary, watchTime };
|
||||
}, [entries]);
|
||||
|
||||
// Handle error redirect in useEffect (not during render)
|
||||
useEffect(() => {
|
||||
if (!isLoading && (isError || (!collection && !isLoading))) {
|
||||
@@ -221,10 +267,10 @@ export function CollectionDetailsPage() {
|
||||
{collection.description}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-3">
|
||||
<p className="text-sm text-white/60">
|
||||
{entries.length} {entries.length === 1 ? "entry" : "entries"}
|
||||
</p>
|
||||
<div className="flex items-center gap-3 flex-wrap text-sm text-white/60">
|
||||
<span>
|
||||
{stats.summary} ~{stats.watchTime}
|
||||
</span>
|
||||
{collection.user_rating != null &&
|
||||
collection.user_rating > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
|
||||
@@ -1,19 +1,33 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
useState,
|
||||
useEffect,
|
||||
useRef,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useReducer,
|
||||
} from "react";
|
||||
import { useSearchParams, Link } from "react-router-dom";
|
||||
import { useTmdbSearch, useTmdbSearchPeople } from "@/hooks/useTmdb";
|
||||
import { useLibrary } from "@/hooks/useEntries";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Search } from "lucide-react";
|
||||
import { EntryCard } from "@/components/entries/EntryCard";
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||
import { getTmdbImageUrl } from "@/lib/api";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Search, Loader2 } from "lucide-react";
|
||||
import { EntryCard } from "@/components/entries/EntryCard";
|
||||
import { getProfileUrl } from "@/lib/media-utils";
|
||||
|
||||
type SearchTab = "entries" | "people";
|
||||
|
||||
const MAX_EMPTY_PAGES = 4;
|
||||
|
||||
export function SearchPage() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const initialQuery = searchParams.get("q") || "";
|
||||
const [searchInput, setSearchInput] = useState(initialQuery);
|
||||
const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
|
||||
const [activeTab, setActiveTab] = useState<SearchTab>("entries");
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout>>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
@@ -36,90 +50,338 @@ export function SearchPage() {
|
||||
|
||||
useLibrary();
|
||||
|
||||
const searchResults = useTmdbSearch(debouncedQuery);
|
||||
const peopleResults = useTmdbSearchPeople(debouncedQuery);
|
||||
const {
|
||||
data: searchData,
|
||||
isLoading: searchLoading,
|
||||
fetchNextPage: fetchNextSearch,
|
||||
hasNextPage: hasNextSearch,
|
||||
isFetchingNextPage: fetchingNextSearch,
|
||||
} = useTmdbSearch(debouncedQuery);
|
||||
|
||||
const searchEntries =
|
||||
searchResults.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const searchPeople =
|
||||
peopleResults.data?.pages.flatMap((p) => p.results) ?? [];
|
||||
const peopleQuery = activeTab === "people" ? debouncedQuery : "";
|
||||
|
||||
const {
|
||||
data: peopleData,
|
||||
fetchNextPage: fetchNextPeople,
|
||||
hasNextPage: hasNextPeople,
|
||||
isFetchingNextPage: fetchingNextPeople,
|
||||
} = useTmdbSearchPeople(peopleQuery);
|
||||
|
||||
// Filter entries: only movies & TV (TMDB multi-search sometimes returns "person" results)
|
||||
const searchEntries = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const all = searchData?.pages.flatMap((p) => p.results) ?? [];
|
||||
return all
|
||||
.filter((entry) => entry.media_type !== "person")
|
||||
.filter((entry) => {
|
||||
const key = `${entry.id}-${entry.media_type}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}, [searchData]);
|
||||
|
||||
const searchPeople = useMemo(() => {
|
||||
const seen = new Set<number>();
|
||||
const all = peopleData?.pages.flatMap((p) => p.results) ?? [];
|
||||
return all.filter((person) => {
|
||||
if (seen.has(person.id)) return false;
|
||||
seen.add(person.id);
|
||||
return true;
|
||||
});
|
||||
}, [peopleData]);
|
||||
|
||||
type SpamAction =
|
||||
| { type: "entry_empty" }
|
||||
| { type: "entry_found" }
|
||||
| { type: "people_empty" }
|
||||
| { type: "people_found" }
|
||||
| { type: "reset_entry" }
|
||||
| { type: "reset_people" }
|
||||
| { type: "reset_all" };
|
||||
|
||||
// ── Anti-spam: stop auto-scroll after N consecutive empty pages ──
|
||||
const prevEntryCountRef = useRef(0);
|
||||
const prevPeopleCountRef = useRef(0);
|
||||
|
||||
const [spam, spamDispatch] = useReducer(
|
||||
(state: { entry: number; people: number }, action: SpamAction) => {
|
||||
switch (action.type) {
|
||||
case "entry_empty":
|
||||
return { ...state, entry: state.entry + 1 };
|
||||
case "entry_found":
|
||||
return { ...state, entry: 0 };
|
||||
case "people_empty":
|
||||
return { ...state, people: state.people + 1 };
|
||||
case "people_found":
|
||||
return { ...state, people: 0 };
|
||||
case "reset_entry":
|
||||
return { ...state, entry: 0 };
|
||||
case "reset_people":
|
||||
return { ...state, people: 0 };
|
||||
case "reset_all":
|
||||
return { entry: 0, people: 0 };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
},
|
||||
{ entry: 0, people: 0 },
|
||||
);
|
||||
|
||||
const entryLoadMore = spam.entry >= MAX_EMPTY_PAGES;
|
||||
const peopleLoadMore = spam.people >= MAX_EMPTY_PAGES;
|
||||
|
||||
// Reset streak on new query
|
||||
useEffect(() => {
|
||||
prevEntryCountRef.current = 0;
|
||||
prevPeopleCountRef.current = 0;
|
||||
spamDispatch({ type: "reset_all" });
|
||||
}, [debouncedQuery]);
|
||||
|
||||
// Detect empty entry fetches
|
||||
useEffect(() => {
|
||||
if (fetchingNextSearch || searchEntries.length === 0) return;
|
||||
if (searchEntries.length === prevEntryCountRef.current) {
|
||||
spamDispatch({ type: "entry_empty" });
|
||||
} else {
|
||||
spamDispatch({ type: "entry_found" });
|
||||
}
|
||||
prevEntryCountRef.current = searchEntries.length;
|
||||
}, [fetchingNextSearch, searchEntries.length]);
|
||||
|
||||
// Detect empty people fetches
|
||||
useEffect(() => {
|
||||
if (fetchingNextPeople || searchPeople.length === 0) return;
|
||||
if (searchPeople.length === prevPeopleCountRef.current) {
|
||||
spamDispatch({ type: "people_empty" });
|
||||
} else {
|
||||
spamDispatch({ type: "people_found" });
|
||||
}
|
||||
prevPeopleCountRef.current = searchPeople.length;
|
||||
}, [fetchingNextPeople, searchPeople.length]);
|
||||
|
||||
// ── Infinite scroll sentinels ──
|
||||
const entrySentinelRef = useRef<HTMLDivElement>(null);
|
||||
const peopleSentinelRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const handleEntryIntersect = useCallback(
|
||||
(entries: IntersectionObserverEntry[]) => {
|
||||
if (
|
||||
entries[0]?.isIntersecting &&
|
||||
hasNextSearch &&
|
||||
!fetchingNextSearch &&
|
||||
!entryLoadMore
|
||||
) {
|
||||
fetchNextSearch();
|
||||
}
|
||||
},
|
||||
[hasNextSearch, fetchingNextSearch, fetchNextSearch, entryLoadMore],
|
||||
);
|
||||
|
||||
const handlePeopleIntersect = useCallback(
|
||||
(entries: IntersectionObserverEntry[]) => {
|
||||
if (
|
||||
entries[0]?.isIntersecting &&
|
||||
hasNextPeople &&
|
||||
!fetchingNextPeople &&
|
||||
!peopleLoadMore
|
||||
) {
|
||||
fetchNextPeople();
|
||||
}
|
||||
},
|
||||
[hasNextPeople, fetchingNextPeople, fetchNextPeople, peopleLoadMore],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const sentinel = entrySentinelRef.current;
|
||||
if (!sentinel) return;
|
||||
const observer = new IntersectionObserver(handleEntryIntersect, {
|
||||
rootMargin: "200px",
|
||||
});
|
||||
observer.observe(sentinel);
|
||||
return () => observer.disconnect();
|
||||
}, [handleEntryIntersect]);
|
||||
|
||||
useEffect(() => {
|
||||
const sentinel = peopleSentinelRef.current;
|
||||
if (!sentinel || activeTab !== "people") return;
|
||||
const observer = new IntersectionObserver(handlePeopleIntersect, {
|
||||
rootMargin: "200px",
|
||||
});
|
||||
observer.observe(sentinel);
|
||||
return () => observer.disconnect();
|
||||
}, [handlePeopleIntersect, activeTab]);
|
||||
|
||||
const isSearching = debouncedQuery.length > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-page-enter">
|
||||
{/* Search */}
|
||||
<div className="relative max-w-md">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search movies, TV shows & people..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-10"
|
||||
autoFocus
|
||||
/>
|
||||
{/* Search + Tabs row */}
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="relative flex-1 max-w-xs">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search movies, TV shows & people..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-10"
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
{isSearching && (
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(v) => setActiveTab(v as SearchTab)}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="entries">Movies & TV</TabsTrigger>
|
||||
<TabsTrigger value="people">People</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isSearching ? (
|
||||
<div className="space-y-6">
|
||||
{/* People results */}
|
||||
{searchPeople.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-lg font-semibold">People</h2>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{searchPeople.slice(0, 10).map((person) => (
|
||||
<Link
|
||||
key={person.id}
|
||||
to={`/people/tmdb/${person.id}`}
|
||||
className="flex items-center gap-2 rounded-full bg-muted px-3 py-1.5 transition-colors hover:bg-accent"
|
||||
<div className="space-y-4">
|
||||
{/* Movies & TV tab */}
|
||||
{activeTab === "entries" && (
|
||||
<>
|
||||
<h2 className="text-xl font-semibold">
|
||||
Results for “{debouncedQuery}”
|
||||
</h2>
|
||||
{searchEntries.length === 0 && !searchLoading ? (
|
||||
<p className="text-muted-foreground">No results found.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
|
||||
{searchEntries.map((entry, index) => (
|
||||
<div
|
||||
key={`${entry.id}-${entry.media_type}`}
|
||||
className="animate-card-enter"
|
||||
style={{
|
||||
animationDelay: `${Math.min(index * 30, 300)}ms`,
|
||||
}}
|
||||
>
|
||||
<EntryCard tmdbEntry={entry} showTypeBadge />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sentinel / Load more */}
|
||||
<div
|
||||
ref={entrySentinelRef}
|
||||
className="flex h-20 items-center justify-center"
|
||||
>
|
||||
<Avatar className="h-7 w-7">
|
||||
<AvatarImage
|
||||
src={
|
||||
person.profile_path
|
||||
? getTmdbImageUrl(person.profile_path, "w92")
|
||||
: undefined
|
||||
}
|
||||
alt={person.name}
|
||||
/>
|
||||
<AvatarFallback className="text-xs">
|
||||
{person.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")
|
||||
.slice(0, 2)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span className="text-sm font-medium">{person.name}</span>
|
||||
{person.known_for_department && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{person.known_for_department}
|
||||
{fetchingNextSearch ? (
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
) : entryLoadMore && hasNextSearch ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
spamDispatch({ type: "reset_entry" });
|
||||
fetchNextSearch();
|
||||
}}
|
||||
>
|
||||
Load more
|
||||
</Button>
|
||||
) : hasNextSearch ? (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Scroll for more
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : searchEntries.length > 0 ? (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
All results loaded
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Entry results */}
|
||||
<h2 className="text-xl font-semibold">
|
||||
Search Results for “{debouncedQuery}”
|
||||
</h2>
|
||||
{searchEntries.length === 0 && !searchResults.isLoading ? (
|
||||
<p className="text-muted-foreground">No results found.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
|
||||
{searchEntries.map((entry, index) => (
|
||||
<div
|
||||
key={entry.id}
|
||||
className="animate-card-enter"
|
||||
style={{ animationDelay: `${Math.min(index * 30, 300)}ms` }}
|
||||
>
|
||||
<EntryCard tmdbEntry={entry} showTypeBadge />
|
||||
{/* People tab */}
|
||||
{activeTab === "people" && (
|
||||
<>
|
||||
<h2 className="text-xl font-semibold">
|
||||
People matching “{debouncedQuery}”
|
||||
</h2>
|
||||
{peopleQuery && searchPeople.length === 0 && !peopleData ? (
|
||||
<div className="flex h-40 items-center justify-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : searchPeople.length === 0 && peopleData ? (
|
||||
<p className="text-muted-foreground">No people found.</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-3 gap-4 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8">
|
||||
{searchPeople.map((person, index) => (
|
||||
<Link
|
||||
key={person.id}
|
||||
to={`/people/tmdb/${person.id}`}
|
||||
className="group flex flex-col items-center gap-2 text-center animate-card-enter"
|
||||
style={{
|
||||
animationDelay: `${Math.min(index * 20, 300)}ms`,
|
||||
}}
|
||||
>
|
||||
<div className="relative">
|
||||
<Avatar className="h-28 w-28 transition-transform group-hover:scale-105 sm:h-32 sm:w-32">
|
||||
<AvatarImage
|
||||
src={getProfileUrl(person.profile_path)}
|
||||
alt={person.name}
|
||||
/>
|
||||
<AvatarFallback className="text-lg">
|
||||
{person.name
|
||||
.split(" ")
|
||||
.map((n) => n[0])
|
||||
.join("")
|
||||
.slice(0, 2)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</div>
|
||||
<span className="text-sm font-medium leading-tight line-clamp-2">
|
||||
{person.name}
|
||||
</span>
|
||||
{person.known_for_department && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{person.known_for_department}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Sentinel / Load more */}
|
||||
<div
|
||||
ref={peopleSentinelRef}
|
||||
className="flex h-20 items-center justify-center"
|
||||
>
|
||||
{fetchingNextPeople ? (
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
) : peopleLoadMore && hasNextPeople ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
spamDispatch({ type: "reset_people" });
|
||||
fetchNextPeople();
|
||||
}}
|
||||
>
|
||||
Load more
|
||||
</Button>
|
||||
) : hasNextPeople ? (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Scroll for more
|
||||
</span>
|
||||
) : searchPeople.length > 0 ? (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
All results loaded
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -1,16 +1,36 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, Link } from "react-router-dom";
|
||||
import { useSeason, useSeasonEpisodes } from "@/hooks/useSeasons";
|
||||
import {
|
||||
useSeason,
|
||||
useSeasonEpisodes,
|
||||
useRefreshSeason,
|
||||
} from "@/hooks/useSeasons";
|
||||
import { useEntry, useEntrySeasons } from "@/hooks/useEntries";
|
||||
import { useLibraryStore } from "@/stores/useLibraryStore";
|
||||
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
|
||||
import { MarkSeasonWatchedDialog } from "@/components/dialogs/MarkSeasonWatchedDialog";
|
||||
import { SeasonRatingDialog } from "@/components/dialogs/SeasonRatingDialog";
|
||||
import { StreamingDialog } from "@/components/streaming/StreamingDialog";
|
||||
import { useStreamingStore } from "@/stores/useStreamingStore";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Eye, CheckCircle2, ListChecks, PlayCircle } from "lucide-react";
|
||||
import { StarRating } from "@/components/ui/star-rating";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
Eye,
|
||||
CheckCircle2,
|
||||
ListChecks,
|
||||
PlayCircle,
|
||||
Ellipsis,
|
||||
RefreshCw,
|
||||
Star,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
@@ -33,8 +53,10 @@ export function SeasonPage() {
|
||||
entry?.title ??
|
||||
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
|
||||
const { initialize, play } = useStreamingStore();
|
||||
const refreshSeason = useRefreshSeason();
|
||||
const [dialogEpisode, setDialogEpisode] = useState<Episode | null>(null);
|
||||
const [showMarkAllDialog, setShowMarkAllDialog] = useState(false);
|
||||
const [showRatingDialog, setShowRatingDialog] = useState(false);
|
||||
const [streamingOpen, setStreamingOpen] = useState(false);
|
||||
|
||||
const handleWatchEpisode = (season: number, episodeNumber: number) => {
|
||||
@@ -98,16 +120,37 @@ export function SeasonPage() {
|
||||
<div className="flex-1 flex flex-col justify-center space-y-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
|
||||
<h1 className="text-xl font-bold sm:text-2xl">{season.name}</h1>
|
||||
{/* Mark Season as Watched — top right */}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="shrink-0 w-full sm:w-auto"
|
||||
onClick={() => setShowMarkAllDialog(true)}
|
||||
>
|
||||
<ListChecks className="mr-1.5 h-4 w-4" />
|
||||
Mark Season Watched
|
||||
</Button>
|
||||
{/* Actions dropdown — top right */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
size="icon"
|
||||
variant="outline"
|
||||
className="shrink-0 self-end sm:self-start"
|
||||
>
|
||||
<Ellipsis className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem onClick={() => setShowMarkAllDialog(true)}>
|
||||
<ListChecks className="mr-2 h-4 w-4" />
|
||||
Mark Season Watched
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShowRatingDialog(true)}>
|
||||
<Star className="mr-2 h-4 w-4" />
|
||||
Rate Season
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => refreshSeason.mutate(season.id)}
|
||||
disabled={refreshSeason.isPending}
|
||||
>
|
||||
<RefreshCw
|
||||
className={`mr-2 h-4 w-4 ${refreshSeason.isPending ? "animate-spin" : ""}`}
|
||||
/>
|
||||
Refresh Season
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>Season {season.season_number}</span>
|
||||
@@ -121,6 +164,21 @@ export function SeasonPage() {
|
||||
<span>{totalEpisodes} episodes</span>
|
||||
</div>
|
||||
|
||||
{/* Season rating */}
|
||||
<div className="flex items-center gap-2">
|
||||
<StarRating value={season.user_rating ?? 0} readOnly size="sm" />
|
||||
{season.user_rating != null && season.user_rating > 0 && (
|
||||
<span className="text-sm font-medium tabular-nums">
|
||||
{season.user_rating}/10
|
||||
</span>
|
||||
)}
|
||||
{season.tmdb_rating != null && season.tmdb_rating > 0 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
TMDB {season.tmdb_rating}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Watch progress */}
|
||||
<div className="flex items-center gap-3 max-w-xs">
|
||||
<Progress value={progress} className="flex-1 h-2" />
|
||||
@@ -281,6 +339,15 @@ export function SeasonPage() {
|
||||
episodes={episodes}
|
||||
/>
|
||||
|
||||
{/* Season Rating dialog */}
|
||||
{season && (
|
||||
<SeasonRatingDialog
|
||||
open={showRatingDialog}
|
||||
onOpenChange={setShowRatingDialog}
|
||||
season={season}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Streaming dialog */}
|
||||
{entry && streamingOpen && (
|
||||
<StreamingDialog
|
||||
|
||||
Reference in new issue
Block a user