15 Commits
Author SHA1 Message Date
X4Lo 3144bd96c9 Add Tauri v2 desktop app alongside Electron
- New tauri/ project: frameless 1280x800 window, loads the Vite dev
  server in dev and tauri/frontend_build in release builds.
- Starts the backend on launch (node server.js in dev, pkg backend.exe
  sidecar in release) and stops it on exit through a Windows job
  object; reuses a backend already listening on port 4000.
- Custom title bar works in Tauri (minimize, maximize, close, drag
  region) with the matching window capabilities.
- react_frontend: dev:tauri / build:tauri scripts, shared platform
  flags so Electron and Tauri builds both use the local API and hash
  router. Web and Electron builds are unchanged.
- tauri/README.md: prerequisites, dev, build, and gaps vs Electron.
2026-11-05 18:27:40 +00:00
X4Lo 06bf902ad3 Merge pull request 'Redesign season and episode pages, add list/card views' (#7) from feat/season-episode-redesign into master
Reviewed-on: #7
2026-11-05 17:49:19 +00:00
X4Lo be248d7513 Redesign season and episode pages, add list/card views 2026-11-05 17:48:44 +00:00
X4Lo d0cd1cd94b Merge pull request 'Add history page with list, timeline and year in review' (#6) from feat/history-page into master
Reviewed-on: #6
2026-11-05 16:21:09 +00:00
X4Lo 760afd8e84 Add history page with list, timeline and year in review
- Backend: /history/years and /history/:year return every movie and
  episode watch in a year, with entry posters, genres, networks and buddies
- History tab: watches by month and day, back-to-back episodes grouped
- Timeline tab: latest to oldest, month dividers, stacked binge sessions
- Year in Review tab: hours, top shows and genres, streaks, busiest day,
  biggest binge, monthly and weekday charts, buddies and new shows
- Year picker, movies/TV filter, state kept in the URL; unknown-date
  watches badged and excluded from the review by default
- History link in the sidebar and command palette
2026-11-05 16:09:24 +00:00
X4Lo c4aa0488d4 Merge pull request 'Feat/tmdb full data' (#5) from feat/tmdb-full-data into master
Reviewed-on: #5
2026-11-05 14:36:10 +00:00
X4Lo 28eee34548 Unify entry page for TMDB previews and add artwork section
- Entry details page now also renders entries not in the library, using
  the TMDB preview mapped to the same entry shape; remove TmdbPreviewPage
- Preview endpoint returns an entry-shaped object, TMDB seasons and
  directors
- Artwork section: TMDB posters, backdrops and logos merged with the media
  table, with in-library badges, language filter and add-to-library
- Record tmdb_path on downloaded media so TMDB images can be matched
- Recommendations by TMDB id for entries not in the library
2026-11-05 14:06:46 +00:00
X4Lo a9ff2d089a Store full TMDB data, add rate limiting and stale-entry refresh
Backend
- Route all TMDB requests through a rate limiter (20 req/s, 8 concurrent)
  with 429/5xx retries; stop logging the API key
- Fetch external ids, certification, keywords, videos, watch providers and
  alternative titles in the entry details request
- Shared entry mapper used by create, refresh, season refresh and importer
- New columns on entries, ids, ratings, seasons, episodes and people, with
  an idempotent startup migration (adds missing columns, widens types)
- Fix TV IMDb ids, network country/logo, episode tmdb_id on refresh, and
  genre/network removal on refresh
- Add stale-entries maintenance job (count, start, cancel) and live
  recommendations endpoint

Frontend
- Entry page: certification, tagline, creators, in-app trailer, vote count,
  TV/movie details, network logos, external links, keywords, where to
  watch, and recommendations
- Episode page: directors, writers and guest stars
- Settings: TMDB refresh card with live progress
2026-11-05 11:39:15 +00:00
X4Lo cee6f7f961 Merge branch 'feat/entry-details-redesign' 2026-11-05 10:30:53 +00:00
X4Lo 1c6023cc52 Redesign entry details page
- Full-bleed backdrop hero with larger poster, bold title, meta and genres
- Single action bar: watch, trailer, watched, rate, favorite, collection, more
- Two-column body with ratings tiles and details sidebar
- Update loading skeleton to match the new layout
2026-11-05 10:30:41 +00:00
X4Lo 67c828838d Updated electron & react frontend packages & Agents.md 2026-11-03 20:47:40 +00:00
X4Lo cd2c135c65 Merge pull request 'Unify person page for local and TMDB people' (#4) from feat/unified-person-page into master
Reviewed-on: #4
2026-11-03 19:01:47 +00:00
X4Lo f88dfdae44 Unify person page for local and TMDB people
- Merge local and TMDB person views into a single PersonDetailsPage
- Remove unused PersonTmdbRedirectPage
- Show age tooltip on birthdays (person page and people list)
2026-11-03 18:58:42 +00:00
X4Lo 6d4c3e185a Merge pull request 'Add poster popup, selectable title, collection media previews and library toggles' (#3) from feat/details-pages-and-library-filters into master
Reviewed-on: #3
2026-11-03 18:40:25 +00:00
X4Lo 834e02e76b Add poster popup, selectable title, collection media previews and library toggles
- Collection edit dialog shows the current poster and backdrop when available
- Entry details: title is selectable (action row no longer overlays it)
- Entry details: clicking the poster opens it full size in a dialog
- Library: Favorites and Hidden are toggles that combine with the type tabs
2026-11-03 18:39:03 +00:00
102 changed files with 13473 additions and 5185 deletions

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ environment.ts
circular-dependencies.png
.agents/skills
auto_puller.py
/brain
# Compiled output
.angular
-27
View File
@@ -11,33 +11,6 @@ You can get project context from the following files:
## Mandatory Task Completion Rule
#### Update the `changes.md` file after completing any task requested by the user.
After completing ANY task requested by the user, you MUST update the file `changes.md`.
Append a new section at the end of `changes.md` using this exact format:
```md
### Milestone XXX
#### Backend Changes
- <change 1>
- <change 2>
- <change 3>
#### Frontend Changes
```
#### Rules
- Always ask the user if this is a new milestone or if you should continue appending to the current milestone.
- Replace `XXX` with the task number provided by the user (example: `025`).
- The bullet list must include all important modifications made.
- Do NOT overwrite previous entries: always APPEND.
- If `changes.md` does not exist, create it.
- If no task number is provided, use the next available number based on the last entry in the file.
- Always ensure formatting matches exactly (heading + code block + bullets).
### Documentation (Skip the legacy docs, we're using obsidian docs-vault now)
Update the `/backend/docs` and `/react_frontend/docs` folders with any relevant documentation changes related to the task you completed. This includes API documentation, architectural diagrams, or any other relevant docs.
+74
View File
@@ -0,0 +1,74 @@
const sequelize = require("./database");
/**
* Lightweight, idempotent schema migrations.
*
* `sequelize.sync()` runs without `alter`, so new model attributes never reach
* existing tables. This adds any column a model defines but the table lacks
* (additive only — nothing is dropped) and widens the few columns whose type
* changed. Safe to run on every start.
*/
// [model name, attribute name, expected DB type prefix (from describeTable)]
const TYPE_CHANGES = [
["entry", "certification", "VARCHAR(20)"],
["entry", "last_fetch", "DATETIME"],
["entry", "network_studio", "VARCHAR(100)"],
["network", "name", "VARCHAR(100)"],
];
async function addMissingColumns(queryInterface) {
for (const model of Object.values(sequelize.models)) {
const table = model.getTableName();
let columns;
try {
columns = await queryInterface.describeTable(table);
} catch {
continue; // table not created yet; sync handles it
}
for (const [name, attribute] of Object.entries(model.rawAttributes)) {
const column = attribute.field || name;
if (columns[column] || attribute.type?.key === "VIRTUAL") continue;
console.log(`[MIGRATION] Adding column ${table}.${column}`);
await queryInterface.addColumn(table, column, {
type: attribute.type,
allowNull: attribute.allowNull !== false,
defaultValue: attribute.defaultValue,
});
}
}
}
async function applyTypeChanges(queryInterface) {
for (const [modelName, attributeName, expectedType] of TYPE_CHANGES) {
const model = sequelize.models[modelName];
if (!model) continue;
const attribute = model.rawAttributes[attributeName];
const column = attribute.field || attributeName;
const table = model.getTableName();
const columns = await queryInterface.describeTable(table);
const current = columns[column]?.type?.toUpperCase();
if (!current || current.startsWith(expectedType)) continue;
console.log(
`[MIGRATION] Changing ${table}.${column} from ${current} to ${expectedType}`,
);
await queryInterface.changeColumn(table, column, {
type: attribute.type,
allowNull: attribute.allowNull !== false,
defaultValue: attribute.defaultValue,
});
}
}
async function runMigrations() {
const queryInterface = sequelize.getQueryInterface();
await addMissingColumns(queryInterface);
await applyTypeChanges(queryInterface);
}
module.exports = { runMigrations };
+130 -16
View File
@@ -1,9 +1,15 @@
const EntryRating = require('../models/EntryRating');
const collectionManager = require('../services/collectionManager');
const entryManager = require('../services/entryManager');
const entryService = require('../services/entryService');
const tmdbService = require('../services/tmdbService');
const asyncWrapper = require('../utils/asyncWrapper');
const EntryRating = require("../models/EntryRating");
const collectionManager = require("../services/collectionManager");
const entryManager = require("../services/entryManager");
const entryService = require("../services/entryService");
const tmdbService = require("../services/tmdbService");
const artworkService = require("../services/artworkService");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
} = require("../mappers/entryMapper");
const asyncWrapper = require("../utils/asyncWrapper");
const _collectionManager = collectionManager;
const _entryManager = entryManager;
@@ -105,7 +111,7 @@ class EntryController {
const seasons = await _entryService.getEntrySeasons(id);
if (seasons.length == 0) {
return res.status(204).json({ message: 'Provided entry has no seasons' });
return res.status(204).json({ message: "Provided entry has no seasons" });
}
res.status(200).json(seasons);
@@ -126,6 +132,59 @@ class EntryController {
res.status(201).json(entry);
});
// * GET - TMDB RECOMMENDATIONS FOR A LIBRARY ENTRY (live, not stored)
getEntryRecommendations = asyncWrapper(async (req, res) => {
const entry = await _entryService.getEntryById(req.params.id, false);
const tmdbId = entry.entryId?.tmdb_id;
if (!tmdbId)
return res.status(400).json({ message: "Entry has no TMDB id" });
const data = await tmdbService.fetchEntryRecommendations(
tmdbId,
entry.is_tvseries,
req.query.page || 1,
);
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch recommendations" });
res.status(200).json(data);
});
// * GET - TMDB RECOMMENDATIONS BY TMDB ID (entries not in the library)
getTmdbRecommendations = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params;
const data = await tmdbService.fetchEntryRecommendations(
tmdbId,
type === "tv",
req.query.page || 1,
);
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch recommendations" });
res.status(200).json(data);
});
// * GET - ARTWORK: TMDB images merged with the entry's media table
getEntryArtwork = asyncWrapper(async (req, res) => {
const artwork = await artworkService.getEntryArtwork(req.params.id);
res.status(200).json(artwork);
});
// * POST - ARTWORK: download a TMDB image into the entry's media table
addEntryArtwork = asyncWrapper(async (req, res) => {
const media = await artworkService.addEntryArtwork(req.params.id, req.body);
res.status(201).json(media);
});
// * GET - ARTWORK BY TMDB ID (entries not in the library)
getTmdbArtwork = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params;
const artwork = await artworkService.getTmdbArtwork(type, tmdbId);
res.status(200).json(artwork);
});
// * PUT - REQUEST COLLECTION REFRECH
fetchEntryCollection = asyncWrapper(async (req, res, next) => {
const { id } = req.params;
@@ -145,7 +204,7 @@ class EntryController {
const { page } = req.query;
const data = await tmdbService.fetchTrending(type, page || 1);
if (!data)
return res.status(500).json({ message: 'Failed to fetch trending data' });
return res.status(500).json({ message: "Failed to fetch trending data" });
res.status(200).json(data);
});
@@ -155,7 +214,7 @@ class EntryController {
const { page } = req.query;
const data = await tmdbService.fetchPopular(type, page || 1);
if (!data)
return res.status(500).json({ message: 'Failed to fetch popular data' });
return res.status(500).json({ message: "Failed to fetch popular data" });
res.status(200).json(data);
});
@@ -163,10 +222,10 @@ class EntryController {
getTmdbSearch = asyncWrapper(async (req, res) => {
const { query, page } = req.query;
if (!query)
return res.status(400).json({ message: 'Query parameter is required' });
return res.status(400).json({ message: "Query parameter is required" });
const data = await tmdbService.searchMulti(query, page || 1);
if (!data)
return res.status(500).json({ message: 'Failed to search TMDB' });
return res.status(500).json({ message: "Failed to search TMDB" });
res.status(200).json(data);
});
@@ -178,7 +237,7 @@ class EntryController {
if (!data)
return res
.status(500)
.json({ message: 'Failed to fetch top rated data' });
.json({ message: "Failed to fetch top rated data" });
res.status(200).json(data);
});
@@ -187,17 +246,17 @@ class EntryController {
const { page } = req.query;
const data = await tmdbService.fetchUpcoming(page || 1);
if (!data)
return res.status(500).json({ message: 'Failed to fetch upcoming data' });
return res.status(500).json({ message: "Failed to fetch upcoming data" });
res.status(200).json(data);
});
// * GET - TMDB PREVIEW (fetch details without saving to library)
getTmdbPreview = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params;
const is_tvserie = type === 'tv';
const is_tvserie = type === "tv";
const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie);
if (!data)
return res.status(404).json({ message: 'Entry not found on TMDB' });
return res.status(404).json({ message: "Entry not found on TMDB" });
// Fetch credits in parallel
const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie);
@@ -208,7 +267,7 @@ class EntryController {
for (const c of creditsData.cast) {
credits.push({
id: c.credit_id || c.id,
cast_type: 'cast',
cast_type: "cast",
character: is_tvserie
? c.roles?.[0]?.character || c.character || null
: c.character || null,
@@ -223,6 +282,59 @@ class EntryController {
}
}
// Directors, so the preview page can show "Directed by"
for (const c of creditsData?.crew ?? []) {
const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job];
if (!jobs.includes("Director")) continue;
credits.push({
id: c.credit_id || c.jobs?.[0]?.credit_id || "crew-" + c.id,
cast_type: "crew",
job: "Director",
department: "Directing",
character: null,
people_id: c.id,
people: {
id: c.id,
name: c.name || c.original_name,
profile_path: c.profile_path,
tmdb_id: c.id,
},
});
}
// Same shape as a library entry, so the details page can render either
const entry = {
id: 0,
...mapEntryFields(data),
is_tvseries: is_tvserie,
isInLibrary: false,
entryIds: { tmdb_id: data.id, ...mapEntryIds(data) },
entryRatings: {
user_rating: null,
imdb_rating: null,
rotten_tomatoes_rating: null,
...mapEntryRatings(data),
},
genres: data.genres || [],
networks: (data.networks || []).map((n) => ({
id: n.id,
name: n.name,
origin_country: n.origin_country || null,
logo_path: n.logo_path || null,
homepage: null,
})),
};
const seasons = (data.seasons || []).map((s) => ({
id: s.id,
name: s.name,
season_number: s.season_number,
episode_count: s.episode_count,
air_date: s.air_date,
poster_path: s.poster_path,
overview: s.overview,
tmdb_rating: s.vote_average,
}));
// Normalize to a shape similar to our Entry model
const preview = {
tmdb_id: data.id,
@@ -248,6 +360,8 @@ class EntryController {
homepage: data.homepage || null,
imdb_id: data.imdb_id || data.external_ids?.imdb_id || null,
credits,
entry,
seasons,
};
res.status(200).json(preview);
+28 -1
View File
@@ -78,6 +78,33 @@ class MaintenanceController {
const result = await _maintenanceService.fixImpossibleSeenDates();
return res.status(200).json(result);
}
parseHours(value) {
const hours = Number(value ?? 24);
return Number.isFinite(hours) && hours >= 0 ? hours : 24;
}
module.exports = new MaintenanceController();
async getStaleEntries(req, res) {
const hours = maintenanceController.parseHours(req.query.hours);
const entries = await _maintenanceService.getStaleEntries(hours);
return res.status(200).json({
count: entries.length,
hours,
job: _maintenanceService.getStaleRefreshStatus(),
});
}
async startStaleRefresh(req, res) {
const hours = maintenanceController.parseHours(req.query.hours);
const result = await _maintenanceService.startStaleRefresh(hours);
return res.status(result.alreadyRunning ? 409 : 202).json(result);
}
async cancelStaleRefresh(req, res) {
return res.status(200).json(_maintenanceService.cancelStaleRefresh());
}
}
const maintenanceController = new MaintenanceController();
module.exports = maintenanceController;
+19 -7
View File
@@ -4,6 +4,10 @@ const Season = require("../models/Season");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const { fetchSeasonData } = require("../services/tmdbService");
const {
mapSeasonFields,
mapEpisodeFields,
} = require("../mappers/entryMapper.js");
class SeasonController {
constructor() {
@@ -117,14 +121,22 @@ class SeasonController {
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,
await season.update(mapSeasonFields(seasonData));
// Keep the season's episodes in sync too (guest stars, crew, votes…)
for (const episode of seasonData.episodes ?? []) {
const existingEpisode = await Episode.findOne({
where: { tmdb_id: episode.id },
});
if (existingEpisode) {
await existingEpisode.update(mapEpisodeFields(episode));
} else {
await Episode.create({
...mapEpisodeFields(episode),
season_id: season.id,
});
}
}
const refreshedSeason = await Season.findByPk(req.params.id);
res.send(refreshedSeason);
+263
View File
@@ -0,0 +1,263 @@
/**
* Maps TMDB responses (from tmdbService.fetchEntryData / fetchSeasonData) to
* the column values we store. Used by entry creation, the entry refresh and
* the legacy importer so every path saves the same fields.
*/
const CERTIFICATION_REGIONS = ["US", "GB"];
const MAX_VIDEOS = 12;
const MAX_KEYWORDS = 30;
const MAX_EPISODE_CREW = 15;
const MAX_GUEST_STARS = 25;
const pick = (obj, keys) =>
obj ? Object.fromEntries(keys.map((k) => [k, obj[k] ?? null])) : null;
function isTv(data) {
return data.first_air_date !== undefined || data.name !== undefined;
}
/** First non-empty certification, preferring US, then the origin country. */
function mapCertification(data) {
const regions = [...CERTIFICATION_REGIONS, ...(data.origin_country ?? [])];
if (data.content_ratings) {
const results = data.content_ratings.results ?? [];
for (const region of regions) {
const rating = results.find((r) => r.iso_3166_1 === region)?.rating;
if (rating) return rating;
}
return results.find((r) => r.rating)?.rating ?? null;
}
if (data.release_dates) {
const results = data.release_dates.results ?? [];
const certFor = (r) => {
const dates = (r?.release_dates ?? []).filter((d) => d.certification);
// Prefer theatrical (3), then limited (2), then anything
const byType =
dates.find((d) => d.type === 3) ??
dates.find((d) => d.type === 2) ??
dates[0];
return byType?.certification || null;
};
for (const region of regions) {
const cert = certFor(results.find((r) => r.iso_3166_1 === region));
if (cert) return cert;
}
}
return null;
}
function mapVideos(videos) {
const results = (videos?.results ?? []).filter(
(v) => v.site === "YouTube" && v.key,
);
const rank = (v) =>
(v.type === "Trailer" ? 0 : v.type === "Teaser" ? 1 : 2) +
(v.official ? 0 : 3);
return results
.sort(
(a, b) =>
rank(a) - rank(b) ||
new Date(b.published_at) - new Date(a.published_at),
)
.slice(0, MAX_VIDEOS)
.map((v) =>
pick(v, ["key", "name", "type", "official", "published_at", "iso_639_1"]),
);
}
/** Keeps per-country provider lists, trimmed to what the UI needs. */
function mapWatchProviders(providers) {
const results = providers?.results;
if (!results) return null;
const trimList = (list) =>
list?.map((p) =>
pick(p, [
"provider_id",
"provider_name",
"logo_path",
"display_priority",
]),
);
return Object.fromEntries(
Object.entries(results).map(([country, info]) => [
country,
{
link: info.link ?? null,
flatrate: trimList(info.flatrate),
free: trimList(info.free),
ads: trimList(info.ads),
rent: trimList(info.rent),
buy: trimList(info.buy),
},
]),
);
}
function mapEpisodeSummary(episode) {
return pick(episode, [
"id",
"name",
"season_number",
"episode_number",
"air_date",
"episode_type",
"runtime",
"still_path",
]);
}
/** Entry table columns. */
function mapEntryFields(data) {
const tv = isTv(data);
const keywords = (data.keywords?.keywords ?? data.keywords?.results ?? [])
.slice(0, MAX_KEYWORDS)
.map((k) => k.name);
const alternativeTitles = (
data.alternative_titles?.titles ??
data.alternative_titles?.results ??
[]
).map((t) => pick(t, ["iso_3166_1", "title", "type"]));
return {
title: data.title || data.name,
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date || null,
release_status: data.status,
runtime:
data.runtime ||
data.episode_run_time?.[0] ||
data.last_episode_to_air?.runtime ||
null,
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries?.[0]?.name ?? null,
status: data.status,
certification: mapCertification(data),
network_studio:
data.networks?.[0]?.name ?? data.production_companies?.[0]?.name ?? null,
adult: !!data.adult,
tmdb_popularity: data.popularity ?? null,
original_language: data.original_language ?? null,
origin_country: data.origin_country ?? null,
spoken_languages:
data.spoken_languages?.map((l) =>
pick(l, ["iso_639_1", "english_name", "name"]),
) ?? null,
production_countries: data.production_countries ?? null,
production_companies:
data.production_companies?.map((c) =>
pick(c, ["id", "name", "logo_path", "origin_country"]),
) ?? null,
homepage: data.homepage || null,
budget: tv ? null : data.budget || null,
revenue: tv ? null : data.revenue || null,
keywords,
tmdb_videos: mapVideos(data.videos),
watch_providers: mapWatchProviders(data["watch/providers"]),
alternative_titles: alternativeTitles,
tv_type: tv ? (data.type ?? null) : null,
created_by: tv
? (data.created_by ?? []).map((p) =>
pick(p, ["id", "name", "profile_path"]),
)
: null,
number_of_seasons: tv ? (data.number_of_seasons ?? null) : null,
number_of_episodes: tv ? (data.number_of_episodes ?? null) : null,
last_air_date: tv ? (data.last_air_date ?? null) : null,
in_production: tv ? (data.in_production ?? null) : null,
next_episode_to_air: tv
? mapEpisodeSummary(data.next_episode_to_air)
: null,
last_episode_to_air: tv
? mapEpisodeSummary(data.last_episode_to_air)
: null,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date(),
};
}
/** EntryId table columns. TV details have no imdb_id; it's in external_ids. */
function mapEntryIds(data) {
const ext = data.external_ids ?? {};
return {
imdb_id: data.imdb_id || ext.imdb_id || null,
tvdb_id: ext.tvdb_id != null ? String(ext.tvdb_id) : null,
wikidata_id: ext.wikidata_id || null,
facebook_id: ext.facebook_id || null,
instagram_id: ext.instagram_id || null,
twitter_id: ext.twitter_id || null,
};
}
/** EntryRating TMDB columns (user/imdb/rt ratings are left untouched). */
function mapEntryRatings(data) {
return {
tmdb_rating: data.vote_average ?? null,
tmdb_vote_count: data.vote_count ?? null,
};
}
/** Season table columns from a season details response. */
function mapSeasonFields(seasonData) {
return {
tmdb_id: seasonData.id,
tvdb_id:
seasonData.external_ids?.tvdb_id != null
? String(seasonData.external_ids.tvdb_id)
: null,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes?.length ?? 0,
air_date: seasonData.air_date,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
};
}
/** Episode table columns from an entry of seasonData.episodes. */
function mapEpisodeFields(episode) {
return {
tmdb_id: episode.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
tmdb_vote_count: episode.vote_count ?? null,
production_code: episode.production_code || null,
crew: (episode.crew ?? [])
.filter((c) => ["Directing", "Writing"].includes(c.department))
.slice(0, MAX_EPISODE_CREW)
.map((c) => pick(c, ["id", "name", "job", "department", "profile_path"])),
guest_stars: (episode.guest_stars ?? [])
.slice(0, MAX_GUEST_STARS)
.map((g) =>
pick(g, ["id", "name", "character", "profile_path", "order"]),
),
still_path: episode.still_path,
};
}
module.exports = {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
};
+62 -21
View File
@@ -1,27 +1,54 @@
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const Entry = sequelize.define('entry', {
const Entry = sequelize.define("entry", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
title: { type: DataTypes.STRING(500) },
original_title: { type: DataTypes.STRING(100), field: 'original_title' },
release_date: { type: DataTypes.DATE, field: 'release_date' },
release_status: { type: DataTypes.STRING(50), field: 'release_status' },
original_title: { type: DataTypes.STRING(100), field: "original_title" },
release_date: { type: DataTypes.DATE, field: "release_date" },
release_status: { type: DataTypes.STRING(50), field: "release_status" },
runtime: { type: DataTypes.INTEGER },
tagline: { type: DataTypes.STRING(200) },
storyline: { type: DataTypes.STRING(3000) },
country: { type: DataTypes.STRING(30) },
certification: { type: DataTypes.INTEGER },
network_studio: { type: DataTypes.STRING(40), field: 'network_studio' },
collection_id: { type: DataTypes.INTEGER, field: 'collection_id' },
max_cast: { type: DataTypes.INTEGER, field: 'max_cast', defaultValue: 10 },
certification: { type: DataTypes.STRING(20) },
network_studio: { type: DataTypes.STRING(100), field: "network_studio" },
// ? TMDB details
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
tmdb_popularity: { type: DataTypes.FLOAT, field: "tmdb_popularity" },
original_language: { type: DataTypes.STRING(10), field: "original_language" },
origin_country: { type: DataTypes.JSON, field: "origin_country" },
spoken_languages: { type: DataTypes.JSON, field: "spoken_languages" },
production_countries: { type: DataTypes.JSON, field: "production_countries" },
production_companies: { type: DataTypes.JSON, field: "production_companies" },
homepage: { type: DataTypes.STRING(500) },
budget: { type: DataTypes.BIGINT },
revenue: { type: DataTypes.BIGINT },
keywords: { type: DataTypes.JSON },
tmdb_videos: { type: DataTypes.JSON, field: "tmdb_videos" },
watch_providers: { type: DataTypes.JSON, field: "watch_providers" },
alternative_titles: { type: DataTypes.JSON, field: "alternative_titles" },
// ? TV-only TMDB details
tv_type: { type: DataTypes.STRING(30), field: "tv_type" },
created_by: { type: DataTypes.JSON, field: "created_by" },
number_of_seasons: { type: DataTypes.INTEGER, field: "number_of_seasons" },
number_of_episodes: { type: DataTypes.INTEGER, field: "number_of_episodes" },
last_air_date: { type: DataTypes.DATEONLY, field: "last_air_date" },
in_production: { type: DataTypes.BOOLEAN, field: "in_production" },
next_episode_to_air: { type: DataTypes.JSON, field: "next_episode_to_air" },
last_episode_to_air: { type: DataTypes.JSON, field: "last_episode_to_air" },
collection_id: { type: DataTypes.INTEGER, field: "collection_id" },
max_cast: { type: DataTypes.INTEGER, field: "max_cast", defaultValue: 10 },
credit_fetched: {
type: DataTypes.BOOLEAN,
defaultValue: false,
field: 'credit_fetched',
field: "credit_fetched",
},
watchlist: { type: DataTypes.BOOLEAN, defaultValue: false },
@@ -30,35 +57,49 @@ const Entry = sequelize.define('entry', {
showInCalendar: {
type: DataTypes.BOOLEAN,
defaultValue: true,
field: 'show_in_calendar',
field: "show_in_calendar",
},
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: 'auto_sync' },
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: "auto_sync" },
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) },
poster_path: { type: DataTypes.STRING(200), field: 'poster_path' },
banner_path: { type: DataTypes.STRING(200), field: 'banner_path' },
poster_path: { type: DataTypes.STRING(200), field: "poster_path" },
banner_path: { type: DataTypes.STRING(200), field: "banner_path" },
date_first_seen: { type: DataTypes.DATEONLY, field: 'date_first_seen' },
date_last_seen: { type: DataTypes.DATEONLY, field: 'date_last_seen' },
date_first_seen: { type: DataTypes.DATEONLY, field: "date_first_seen" },
date_last_seen: { type: DataTypes.DATEONLY, field: "date_last_seen" },
last_fetch: { type: DataTypes.DATEONLY },
last_fetch: { type: DataTypes.DATE },
entry_sync_status: {
type: DataTypes.STRING(50),
field: 'entry_sync_status',
field: "entry_sync_status",
allowNull: true,
},
director: { type: DataTypes.STRING(200), allowNull: true },
watch_status: {
type: DataTypes.STRING(20),
field: 'watch_status',
field: "watch_status",
allowNull: true,
defaultValue: null,
},
});
// Large JSON columns only needed on the details page; left out of list queries.
Entry.DETAIL_ONLY_ATTRIBUTES = [
"keywords",
"tmdb_videos",
"watch_providers",
"alternative_titles",
"production_companies",
"spoken_languages",
"production_countries",
"created_by",
"next_episode_to_air",
"last_episode_to_air",
];
module.exports = Entry;
+4
View File
@@ -15,6 +15,10 @@ const EntryId = sequelize.define(
tmdb_id: { type: DataTypes.STRING(30) },
imdb_id: { type: DataTypes.STRING(30) },
tvdb_id: { type: DataTypes.STRING(30) },
wikidata_id: { type: DataTypes.STRING(30) },
facebook_id: { type: DataTypes.STRING(100) },
instagram_id: { type: DataTypes.STRING(100) },
twitter_id: { type: DataTypes.STRING(100) },
},
{
timestamps: false,
+1
View File
@@ -14,6 +14,7 @@ const EntryRating = sequelize.define(
},
user_rating: { type: DataTypes.FLOAT },
tmdb_rating: { type: DataTypes.FLOAT },
tmdb_vote_count: { type: DataTypes.INTEGER },
imdb_rating: { type: DataTypes.FLOAT },
rotten_tomatoes_rating: { type: DataTypes.FLOAT },
},
+5
View File
@@ -25,6 +25,11 @@ const Episode = sequelize.define("episode", {
user_rating: { type: DataTypes.FLOAT },
tmdb_rating: { type: DataTypes.FLOAT },
tmdb_vote_count: { type: DataTypes.INTEGER },
production_code: { type: DataTypes.STRING(50) },
crew: { type: DataTypes.JSON },
guest_stars: { type: DataTypes.JSON },
still_path: { type: DataTypes.STRING(200) },
+2
View File
@@ -9,6 +9,8 @@ const Media = sequelize.define("media", {
type: { type: DataTypes.STRING(50) },
path: { type: DataTypes.STRING(200) },
// TMDB file_path this image was downloaded from (null for custom uploads)
tmdbPath: { type: DataTypes.STRING(200), field: "tmdb_path" },
isLocal: { type: DataTypes.BOOLEAN, field: "is_local" },
isSelected: {
+1 -1
View File
@@ -4,7 +4,7 @@ const sequelize = require("../config/database");
const Network = sequelize.define("network", {
id: { type: DataTypes.INTEGER, primaryKey: true },
name: { type: DataTypes.STRING(30) },
name: { type: DataTypes.STRING(100) },
originCountry: { type: DataTypes.STRING(100), field: "origin_country" },
homepage: { type: DataTypes.STRING(100), field: "homepage" },
+1
View File
@@ -7,6 +7,7 @@ const People = sequelize.define("peoples", {
tmdb_id: { type: DataTypes.STRING(100) },
name: { type: DataTypes.STRING(100) },
original_name: { type: DataTypes.STRING(200) },
birthday: { type: DataTypes.DATEONLY },
deathday: { type: DataTypes.DATEONLY, allowNull: true },
gender: { type: DataTypes.INTEGER },
+1
View File
@@ -6,6 +6,7 @@ const Season = sequelize.define("season", {
tmdb_id: { type: DataTypes.STRING(30) },
imdb_id: { type: DataTypes.STRING(30) },
tvdb_id: { type: DataTypes.STRING(30) },
entry_id: {
type: DataTypes.INTEGER,
+11
View File
@@ -18,6 +18,11 @@ entryRouter.get("/tmdb/top-rated/:type", entryController.getTmdbTopRated);
entryRouter.get("/tmdb/upcoming/movie", entryController.getTmdbUpcoming);
entryRouter.get("/tmdb/search", entryController.getTmdbSearch);
entryRouter.get("/tmdb/preview/:type/:tmdbId", entryController.getTmdbPreview);
entryRouter.get(
"/tmdb/recommendations/:type/:tmdbId",
entryController.getTmdbRecommendations,
);
entryRouter.get("/tmdb/artwork/:type/:tmdbId", entryController.getTmdbArtwork);
entryRouter.get("/sync-series", entryController.syncSeries);
@@ -31,6 +36,12 @@ entryRouter.delete("/:id", entryController.deleteEntry);
entryRouter.get("/:id/seasons", entryController.getEntrySeasons);
entryRouter.get("/:id/credits", entryController.getEntryCredits);
entryRouter.get(
"/:id/recommendations",
entryController.getEntryRecommendations,
);
entryRouter.get("/:id/artwork", entryController.getEntryArtwork);
entryRouter.post("/:id/artwork", entryController.addEntryArtwork);
entryRouter.put("/:id/refresh", entryController.refrechEntry);
entryRouter.put("/:id/fetch-collection", entryController.fetchEntryCollection);
+24
View File
@@ -0,0 +1,24 @@
const express = require("express");
const historyRouter = express.Router();
const historyService = require("../services/historyService");
const asyncWrapper = require("../utils/asyncWrapper");
// ! /history
// * GET - Years that have watches, with movie/episode counts
historyRouter.get(
"/years",
asyncWrapper(async (req, res) => {
res.status(200).json(await historyService.getYears());
}),
);
// * GET - Every movie/episode watch in a year (newest first)
historyRouter.get(
"/:year",
asyncWrapper(async (req, res) => {
res.status(200).json(await historyService.getYear(req.params.year));
}),
);
module.exports = historyRouter;
+15
View File
@@ -76,4 +76,19 @@ maintenanceRouter.post(
maintenanceController.fixImpossibleSeenDates,
);
// * GET - Count of entries not refreshed in the last ?hours=24 + job status
maintenanceRouter.get("/stale-entries", maintenanceController.getStaleEntries);
// * POST - Start refreshing stale entries in the background (?hours=24)
maintenanceRouter.post(
"/stale-entries/refresh",
maintenanceController.startStaleRefresh,
);
// * DELETE - Cancel the running stale refresh
maintenanceRouter.delete(
"/stale-entries/refresh",
maintenanceController.cancelStaleRefresh,
);
module.exports = maintenanceRouter;
+2
View File
@@ -17,6 +17,7 @@ const authRouter = require("./auth.routes");
const watchBuddyRouter = require("./watch-buddy.routes");
const homepageIntegrationRouter = require("./homepage-integration.routes");
const videoRouter = require("./video.routes");
const historyRouter = require("./history.routes");
const router = express.Router();
router.use("/auth", authRouter);
@@ -32,6 +33,7 @@ router.use("/episode-seen", episodeSeenRouter);
router.use("/import", importRouter);
router.use("/statistics", statisticsRouter);
router.use("/history", historyRouter);
router.use("/settings", settingsRouter);
router.use("/maintenance", maintenanceRouter);
router.use("/ping", pingRouter);
+3 -1
View File
@@ -21,6 +21,7 @@ process.on("uncaughtException", (error) => {
const relations = require("./config/relations.js");
const sequelizeHooks = require("./config/sequelizeHooks.js");
const { initializeData } = require("./config/dataInitializer.js");
const { runMigrations } = require("./config/migrations.js");
const killerRouter = require("./routes/killer.routes.js");
const errorHandler = require("./middleware/errorHandler");
const authMiddleware = require("./middleware/authMiddleware");
@@ -68,8 +69,9 @@ console.log(`Syncing database schema...`);
sequelize
// .sync({force: true}) // will drop all tables and recreate them.
.sync({ alter: doUpdate }) // will attempt to automatically alter tables to fit the model definitions.
.then((result) => {
.then(async (result) => {
console.log(`Database schema synced.`);
await runMigrations();
initializeData();
app.listen(PORT, () => {
+207
View File
@@ -0,0 +1,207 @@
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const Media = require("../models/Media");
const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError");
const InternalServerError = require("../errors/InternalServerError");
const configService = require("./configService");
const tmdbService = require("./tmdbService");
const mediaDownloaderService = require("./mediaDownloaderService");
const mediaOptimizerService = require("./mediaOptimizerService");
const { logToFile } = require("./logService");
// TMDB images response key → our Media.type
const ARTWORK_TYPES = {
posters: "poster",
backdrops: "backdrop",
logos: "logo",
};
const MEDIA_TYPES = Object.values(ARTWORK_TYPES);
function mapTmdbImage(image) {
return {
file_path: image.file_path,
width: image.width,
height: image.height,
aspect_ratio: image.aspect_ratio,
language: image.iso_639_1 || null,
vote_average: image.vote_average ?? 0,
vote_count: image.vote_count ?? 0,
};
}
function sortByVotes(a, b) {
return b.vote_count - a.vote_count || b.vote_average - a.vote_average;
}
/** TMDB artwork grouped by type, best-voted first. */
async function fetchTmdbArtwork(tmdbId, isTv) {
const data = await tmdbService.fetchEntryMedia(tmdbId, isTv);
if (!data) {
throw new InternalServerError("Couldn't fetch artwork from TMDB");
}
const result = {};
for (const [tmdbKey, type] of Object.entries(ARTWORK_TYPES)) {
result[`${type}s`] = (data[tmdbKey] ?? [])
.map(mapTmdbImage)
.sort(sortByVotes);
}
return result;
}
class ArtworkService {
constructor() {
if (!ArtworkService.instance) {
ArtworkService.instance = this;
}
return ArtworkService.instance;
}
/** Artwork for an entry that is not in the library (TMDB only). */
async getTmdbArtwork(type, tmdbId) {
const result = await fetchTmdbArtwork(tmdbId, type === "tv");
for (const key of Object.keys(result)) {
result[key] = result[key].map((img) => ({ ...img, in_library: false }));
}
return result;
}
/**
* TMDB artwork merged with the entry's media table. TMDB images we already
* have are flagged `in_library` with their media id; local images that
* don't match a TMDB image (custom uploads, older downloads) are appended.
*/
async getEntryArtwork(entryId) {
const entry = await Entry.findByPk(entryId, {
attributes: ["id", "is_tvseries"],
include: [{ model: EntryId, as: "entryId" }],
});
if (!entry) throw new NotFoundError("Entry not found");
const medias = await Media.findAll({
where: { mediaable: "entry", mediaableId: entryId, type: MEDIA_TYPES },
order: [["id", "ASC"]],
});
const tmdbId = entry.entryId?.tmdb_id;
const tmdb = tmdbId
? await fetchTmdbArtwork(tmdbId, entry.is_tvseries)
: { posters: [], backdrops: [], logos: [] };
const result = {};
for (const type of MEDIA_TYPES) {
const key = `${type}s`;
const ofType = medias.filter((m) => m.type === type);
const byTmdbPath = new Map(
ofType.filter((m) => m.tmdbPath).map((m) => [m.tmdbPath, m]),
);
const merged = tmdb[key].map((img) => {
const media = byTmdbPath.get(img.file_path);
return {
...img,
in_library: !!media,
media_id: media?.id ?? null,
media_path: media?.path ?? null,
is_selected: !!media?.isSelected,
};
});
const localOnly = ofType
.filter(
(m) =>
!m.tmdbPath || !tmdb[key].some((i) => i.file_path === m.tmdbPath),
)
.map((m) => ({
file_path: null,
width: null,
height: null,
aspect_ratio: null,
language: null,
vote_average: 0,
vote_count: 0,
in_library: true,
media_id: m.id,
media_path: m.path,
is_selected: !!m.isSelected,
is_custom: !!m.isCustom,
}));
// Library images first so what you already have is easy to find
result[key] = [
...localOnly,
...merged.filter((i) => i.in_library),
...merged.filter((i) => !i.in_library),
];
}
return result;
}
/**
* Downloads a TMDB image into the entry's media table. If the entry has no
* selected image of that type yet, the new one becomes selected.
* @param {number} entryId
* @param {{type: "poster"|"backdrop"|"logo", file_path: string}} data
*/
async addEntryArtwork(entryId, { type, file_path }) {
if (!MEDIA_TYPES.includes(type)) {
throw new BadRequestError(`Invalid artwork type: ${type}`);
}
if (!file_path || !/^\/[\w.-]+$/.test(file_path)) {
throw new BadRequestError("Invalid TMDB file path");
}
const entry = await Entry.findByPk(entryId, { attributes: ["id"] });
if (!entry) throw new NotFoundError("Entry not found");
const where = { mediaable: "entry", mediaableId: entryId, type };
const existing = await Media.findOne({
where: { ...where, tmdbPath: file_path },
});
if (existing) return existing;
configService.createMediaFolders();
const extension = file_path.split(".").pop();
const filename = `${uuidv4()}.${extension}`;
const dir = path.join(
configService.getSettings().userDataPath,
"images",
"entries",
`${type}s`,
);
await mediaDownloaderService.downloadImage(
`https://image.tmdb.org/t/p/original${file_path}`,
path.join(dir, filename),
);
const hasSelected = await Media.count({
where: { ...where, isSelected: true },
});
const media = await Media.create({
...where,
path: filename,
tmdbPath: file_path,
isLocal: true,
isSelected: hasSelected === 0,
isCustom: false,
});
mediaOptimizerService
.doGeneratePreview("entries", `${type}s`, filename)
.catch((err) =>
logToFile(`Artwork | Error generating preview for ${filename}: ${err}`),
);
logToFile(`Artwork | Added ${type} ${file_path} to entry ${entryId}`);
return media;
}
}
module.exports = new ArtworkService();
+1
View File
@@ -98,6 +98,7 @@ class CollectionManager {
mediaableId: collection.id,
type: image.type,
path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true,
isSelected: true,
});
+39 -97
View File
@@ -28,6 +28,13 @@ const entryService = require("./entryService");
const mediaManager = require("./mediaManager.js");
const networkService = require("./networkService.js");
const InternalServerError = require("../errors/InternalServerError.js");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
} = require("../mappers/entryMapper.js");
const _collectionManager = collectionManager;
const _entryService = entryService;
@@ -107,79 +114,50 @@ class EntryManager {
}
// ! the refrech logic
let newData = {
title: entryData.title || entryData.name,
original_title: entryData.original_title || entryData.original_name,
release_date: entryData.release_date || entryData.first_air_date,
release_status: entryData.status,
runtime: entryData.runtime || null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
country:
entryData.production_countries.length > 0
? entryData.production_countries[0].name
: null,
status: entryData.status,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date(),
};
const savedEntry = await _entryService.updateEntryById(id, newData, false);
const savedEntry = await _entryService.updateEntryById(
id,
mapEntryFields(entryData),
false,
);
// * updating ids
// TODO: get more ids
await oldEntry.entryId.update({
imdb_id: entryData.imdb_id,
});
await oldEntry.entryId.update(mapEntryIds(entryData));
// * updating ratings
await oldEntry.entryRating.update({
tmdb_rating: entryData.vote_average,
});
await oldEntry.entryRating.update(mapEntryRatings(entryData));
// * updating genres
// * syncing genres (add new ones, drop ones TMDB no longer lists)
const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
entryData.genres.forEach(async (genre) => {
// if the entry already has this genre then skip
if (currentGenresIds.includes(genre.id)) return;
// otherwise assign the genre to the entry
await EntryGenre.create({
genre_id: genre.id,
entry_id: savedEntry.id,
});
const newGenresIds = entryData.genres.map((genre) => genre.id);
for (const genreId of newGenresIds) {
if (currentGenresIds.includes(genreId)) continue;
await EntryGenre.create({ genre_id: genreId, entry_id: savedEntry.id });
}
const removedGenresIds = currentGenresIds.filter(
(genreId) => !newGenresIds.includes(genreId),
);
if (removedGenresIds.length) {
await EntryGenre.destroy({
where: { entry_id: savedEntry.id, genre_id: removedGenresIds },
});
}
// * networks
// * syncing networks (also refreshes each network's name/logo/country)
if (entryData.networks) {
const oldNetworksIds = oldEntry.networks.map((network) => network.id);
const networks = [];
for (const networkData of entryData.networks) {
// If the entry already has this network, skip it
if (oldNetworksIds.includes(networkData.id)) continue;
// Create or update the network
const [oldNetwork, newNetwork] =
const [network] =
await _networkService.createOrUpdateNetwork(networkData);
let network = oldNetwork || newNetwork;
if (!network) {
throw new NotFoundError("Network not found");
}
// Associate the new network with the entry
await oldEntry.addNetwork(network);
networks.push(network);
}
await oldEntry.setNetworks(networks);
}
// * For TV-Series (Seasons & Episodes)
if (oldEntry.is_tvseries) {
// ? Only refrech if the series's status is not 'Ended'
// ? and atleast 48 hours has passed
// * Update or insert seasons for the entry
for (const season of entryData.seasons) {
// fetch new season data from tmdb
@@ -187,6 +165,7 @@ class EntryManager {
entryData.id,
season.season_number,
);
if (!seasonData) continue;
// Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({
@@ -198,31 +177,12 @@ class EntryManager {
// If the season exists, update it; otherwise, create a new season
if (existingSeason) {
// Update existing season data
existingSeason.tmdb_id = seasonData.id;
existingSeason.name = seasonData.name;
existingSeason.overview = seasonData.overview;
existingSeason.episode_count = seasonData.episodes.length;
existingSeason.air_date = seasonData.air_date;
existingSeason.tmdb_rating = seasonData.vote_average;
existingSeason.poster_path = seasonData.poster_path;
existingSeason.banner_path = null;
// Save the updated season
await existingSeason.save();
await existingSeason.update(mapSeasonFields(seasonData));
} else {
// Create a new season
existingSeason = await Season.create({
tmdb_id: seasonData.id,
...mapSeasonFields(seasonData),
entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
}
@@ -242,31 +202,11 @@ class EntryManager {
// If the episode exists, update it; otherwise, create a new episode
if (existingEpisode) {
// Update existing episode data
existingEpisode.tmdb_id = episode.tmdb_id;
existingEpisode.name = episode.name;
existingEpisode.overview = episode.overview;
existingEpisode.episode_type = episode.episode_type;
existingEpisode.runtime = episode.runtime;
existingEpisode.air_date = episode.air_date;
existingEpisode.tmdb_rating = episode.vote_average;
existingEpisode.still_path = episode.still_path;
// Updated episode
await existingEpisode.save();
await existingEpisode.update(mapEpisodeFields(episode));
} else {
// Create a new episode
existingEpisode = await Episode.create({
tmdb_id: episode.id,
...mapEpisodeFields(episode),
season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
}
@@ -315,6 +255,7 @@ class EntryManager {
return {
tmdb_id: credit.id,
name: credit.name,
original_name: credit.original_name || null,
gender: credit.gender || null,
popularity: credit.popularity,
known_for_department: credit.known_for_department || null,
@@ -561,6 +502,7 @@ class EntryManager {
mediaableId: oldEntry.id,
type: image.type,
path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true,
isSelected: true,
});
+18 -49
View File
@@ -20,6 +20,13 @@ const networkService = require("./networkService.js");
const Cast = require("../models/Credit.js");
const People = require("../models/People.js");
const Credit = require("../models/Credit.js");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
} = require("../mappers/entryMapper.js");
const _mediaManager = mediaManager;
const _mediaOptimizerService = mediaOptimizerService;
@@ -35,6 +42,7 @@ class EntryService {
async getAllEntries() {
const entries = await Entry.findAll({
attributes: { exclude: Entry.DETAIL_ONLY_ATTRIBUTES },
include: [
{ model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" },
@@ -154,40 +162,20 @@ class EntryService {
console.log("entryService > createEntry > is_tvseries: ", is_tvseries);
let movie = Entry.build({
title: data.title || data.name,
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date,
release_status: data.status,
runtime: data.runtime || null,
tagline: data.tagline || null,
storyline: data.overview,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
...mapEntryFields(data),
is_tvseries: is_tvseries,
watchlist: true,
status: data.status,
genres: data.genre_ids,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date(),
});
let savedEntry = await movie.save();
console.log("entryService > createEntry > savedEntry: ", savedEntry);
console.log("entryService > createEntry > savedEntry: ", savedEntry.id);
// ? ids
await EntryId.create({
entry_id: savedEntry.id,
tmdb_id: data.id,
imdb_id: data.imdb_id,
...mapEntryIds(data),
});
// ? genres
@@ -218,7 +206,7 @@ class EntryService {
await EntryRating.create({
entry_id: savedEntry.id,
user_rating: 0,
tmdb_rating: data.vote_average,
...mapEntryRatings(data),
});
// ! seasons & episodes for tv series
@@ -227,21 +215,12 @@ class EntryService {
let seasons = [];
for (const season of data.seasons) {
let seasonData = await fetchSeasonData(data.id, season.season_number);
if (!seasonData) continue;
const savedSeason = await Season.create({
tmdb_id: seasonData.id,
...mapSeasonFields(seasonData),
entry_id: savedEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
@@ -251,20 +230,8 @@ class EntryService {
let episodes = [];
for (const episode of seasonData.episodes) {
const savedEpisode = await Episode.create({
tmdb_id: episode.id,
...mapEpisodeFields(episode),
season_id: savedSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
episodes.push(savedEpisode);
@@ -309,6 +276,7 @@ class EntryService {
return {
tmdb_id: credit.id,
name: credit.name,
original_name: credit.original_name || null,
gender: credit.gender || null,
popularity: credit.popularity,
known_for_department: credit.known_for_department || null,
@@ -407,6 +375,7 @@ class EntryService {
mediaableId: savedEntry.id,
type: image.type,
path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true,
isSelected: true,
});
+208
View File
@@ -0,0 +1,208 @@
const { Op } = require("sequelize");
const sequelize = require("../config/database");
const Entry = require("../models/Entry");
const EntryRating = require("../models/EntryRating");
const EntrySeen = require("../models/EntrySeen");
const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen");
const Genre = require("../models/Genre");
const Media = require("../models/Media");
const Network = require("../models/Network");
const Season = require("../models/Season");
const WatchBuddy = require("../models/WatchBuddy");
const BadRequestError = require("../errors/BadRequestError");
const ENTRY_ATTRIBUTES = [
"id",
"title",
"is_tvseries",
"poster_path",
"banner_path",
"runtime",
"release_date",
"original_language",
];
const BUDDY_INCLUDE = {
model: WatchBuddy,
as: "buddies",
attributes: ["id", "name"],
through: { attributes: [] },
};
class HistoryService {
constructor() {
if (!HistoryService.instance) {
HistoryService.instance = this;
}
return HistoryService.instance;
}
/** Years that have watches, newest first, with movie/episode counts. */
async getYears() {
const [rows] = await sequelize.query(`
SELECT y AS year, SUM(movies) AS movies, SUM(episodes) AS episodes FROM (
SELECT YEAR(date_seen) AS y, COUNT(*) AS movies, 0 AS episodes
FROM entrySeens WHERE date_seen IS NOT NULL GROUP BY y
UNION ALL
SELECT YEAR(date_seen) AS y, 0 AS movies, COUNT(*) AS episodes
FROM episodeSeens WHERE date_seen IS NOT NULL GROUP BY y
) t GROUP BY y ORDER BY y DESC
`);
return rows.map((r) => ({
year: Number(r.year),
movies: Number(r.movies),
episodes: Number(r.episodes),
}));
}
/**
* Every watch in a year, newest first. Entries are returned once in
* `entries` (keyed by id) and referenced by `entry_id` from each event.
* @param {number} year
*/
async getYear(year) {
year = Number(year);
if (!Number.isInteger(year) || year < 1900 || year > 3000) {
throw new BadRequestError("Invalid year");
}
const range = {
[Op.gte]: new Date(year, 0, 1),
[Op.lt]: new Date(year + 1, 0, 1),
};
const [movieSeens, episodeSeens] = await Promise.all([
EntrySeen.findAll({
where: { date_seen: range },
attributes: ["id", "entry_id", "date_seen", "accuracy"],
include: [BUDDY_INCLUDE],
}),
EpisodeSeen.findAll({
where: { date_seen: range },
attributes: ["id", "entry_id", "episode_id", "date_seen", "accuracy"],
include: [
BUDDY_INCLUDE,
{
model: Episode,
attributes: [
"id",
"name",
"episode_number",
"runtime",
"still_path",
"season_id",
],
include: [
{ model: Season, as: "season", attributes: ["season_number"] },
],
},
],
}),
]);
const entryIds = [
...new Set([
...movieSeens.map((s) => s.entry_id),
...episodeSeens.map((s) => s.entry_id),
]),
].filter(Boolean);
const entries = entryIds.length
? await Entry.findAll({
where: { id: entryIds },
attributes: ENTRY_ATTRIBUTES,
include: [
{
model: Media,
as: "medias",
attributes: ["id", "type", "path", "isSelected"],
where: { type: "poster", isSelected: true },
required: false,
},
{
model: Genre,
as: "genres",
attributes: ["id", "name"],
through: { attributes: [] },
},
{
model: Network,
as: "networks",
attributes: ["id", "name", "logoPath"],
through: { attributes: [] },
},
{
model: EntryRating,
as: "entryRating",
attributes: ["user_rating", "tmdb_rating"],
},
],
})
: [];
const buddies = (seen) =>
(seen.buddies ?? []).map((b) => ({ id: b.id, name: b.name }));
const events = [
...movieSeens.map((s) => ({
id: `m-${s.id}`,
seen_id: s.id,
kind: "movie",
entry_id: s.entry_id,
date_seen: s.date_seen,
accuracy: s.accuracy,
buddies: buddies(s),
})),
...episodeSeens.map((s) => {
const ep = s.episode;
return {
id: `e-${s.id}`,
seen_id: s.id,
kind: "episode",
entry_id: s.entry_id,
date_seen: s.date_seen,
accuracy: s.accuracy,
buddies: buddies(s),
episode: ep
? {
id: ep.id,
name: ep.name,
season_id: ep.season_id,
season_number: ep.season?.season_number ?? null,
episode_number: ep.episode_number,
runtime: ep.runtime,
still_path: ep.still_path,
}
: null,
};
}),
].sort((a, b) => new Date(b.date_seen) - new Date(a.date_seen));
return {
year,
entries: Object.fromEntries(
entries.map((e) => {
const plain = e.get({ plain: true });
return [
plain.id,
{
...plain,
genres: plain.genres?.map((g) => g.name) ?? [],
networks:
plain.networks?.map((n) => ({
id: n.id,
name: n.name,
logo_path: n.logoPath,
})) ?? [],
},
];
}),
),
events,
};
}
}
module.exports = new HistoryService();
+94
View File
@@ -6,6 +6,7 @@ const Media = require("../models/Media");
const People = require("../models/People");
const Credit = require("../models/Credit");
const Entry = require("../models/Entry");
const { Op } = require("sequelize");
const { logToFile } = require("./logService");
const configService = require("./configService");
@@ -569,6 +570,99 @@ class MaintenanceService {
);
return { count: impossibleEntries.length };
}
/**
* Entries due for a TMDB refresh: never fetched, or last fetched more than
* `hours` ago. Entries with auto sync turned off are skipped.
* @param {number} [hours=24]
*/
async getStaleEntries(hours = 24) {
const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000);
return Entry.findAll({
attributes: ["id", "title", "last_fetch"],
where: {
autoSync: { [Op.not]: false },
[Op.or]: [{ last_fetch: null }, { last_fetch: { [Op.lt]: cutoff } }],
},
order: [["last_fetch", "ASC"]],
});
}
/** Current/last stale refresh job, for the status endpoint. */
getStaleRefreshStatus() {
const job = this.staleRefreshJob;
if (!job) return { running: false };
return { ...job, failed: job.failed.slice(-50) };
}
/**
* Starts refreshing every stale entry in the background, one at a time.
* TMDB requests go through tmdbService's rate limiter, so a large library
* is spread out instead of hammering the API.
* @param {number} [hours=24]
* @returns {Object} the job status, or `{ alreadyRunning: true, ... }`
*/
async startStaleRefresh(hours = 24) {
if (this.staleRefreshJob?.running) {
return { alreadyRunning: true, ...this.getStaleRefreshStatus() };
}
const entries = await this.getStaleEntries(hours);
const job = {
running: true,
cancelRequested: false,
hours,
total: entries.length,
done: 0,
succeeded: 0,
failed: [],
current: null,
startedAt: new Date(),
finishedAt: null,
};
this.staleRefreshJob = job;
logToFile(`Stale refresh started: ${entries.length} entries (> ${hours}h)`);
// Required lazily: entryManager pulls in most of the services layer.
const entryManager = require("./entryManager");
(async () => {
for (const entry of entries) {
if (job.cancelRequested) break;
job.current = { id: entry.id, title: entry.title };
try {
await entryManager.refrechEntryById(entry.id, false);
job.succeeded++;
} catch (error) {
job.failed.push({
id: entry.id,
title: entry.title,
error: error.message,
});
logToFile(
`Stale refresh failed for entry ${entry.id} (${entry.title}): ${error.message}`,
);
}
job.done++;
}
job.running = false;
job.current = null;
job.finishedAt = new Date();
logToFile(
`Stale refresh ${job.cancelRequested ? "cancelled" : "finished"}: ${job.succeeded} ok, ${job.failed.length} failed of ${job.total}`,
);
})();
return this.getStaleRefreshStatus();
}
cancelStaleRefresh() {
if (this.staleRefreshJob?.running) {
this.staleRefreshJob.cancelRequested = true;
}
return this.getStaleRefreshStatus();
}
}
module.exports = new MaintenanceService();
+5 -1
View File
@@ -151,7 +151,11 @@ class MediaDownloaderService {
logToFile(
`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`,
);
downloadedImages.push({ type: mediaType, path: filename });
downloadedImages.push({
type: mediaType,
path: filename,
tmdb_path: media.file_path,
});
})
.catch((err) => {
logToFile(
@@ -18,6 +18,13 @@ const EntrySeen = require("../../models/EntrySeen.js");
const Episode = require("../../models/Episode.js");
const Media = require("../../models/Media.js");
const Genre = require("../../models/Genre.js");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
} = require("../../mappers/entryMapper.js");
async function saveEntry(data) {
try {
@@ -27,29 +34,9 @@ async function saveEntry(data) {
var is_tvseries = data.release_date == null ? true : false;
let movie = Entry.build({
title: data.title || data.name,
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date,
release_status: data.status,
runtime: data.runtime || null,
tagline: data.tagline || null,
storyline: data.overview,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
...mapEntryFields(data),
is_tvseries: is_tvseries,
watchlist: true,
status: data.status,
genres: data.genre_ids,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date(),
});
const savedEntry = await movie.save();
@@ -58,7 +45,7 @@ async function saveEntry(data) {
const ids = await EntryId.create({
entry_id: savedEntry.id,
tmdb_id: data.id,
imdb_id: data.imdb_id,
...mapEntryIds(data),
});
// ? genres
@@ -73,7 +60,7 @@ async function saveEntry(data) {
const ratings = await EntryRating.create({
entry_id: savedEntry.id,
user_rating: 0,
tmdb_rating: data.vote_average,
...mapEntryRatings(data),
});
// ! seasons & episodes for tv series
@@ -82,21 +69,11 @@ async function saveEntry(data) {
let seasons = [];
for (const season of data.seasons) {
let seasonData = await fetchSeasonData(data.id, season.season_number);
if (!seasonData) continue;
const savedSeason = await Season.create({
tmdb_id: seasonData.id,
...mapSeasonFields(seasonData),
entry_id: savedEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null,
});
@@ -104,20 +81,8 @@ async function saveEntry(data) {
let episodes = [];
for (const episode of seasonData.episodes) {
const savedEpisode = await Episode.create({
tmdb_id: episode.id,
...mapEpisodeFields(episode),
season_id: savedSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
});
episodes.push(savedEpisode);
@@ -143,6 +108,7 @@ async function saveEntry(data) {
mediaableId: savedEntry.id,
type: image.type,
path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true,
isSelected: true,
});
@@ -554,6 +520,7 @@ async function refrechEntry(entryId) {
mediaableId: oldEntry.id,
type: image.type,
path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true,
isSelected: true,
});
+23 -11
View File
@@ -50,21 +50,33 @@ class NetworkService {
return network;
}
/**
* Creates the network or refreshes its TMDB fields. TMDB sends snake_case
* (`origin_country`, `logo_path`); the model attributes are camelCase.
* @returns {Promise<[Network, boolean]>} same shape as findOrCreate
*/
async createOrUpdateNetwork(networkData) {
return await Network.findOrCreate({
where: { id: networkData.id },
defaults: {
id: networkData.id,
const fields = {
name: networkData.name,
originCountry: networkData.origin_country || null,
logoPath: networkData.logo_path || null,
};
originCountry: networkData.originCountry,
homepage: networkData.homepage,
logoPath: networkData.logoPath,
posterPath: networkData.posterPath,
backdropPath: networkData.backdropPath,
},
const [network, created] = await Network.findOrCreate({
where: { id: networkData.id },
defaults: { id: networkData.id, ...fields },
});
if (
!created &&
(network.name !== fields.name ||
network.originCountry !== fields.originCountry ||
network.logoPath !== fields.logoPath)
) {
await network.update(fields);
}
return [network, created];
}
}
+1
View File
@@ -72,6 +72,7 @@ class PeopleManager {
mediaableId: person.id,
type: image.type,
path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true,
isSelected: true,
});
+181 -201
View File
@@ -5,91 +5,161 @@ const configService = require("./configService");
const TMDB_APIURL = configService.getTmdbApiUrl();
const TMDB_APIKEY = configService.getTmdbApiKey();
async function fetchEntryData(tmdb_id, is_tvserie) {
try {
let type = is_tvserie ? "tv" : "movie";
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Entry Data From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
// ─── Rate limiting ───────────────────────────────────────────────────────────
// TMDB allows roughly 50 requests/second per IP. We stay well below that so
// bulk jobs (e.g. the stale-entries refresh) never get the IP blocked.
const MAX_REQUESTS_PER_WINDOW = 20;
const WINDOW_MS = 1000;
const MAX_CONCURRENT = 8;
const MAX_RETRIES = 4;
return data;
const queue = [];
const recentStarts = [];
let activeRequests = 0;
let wakeTimer = null;
function scheduleNext() {
while (queue.length > 0 && activeRequests < MAX_CONCURRENT) {
const now = Date.now();
while (recentStarts.length && now - recentStarts[0] >= WINDOW_MS) {
recentStarts.shift();
}
if (recentStarts.length >= MAX_REQUESTS_PER_WINDOW) {
if (!wakeTimer) {
const waitMs = WINDOW_MS - (now - recentStarts[0]) + 5;
wakeTimer = setTimeout(() => {
wakeTimer = null;
scheduleNext();
}, waitMs);
}
return;
}
recentStarts.push(now);
activeRequests++;
const job = queue.shift();
job().finally(() => {
activeRequests--;
scheduleNext();
});
}
}
function enqueue(fn) {
return new Promise((resolve, reject) => {
queue.push(() => fn().then(resolve, reject));
scheduleNext();
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function isRetryable(error) {
const status = error.response?.status;
if (status === 429) return true;
if (status >= 500) return true;
return !error.response; // network error / timeout
}
/**
* Rate-limited GET against the TMDB API. Retries 429s (honouring Retry-After)
* and transient failures with backoff. The API key is never logged.
* @param {string} path - e.g. "movie/550"
* @param {Object} [params] - extra query params
* @returns {Promise<Object>} response data
*/
async function tmdbGet(path, params = {}) {
const query = { language: "en-US", ...params };
const logQuery = new URLSearchParams(
Object.entries(query).filter(([, v]) => v !== undefined),
).toString();
for (let attempt = 1; ; attempt++) {
try {
logToFile(`TMDB GET ${path}?${logQuery}`);
const response = await enqueue(() =>
axios.get(`${TMDB_APIURL}${path}`, {
params: { api_key: TMDB_APIKEY, ...query },
timeout: 20000,
}),
);
return response.data;
} catch (error) {
console.log("Error fetching the entry data.", error);
if (attempt >= MAX_RETRIES || !isRetryable(error)) throw error;
const retryAfter = Number(error.response?.headers?.["retry-after"]);
const waitMs =
Number.isFinite(retryAfter) && retryAfter > 0
? retryAfter * 1000
: 1000 * 2 ** (attempt - 1);
logToFile(
`TMDB GET ${path} failed (${error.response?.status ?? error.code}), retry ${attempt}/${MAX_RETRIES - 1} in ${waitMs}ms`,
);
await sleep(waitMs);
}
}
}
/** Runs a TMDB request, logging and returning null on failure. */
async function safeGet(label, path, params) {
try {
return await tmdbGet(path, params);
} catch (error) {
logToFile(
`Error fetching ${label} (${path}): ${error.response?.status ?? ""} ${error.message}`,
);
console.log(`Error fetching ${label}.`, error.message);
return null;
}
}
// ─── Entries ─────────────────────────────────────────────────────────────────
/**
* Fetches movie/TV details plus everything we store from the same request:
* external ids, certification, keywords, videos, watch providers and
* alternative titles.
*/
async function fetchEntryData(tmdb_id, is_tvserie) {
const type = is_tvserie ? "tv" : "movie";
const appends = [
"external_ids",
is_tvserie ? "content_ratings" : "release_dates",
"keywords",
"videos",
"watch/providers",
"alternative_titles",
];
return safeGet("entry data", `${type}/${tmdb_id}`, {
append_to_response: appends.join(","),
include_video_language: "en,null",
});
}
async function fetchSeasonData(tmdbTvId, seasonNumber) {
// fetching the informations
try {
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Season Data From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
return safeGet("season data", `tv/${tmdbTvId}/season/${seasonNumber}`, {
append_to_response: "external_ids",
});
return data;
} catch (error) {
console.log("Error fetching the data.");
return null;
}
}
async function fetchEntryMedia(tmdb_id, is_tvserie) {
try {
let type = is_tvserie ? "tv" : "movie";
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`;
logToFile(`Fetching Entry Media Data From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
const type = is_tvserie ? "tv" : "movie";
// Images are language-agnostic, so don't send language=en-US
return safeGet("entry media", `${type}/${tmdb_id}/images`, {
language: undefined,
});
return data;
} catch (error) {
console.log("Error fetching the entry media.", error);
return null;
}
async function fetchEntryRecommendations(tmdb_id, is_tvserie, page = 1) {
const type = is_tvserie ? "tv" : "movie";
return safeGet("recommendations", `${type}/${tmdb_id}/recommendations`, {
page,
});
}
async function fetchCollectionData(collectionId) {
try {
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Collection Data From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200)
return console.log(
"Error fetching collection data from tmdb:",
response,
);
data = response.data;
});
return data;
} catch (error) {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
return null;
}
return safeGet("collection data", `collection/${collectionId}`);
}
/**
@@ -99,31 +169,13 @@ async function fetchCollectionData(collectionId) {
* @returns {Promise<Object|null>} - The credits data or null if there's an error
*/
async function fetchEntryCredits(tmdb_id, is_tvserie) {
try {
let type = is_tvserie ? "tv" : "movie";
let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`;
if (is_tvserie) {
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`;
const path = is_tvserie
? `tv/${tmdb_id}/aggregate_credits`
: `movie/${tmdb_id}/credits`;
return safeGet("entry credits", path);
}
logToFile(`Fetching Entry Credits From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Credits From: ${url}`);
return console.log("Error fetching the credits data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log("Error fetching the entry credits.", error);
return null;
}
}
// ─── People ──────────────────────────────────────────────────────────────────
/**
* Fetches detailed information about a person
@@ -131,126 +183,54 @@ async function fetchEntryCredits(tmdb_id, is_tvserie) {
* @returns {Promise<Object|null>} - The person data or null if there's an error
*/
async function fetchPersonDetails(tmdb_id) {
try {
let url = `${TMDB_APIURL}person/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US&append_to_response=external_ids`;
logToFile(`Fetching Person Details From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Person Details From: ${url}`);
return console.log("Error fetching the person data.");
}
data = response.data;
return safeGet("person details", `person/${tmdb_id}`, {
append_to_response: "external_ids",
});
return data;
} catch (error) {
console.log("Error fetching the person details.", error);
return null;
}
}
async function fetchTrending(type, page = 1) {
try {
let url = `${TMDB_APIURL}trending/${type}/week?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Trending ${type} From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(`Error fetching trending ${type}.`, error);
return null;
}
}
async function fetchPopular(type, page = 1) {
try {
let url = `${TMDB_APIURL}${type}/popular?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Popular ${type} From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(`Error fetching popular ${type}.`, error);
return null;
}
}
async function fetchTopRated(type, page = 1) {
try {
let url = `${TMDB_APIURL}${type}/top_rated?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Top Rated ${type} From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(`Error fetching top rated ${type}.`, error);
return null;
}
}
async function fetchUpcoming(page = 1) {
try {
let url = `${TMDB_APIURL}movie/upcoming?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Upcoming Movies From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error fetching upcoming movies.", error);
return null;
}
}
async function searchMulti(query, page = 1) {
try {
let url = `${TMDB_APIURL}search/multi?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`;
logToFile(`Searching TMDB for: ${query}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error searching TMDB.", error);
return null;
}
}
async function searchPeople(query, page = 1) {
try {
let url = `${TMDB_APIURL}search/person?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`;
logToFile(`Searching TMDB People for: ${query}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error searching TMDB people.", error);
return null;
}
}
async function fetchPopularPeople(page = 1) {
try {
let url = `${TMDB_APIURL}person/popular?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Popular People From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error fetching popular people.", error);
return null;
}
}
async function fetchPersonCombinedCredits(tmdb_id) {
try {
const url = `${TMDB_APIURL}person/${tmdb_id}/combined_credits?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Person Combined Credits From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error fetching person combined credits.", error);
return null;
return safeGet(
"person combined credits",
`person/${tmdb_id}/combined_credits`,
);
}
// ─── Lists & search ──────────────────────────────────────────────────────────
async function fetchTrending(type, page = 1) {
return safeGet(`trending ${type}`, `trending/${type}/week`, { page });
}
async function fetchPopular(type, page = 1) {
return safeGet(`popular ${type}`, `${type}/popular`, { page });
}
async function fetchTopRated(type, page = 1) {
return safeGet(`top rated ${type}`, `${type}/top_rated`, { page });
}
async function fetchUpcoming(page = 1) {
return safeGet("upcoming movies", "movie/upcoming", { page });
}
async function searchMulti(query, page = 1) {
return safeGet("search", "search/multi", { query, page });
}
async function searchPeople(query, page = 1) {
return safeGet("people search", "search/person", { query, page });
}
async function fetchPopularPeople(page = 1) {
return safeGet("popular people", "person/popular", { page });
}
module.exports = {
tmdbGet,
fetchEntryData,
fetchSeasonData,
fetchEntryMedia,
fetchEntryRecommendations,
fetchCollectionData,
fetchEntryCredits,
fetchPersonDetails,
+915 -2575
View File
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -49,9 +49,8 @@
},
"author": "",
"license": "ISC",
"dependencies": {},
"devDependencies": {
"electron": "^34.0.1",
"electron-builder": "^25.1.8"
"electron": "^45.1.0",
"electron-builder": "^26.18.0"
}
}
+3
View File
@@ -6,6 +6,8 @@
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"dev:tauri": "cross-env VITE_TAURI=true vite",
"build:tauri": "cross-env VITE_TAURI=true vite build --outDir ../tauri/frontend_build --emptyOutDir",
"build:electron": "cross-env VITE_ELECTRON=true vite build --outDir ../electron/frontend_build",
"lint": "eslint .",
"preview": "vite preview"
@@ -15,6 +17,7 @@
"@fontsource-variable/geist": "^5.2.8",
"@hookform/resolvers": "^5.2.2",
"@tanstack/react-query": "^5.95.2",
"@tauri-apps/api": "^2.12.4",
"axios": "^1.14.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+756 -445
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
allowBuilds:
msw: false
overrides:
'@babel/core@<=7.29.0': ^7.29.6
'@hono/node-server@<1.19.15': ^1.19.15
'@hono/node-server@>=1.19.10 <2.1.3': ^2.1.3
'@modelcontextprotocol/sdk@<1.32.0': ^1.32.0
axios@>=1.0.0 <1.20.0: ^1.20.0
baseline-browser-mapping@>=2.0.0 <2.11.0: ^2.11.0
body-parser@>=2.0.0 <2.4.0: ^2.4.0
brace-expansion@<1.1.21: ^1.1.21
brace-expansion@>=3.0.0 <5.0.7: ^5.0.7
brace-expansion@>=4.0.0 <5.0.12: ^5.0.12
browserslist@<=4.28.6: ^4.28.7
fast-uri@>=3.0.0 <3.1.9: ^3.1.9
follow-redirects@>=1.16.0 <1.16.1: ^1.16.1
form-data@>=4.0.0 <4.0.6: ^4.0.6
hono@<4.13.7: ^4.13.7
hono@>=4.12.4 <4.13.11: ^4.13.11
ip-address@<=10.7.3: ^10.7.4
js-yaml@>=4.0.0 <4.3.2: ^4.3.2
nanoid@<3.3.18: ^3.3.18
postcss-selector-parser@>=7.0.0 <7.1.6: ^7.1.6
postcss@<=8.5.22: ^8.5.23
proxy-addr@>=1.1.0 <2.0.8: ^2.0.8
qs@>=2.2.5 <6.16.0: ^6.16.0
qs@>=6.7.0 <=6.16.0: ^6.16.1
react-router@>=6.0.0 <7.18.0: ^7.18.0
react-router@>=7.12.0 <7.18.2: ^7.18.2
source-map-js@>=1.0.0 <1.2.2: ^1.2.2
vite@>=8.0.0 <=8.1.5: ^8.1.6
zod@<4.6.6: ^4.6.6
+33 -1
View File
@@ -1,6 +1,15 @@
import { api } from "@/lib/api";
import { normalizeEntry, normalizeCredit } from "@/lib/normalizers";
import type { Entry, Credit, TmdbPreview } from "@/types";
import type {
Entry,
Credit,
TmdbPreview,
TmdbEntry,
TmdbPaginatedResponse,
ArtworkResponse,
ArtworkType,
Media,
} from "@/types";
export const entriesApi = {
getAll: () =>
@@ -58,6 +67,29 @@ export const entriesApi = {
.get<Credit[]>(`/entries/${id}/credits`)
.then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])),
getRecommendations: (id: number) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>(`/entries/${id}/recommendations`)
.then((r) => r.data),
getTmdbRecommendations: (type: "movie" | "tv", tmdbId: number) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>(
`/entries/tmdb/recommendations/${type}/${tmdbId}`,
)
.then((r) => r.data),
getArtwork: (id: number) =>
api.get<ArtworkResponse>(`/entries/${id}/artwork`).then((r) => r.data),
getTmdbArtwork: (type: "movie" | "tv", tmdbId: number) =>
api
.get<ArtworkResponse>(`/entries/tmdb/artwork/${type}/${tmdbId}`)
.then((r) => r.data),
addArtwork: (id: number, data: { type: ArtworkType; file_path: string }) =>
api.post<Media>(`/entries/${id}/artwork`, data).then((r) => r.data),
syncSeries: () => api.get("/entries/sync-series").then((r) => r.data),
previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
+61
View File
@@ -0,0 +1,61 @@
import { api } from "@/lib/api";
export type WatchAccuracy = "EXACT" | "ESTIMATED" | "UNKNOWN";
export interface HistoryYear {
year: number;
movies: number;
episodes: number;
}
export interface HistoryEntry {
id: number;
title: string;
is_tvseries: boolean;
poster_path: string | null;
banner_path: string | null;
runtime: number | null;
release_date: string | null;
original_language: string | null;
medias: { id: number; type: string; path: string; isSelected: boolean }[];
genres: string[];
networks: { id: number; name: string; logo_path: string | null }[];
entryRating: {
user_rating: number | null;
tmdb_rating: number | null;
} | null;
}
export interface HistoryEpisode {
id: number;
name: string;
season_id: number;
season_number: number | null;
episode_number: number;
runtime: number | null;
still_path: string | null;
}
export interface HistoryEvent {
id: string;
seen_id: number;
kind: "movie" | "episode";
entry_id: number;
date_seen: string;
accuracy: WatchAccuracy;
buddies: { id: number; name: string }[];
episode?: HistoryEpisode | null;
}
export interface HistoryYearData {
year: number;
entries: Record<number, HistoryEntry>;
events: HistoryEvent[];
}
export const historyApi = {
getYears: () => api.get<HistoryYear[]>("/history/years").then((r) => r.data),
getYear: (year: number) =>
api.get<HistoryYearData>(`/history/${year}`).then((r) => r.data),
};
+40
View File
@@ -11,7 +11,47 @@ export interface OrphanPeopleResult {
count: number;
}
export interface StaleRefreshJob {
running: boolean;
hours?: number;
total?: number;
done?: number;
succeeded?: number;
failed?: { id: number; title: string; error: string }[];
current?: { id: number; title: string } | null;
cancelRequested?: boolean;
startedAt?: string;
finishedAt?: string | null;
}
export interface StaleEntriesResult {
count: number;
hours: number;
job: StaleRefreshJob;
}
export const maintenanceApi = {
getStaleEntries: (hours = 24) =>
api
.get<StaleEntriesResult>("/maintenance/stale-entries", {
params: { hours },
})
.then((r) => r.data),
// 409 means a job is already running; its status is returned either way
startStaleRefresh: (hours = 24) =>
api
.post<StaleRefreshJob>("/maintenance/stale-entries/refresh", null, {
params: { hours },
validateStatus: (s) => s === 202 || s === 409,
})
.then((r) => r.data),
cancelStaleRefresh: () =>
api
.delete<StaleRefreshJob>("/maintenance/stale-entries/refresh")
.then((r) => r.data),
scanOrphanFiles: () =>
api.get<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
@@ -16,6 +16,7 @@ import {
ArrowDown,
CornerDownLeft,
ArrowRight,
History,
} from "lucide-react";
import { tmdbApi } from "@/api/tmdb";
import { useLibraryStore } from "@/stores/useLibraryStore";
@@ -53,6 +54,12 @@ const NAVIGATION_COMMANDS: CommandItem[] = [
title: "Go to Watchlist",
icon: <BookOpen className="h-4 w-4" />,
},
{
id: "cmd-history",
type: "command",
title: "Go to History",
icon: <History className="h-4 w-4" />,
},
{
id: "cmd-stats",
type: "command",
@@ -88,6 +95,7 @@ const NAVIGATION_COMMANDS: CommandItem[] = [
const COMMAND_ROUTES: Record<string, string> = {
"cmd-library": "/library",
"cmd-watchlist": "/watchlist",
"cmd-history": "/history",
"cmd-stats": "/dashboard",
"cmd-calendar": "/calendar",
"cmd-people": "/people",
@@ -13,6 +13,11 @@ import { Textarea } from "@/components/ui/textarea";
import { ImageIcon } from "lucide-react";
import { StarRating } from "@/components/ui/star-rating";
import { useUpdateCollection } from "@/hooks/useCollections";
import {
DEFAULT_POSTER,
getCollectionDisplayBackdropUrl,
getCollectionDisplayPosterUrl,
} from "@/lib/collection-media";
import type { Collection } from "@/types";
interface CollectionEditDialogProps {
@@ -34,6 +39,14 @@ export function CollectionEditDialog({
const [posterPreview, setPosterPreview] = useState<string | null>(null);
const [backdropPreview, setBackdropPreview] = useState<string | null>(null);
// What the collection page currently shows, so the user can see what an
// upload would replace. The default placeholder doesn't count as a poster.
const displayPoster = getCollectionDisplayPosterUrl(collection);
const currentPoster = displayPoster === DEFAULT_POSTER ? null : displayPoster;
const currentBackdrop = getCollectionDisplayBackdropUrl(collection);
const shownPoster = posterPreview ?? currentPoster;
const shownBackdrop = backdropPreview ?? currentBackdrop;
const posterInputRef = useRef<HTMLInputElement>(null);
const backdropInputRef = useRef<HTMLInputElement>(null);
@@ -131,15 +144,20 @@ export function CollectionEditDialog({
<Button
type="button"
variant="outline"
className="w-full h-20 flex flex-col gap-1"
className="group relative w-full h-32 p-0 overflow-hidden flex flex-col gap-1"
onClick={() => posterInputRef.current?.click()}
>
{posterPreview ? (
{shownPoster ? (
<>
<img
src={posterPreview}
src={shownPoster}
alt="Poster preview"
className="h-14 w-auto rounded object-cover"
className="h-full w-full object-contain bg-muted"
/>
<span className="absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100">
Change Poster
</span>
</>
) : (
<>
<ImageIcon className="h-5 w-5 text-muted-foreground" />
@@ -163,15 +181,20 @@ export function CollectionEditDialog({
<Button
type="button"
variant="outline"
className="w-full h-20 flex flex-col gap-1"
className="group relative w-full h-32 p-0 overflow-hidden flex flex-col gap-1"
onClick={() => backdropInputRef.current?.click()}
>
{backdropPreview ? (
{shownBackdrop ? (
<>
<img
src={backdropPreview}
src={shownBackdrop}
alt="Backdrop preview"
className="h-14 w-auto rounded object-cover"
className="h-full w-full object-cover"
/>
<span className="absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100">
Change Backdrop
</span>
</>
) : (
<>
<ImageIcon className="h-5 w-5 text-muted-foreground" />
@@ -0,0 +1,445 @@
import { useEffect, useMemo, useState } from "react";
import { Check, Download, Loader2, Star } from "lucide-react";
import { useAddArtwork, useArtwork } from "@/hooks/useEntries";
import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import type { ArtworkItem, ArtworkType } from "@/types";
// Rows shown at first and added per "Show more"
const ROWS_STEP = 2;
// Checkerboard behind logos so transparent/dark logos stay visible
const CHECKER =
"bg-[repeating-conic-gradient(#8883_0_25%,transparent_0_50%)] bg-size-[16px_16px]";
const TYPES: {
type: ArtworkType;
key: "posters" | "backdrops" | "logos";
label: string;
thumbSize: string;
grid: string;
/** Columns per breakpoint; must match `grid` */
cols: { base: number; sm?: number; md?: number; xl?: number };
aspect: string;
}[] = [
{
type: "poster",
key: "posters",
label: "Posters",
thumbSize: "w342",
grid: "grid-cols-3 sm:grid-cols-4 md:grid-cols-5 xl:grid-cols-6",
cols: { base: 3, sm: 4, md: 5, xl: 6 },
aspect: "aspect-2/3",
},
{
type: "backdrop",
key: "backdrops",
label: "Backdrops",
thumbSize: "w780",
grid: "grid-cols-1 sm:grid-cols-2 xl:grid-cols-3",
cols: { base: 1, sm: 2, xl: 3 },
aspect: "aspect-video",
},
{
type: "logo",
key: "logos",
label: "Logos",
thumbSize: "w500",
grid: "grid-cols-2 sm:grid-cols-3 xl:grid-cols-4",
cols: { base: 2, sm: 3, xl: 4 },
aspect: "aspect-[2/1]",
},
];
const languageName = (() => {
try {
const names = new Intl.DisplayNames(["en"], { type: "language" });
return (code: string) => names.of(code) ?? code;
} catch {
return (code: string) => code;
}
})();
function imageUrls(item: ArtworkItem, type: ArtworkType, thumbSize: string) {
if (item.file_path) {
return {
thumb: getTmdbImageUrl(item.file_path, thumbSize),
full: getTmdbImageUrl(item.file_path, "original"),
};
}
const folder = `${type}s`;
return {
thumb: getMediaUrl("entries", folder, "preview", item.media_path!),
full: getMediaUrl("entries", folder, "full", item.media_path!),
};
}
const BREAKPOINTS = [
["xl", 1280],
["md", 768],
["sm", 640],
] as const;
/** Current column count for a grid, following the Tailwind breakpoints. */
function useGridColumns(cols: {
base: number;
sm?: number;
md?: number;
xl?: number;
}) {
const compute = () => {
for (const [bp, minWidth] of BREAKPOINTS) {
const value = cols[bp];
if (value && window.matchMedia(`(min-width: ${minWidth}px)`).matches) {
return value;
}
}
return cols.base;
};
const [columns, setColumns] = useState(compute);
useEffect(() => {
const update = () => setColumns(compute());
update();
const queries = BREAKPOINTS.map(([, w]) =>
window.matchMedia(`(min-width: ${w}px)`),
);
queries.forEach((q) => q.addEventListener("change", update));
return () =>
queries.forEach((q) => q.removeEventListener("change", update));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cols.base, cols.sm, cols.md, cols.xl]);
return columns;
}
const itemKey = (item: ArtworkItem) =>
item.file_path ?? `media-${item.media_id}`;
/**
* Posters, backdrops and logos from TMDB merged with the entry's media table.
* For library entries, TMDB images can be added (downloaded) to the library.
*/
export function ArtworkSection({
entryId = 0,
tmdbId = 0,
isTvSeries,
originalLanguage,
}: {
entryId?: number;
tmdbId?: number;
isTvSeries: boolean;
originalLanguage?: string | null;
}) {
const isLibrary = !!entryId;
const { data, isLoading, isError } = useArtwork(
isLibrary ? { entryId } : { tmdbId, type: isTvSeries ? "tv" : "movie" },
);
const addArtwork = useAddArtwork(entryId);
const [activeType, setActiveType] = useState<ArtworkType>("poster");
const [language, setLanguage] = useState("all");
const [libraryOnly, setLibraryOnly] = useState(false);
const [rows, setRows] = useState(ROWS_STEP);
const [pendingPath, setPendingPath] = useState<string | null>(null);
const [viewing, setViewing] = useState<ArtworkItem | null>(null);
const config = TYPES.find((t) => t.type === activeType)!;
const columns = useGridColumns(config.cols);
const visible = columns * rows;
const items = useMemo(() => data?.[config.key] ?? [], [data, config.key]);
// Languages present for this type, most common first ("none" = no text)
const languages = useMemo(() => {
const counts = new Map<string, number>();
for (const item of items) {
if (!item.file_path) continue;
const lang = item.language ?? "none";
counts.set(lang, (counts.get(lang) ?? 0) + 1);
}
const preferred = ["none", "en", originalLanguage].filter(Boolean);
return [...counts.entries()].sort(([a, ca], [b, cb]) => {
const pa = preferred.indexOf(a);
const pb = preferred.indexOf(b);
if (pa !== -1 || pb !== -1)
return (pa === -1 ? 99 : pa) - (pb === -1 ? 99 : pb);
return cb - ca;
});
}, [items, originalLanguage]);
const filtered = items.filter((item) => {
if (libraryOnly && !item.in_library) return false;
if (language === "all" || !item.file_path) return true;
return (item.language ?? "none") === language;
});
const changeType = (type: ArtworkType) => {
setActiveType(type);
setLanguage("all");
setRows(ROWS_STEP);
};
const add = (item: ArtworkItem) => {
if (!item.file_path) return;
setPendingPath(item.file_path);
addArtwork.mutate(
{ type: activeType, file_path: item.file_path },
{
onSuccess: () =>
setViewing((v) =>
v?.file_path === item.file_path ? { ...v, in_library: true } : v,
),
onSettled: () => setPendingPath(null),
},
);
};
if (isError) return null;
const total = data
? data.posters.length + data.backdrops.length + data.logos.length
: 0;
if (!isLoading && total === 0) return null;
return (
<section className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-lg font-semibold">Artwork</h3>
<div className="flex flex-wrap items-center gap-2">
<select
value={language}
onChange={(e) => {
setLanguage(e.target.value);
setRows(ROWS_STEP);
}}
className="h-8 rounded-md border border-border/60 bg-background px-2 text-xs"
aria-label="Language"
>
<option value="all">All languages</option>
{languages.map(([lang, count]) => (
<option key={lang} value={lang}>
{lang === "none" ? "No text" : languageName(lang)} ({count})
</option>
))}
</select>
{isLibrary && (
<Button
variant={libraryOnly ? "default" : "outline"}
size="sm"
aria-pressed={libraryOnly}
onClick={() => {
setLibraryOnly((v) => !v);
setRows(ROWS_STEP);
}}
>
<Check />
In library
</Button>
)}
</div>
</div>
<Tabs
value={activeType}
onValueChange={(v) => changeType(v as ArtworkType)}
>
<TabsList>
{TYPES.map((t) => (
<TabsTrigger key={t.type} value={t.type}>
{t.label}
{data && (
<span className="ml-1 text-muted-foreground tabular-nums">
{data[t.key].length}
</span>
)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
{isLoading ? (
<div className={`grid gap-3 ${config.grid}`}>
{Array.from({ length: columns * ROWS_STEP }).map((_, i) => (
<Skeleton key={i} className={`${config.aspect} rounded-lg`} />
))}
</div>
) : filtered.length === 0 ? (
<p className="text-sm text-muted-foreground">
No {config.label.toLowerCase()} match these filters.
</p>
) : (
<>
<div className={`grid gap-3 ${config.grid}`}>
{filtered.slice(0, visible).map((item) => (
<ArtworkTile
key={itemKey(item)}
item={item}
type={activeType}
thumbSize={config.thumbSize}
aspect={config.aspect}
canAdd={isLibrary}
adding={pendingPath === item.file_path}
onAdd={() => add(item)}
onOpen={() => setViewing(item)}
/>
))}
</div>
{filtered.length > visible && (
<div className="flex justify-center">
<Button
variant="outline"
size="sm"
onClick={() => setRows((r) => r + ROWS_STEP)}
>
Show more ({filtered.length - visible} left)
</Button>
</div>
)}
</>
)}
<Dialog
open={!!viewing}
onOpenChange={(open) => !open && setViewing(null)}
>
<DialogContent className="w-auto max-w-[calc(100%-2rem)] sm:max-w-[calc(100%-2rem)] gap-3 p-3">
<DialogTitle className="sr-only">{config.label} preview</DialogTitle>
{viewing && (
<>
<img
src={imageUrls(viewing, activeType, config.thumbSize).full}
alt=""
className={`max-h-[80vh] max-w-full rounded-lg object-contain ${
activeType === "logo" ? `${CHECKER} p-4` : ""
}`}
/>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span>
{viewing.width && viewing.height
? `${viewing.width}×${viewing.height}`
: "Local file"}
{viewing.file_path &&
` · ${viewing.language ? languageName(viewing.language) : "No text"}`}
</span>
{viewing.in_library ? (
<LibraryBadge selected={viewing.is_selected} />
) : (
isLibrary &&
viewing.file_path && (
<Button
size="sm"
onClick={() => add(viewing)}
disabled={pendingPath === viewing.file_path}
>
{pendingPath === viewing.file_path ? (
<Loader2 className="animate-spin" />
) : (
<Download />
)}
Add to library
</Button>
)
)}
</div>
</>
)}
</DialogContent>
</Dialog>
</section>
);
}
function LibraryBadge({ selected }: { selected?: boolean }) {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow">
<Check className="h-3 w-3" />
{selected ? "Selected" : "In library"}
</span>
);
}
function ArtworkTile({
item,
type,
thumbSize,
aspect,
canAdd,
adding,
onAdd,
onOpen,
}: {
item: ArtworkItem;
type: ArtworkType;
thumbSize: string;
aspect: string;
canAdd: boolean;
adding: boolean;
onAdd: () => void;
onOpen: () => void;
}) {
const { thumb } = imageUrls(item, type, thumbSize);
return (
<div
className={`group relative overflow-hidden rounded-lg bg-muted ring-1 ${
item.in_library ? "ring-emerald-500/60" : "ring-border/60"
} ${aspect}`}
>
<button
type="button"
onClick={onOpen}
className="block h-full w-full cursor-zoom-in"
aria-label="View full size"
>
<img
src={thumb}
alt=""
loading="lazy"
className={`h-full w-full transition-transform duration-300 group-hover:scale-[1.03] ${
type === "logo" ? `${CHECKER} object-contain p-3` : "object-cover"
}`}
/>
</button>
{/* Top: library badge / language */}
<div className="pointer-events-none absolute inset-x-1.5 top-1.5 flex items-start justify-between gap-1">
{item.in_library ? (
<LibraryBadge selected={item.is_selected} />
) : (
<span />
)}
{item.file_path && item.language && (
<span className="rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase text-white">
{item.language}
</span>
)}
</div>
{/* Bottom: votes + add */}
<div className="absolute inset-x-1.5 bottom-1.5 flex items-end justify-between gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
{item.vote_count > 0 ? (
<span className="inline-flex items-center gap-0.5 rounded bg-black/60 px-1.5 py-0.5 text-[10px] text-white tabular-nums">
<Star className="h-2.5 w-2.5 fill-yellow-400 text-yellow-400" />
{item.vote_average.toFixed(1)}
</span>
) : (
<span />
)}
{canAdd && !item.in_library && item.file_path && (
<Button
size="xs"
onClick={onAdd}
disabled={adding}
className="shadow"
aria-label="Add to library"
>
{adding ? <Loader2 className="animate-spin" /> : <Download />}
Add
</Button>
)}
</div>
</div>
);
}
@@ -13,6 +13,8 @@ interface CastListProps {
maxItems?: number;
/** Override link for "All Cast & Crew" — if unset, uses /entry/:entryId/cast */
allCastHref?: string;
/** Section heading (default: "Cast") */
title?: string;
}
export function CastList({
@@ -21,6 +23,7 @@ export function CastList({
isTvSeries,
maxItems,
allCastHref,
title = "Cast",
}: CastListProps) {
let castCredits = credits.filter((c) => c.cast_type === "cast");
const hasMore = maxItems != null && castCredits.length > maxItems;
@@ -36,7 +39,7 @@ export function CastList({
return (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Cast</h3>
<h3 className="text-lg font-semibold">{title}</h3>
{allCastLink && (
<Link
to={allCastLink}
@@ -0,0 +1,178 @@
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
/**
* Full-bleed hero used by the season and episode pages: a backdrop that fades
* into the page, with content laid over it (same look as the entry page).
*/
export function DetailHero({
backdrop,
children,
}: {
backdrop: string | null | undefined;
children: ReactNode;
}) {
return (
<section className="relative -mx-4 -mt-4 md:-mx-6 md:-mt-6">
<div className="absolute inset-0 overflow-hidden">
{backdrop ? (
<img
src={backdrop}
alt=""
className="h-full w-full object-cover object-top"
/>
) : (
<div className="h-full w-full bg-linear-to-br from-primary/30 via-primary/10 to-background" />
)}
<div className="absolute inset-0 bg-linear-to-t from-background via-background/75 to-background/10" />
<div className="absolute inset-0 bg-linear-to-r from-background/90 via-background/40 to-transparent" />
</div>
<div className="relative mx-auto max-w-6xl px-4 pb-8 pt-24 md:px-6 sm:pt-40">
{children}
</div>
</section>
);
}
export function MetaItem({ children }: { children: ReactNode }) {
return (
<span className="inline-flex items-center gap-3">
<span className="h-1 w-1 rounded-full bg-muted-foreground/50" />
<span>{children}</span>
</span>
);
}
export function HeroChip({ children }: { children: ReactNode }) {
return (
<span className="inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-background/60 px-2.5 py-0.5 text-xs font-medium uppercase tracking-wider text-muted-foreground backdrop-blur [&_svg]:h-3 [&_svg]:w-3">
{children}
</span>
);
}
export function IconAction({
label,
onClick,
disabled,
active,
children,
}: {
label: string;
onClick: () => void;
disabled?: boolean;
active?: boolean;
children: ReactNode;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Button
variant="outline"
size="icon-lg"
onClick={onClick}
disabled={disabled}
aria-label={label}
aria-pressed={active}
className={`h-11 w-11 rounded-full border-border/60 bg-background/60 backdrop-blur ${active ? "border-foreground/20 bg-accent" : ""}`}
/>
}
>
{children}
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
/** Round icon link with a tooltip (same look as IconAction). */
export function IconLink({
label,
to,
children,
}: {
label: string;
to: string;
children: ReactNode;
}) {
return (
<Tooltip>
<TooltipTrigger
render={
<Link
to={to}
aria-label={label}
className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-border/60 bg-background/60 backdrop-blur transition-colors hover:bg-accent"
/>
}
>
{children}
</TooltipTrigger>
<TooltipContent>{label}</TooltipContent>
</Tooltip>
);
}
export function DetailSection({
title,
action,
children,
}: {
title: string;
action?: ReactNode;
children: ReactNode;
}) {
return (
<section className="space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="text-lg font-semibold">{title}</h3>
{action}
</div>
{children}
</section>
);
}
export function DetailCard({
title,
children,
}: {
title: string;
children: ReactNode;
}) {
return (
<div className="rounded-xl border border-border/60 bg-card/50 p-4">
<h3 className="mb-3 text-xs font-semibold uppercase tracking-wider text-muted-foreground">
{title}
</h3>
{children}
</div>
);
}
export function DetailRow({
icon,
label,
children,
}: {
icon: ReactNode;
label: string;
children: ReactNode;
}) {
return (
<div className="flex items-start justify-between gap-4 text-sm">
<dt className="flex items-center gap-2 text-muted-foreground [&_svg]:h-3.5 [&_svg]:w-3.5">
{icon}
{label}
</dt>
<dd className="text-right font-medium">{children}</dd>
</div>
);
}
@@ -0,0 +1,55 @@
import {
useEntryRecommendations,
useTmdbRecommendations,
} from "@/hooks/useEntries";
import { EntryCard } from "@/components/entries/EntryCard";
import { Skeleton } from "@/components/ui/skeleton";
const GRID =
"grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6";
const MAX_ITEMS = 12;
/**
* "More like this": live TMDB recommendations. Pass `entryId` for a library
* entry, or `tmdbId` for one that is not in the library.
*/
export function RecommendationsSection({
entryId = 0,
tmdbId = 0,
isTvSeries,
}: {
entryId?: number;
tmdbId?: number;
isTvSeries: boolean;
}) {
const type = isTvSeries ? "tv" : "movie";
const library = useEntryRecommendations(entryId);
const tmdb = useTmdbRecommendations(entryId ? 0 : tmdbId, type);
const { data, isLoading, isError } = entryId ? library : tmdb;
if (isError) return null;
const results = (data?.results ?? [])
.filter((r) => r.poster_path)
.slice(0, MAX_ITEMS)
// Recommendations don't always carry media_type; it matches the entry's
.map((r) => ({
...r,
media_type: r.media_type ?? (isTvSeries ? "tv" : "movie"),
}));
if (!isLoading && results.length === 0) return null;
return (
<section className="space-y-3">
<h3 className="text-lg font-semibold">More like this</h3>
<div className={GRID}>
{isLoading
? Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 rounded-lg" />
))
: results.map((r) => <EntryCard key={r.id} tmdbEntry={r} />)}
</div>
</section>
);
}
@@ -0,0 +1,324 @@
import { Link } from "react-router-dom";
import {
CheckCircle2,
Clock,
Eye,
LayoutGrid,
List,
PlayCircle,
Star,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils";
import {
isEpisodeUpcoming,
isEpisodeWatched,
type EpisodeView,
} from "@/lib/episodes";
import type { Episode, EpisodeSeen } from "@/types";
interface EpisodeActions {
entryId: number;
seasonId: number;
onPlay: (episode: Episode) => void;
onMarkWatched: (episode: Episode) => void;
}
/** List/cards toggle for the season page's episodes header. */
export function EpisodeViewToggle({
view,
onChange,
}: {
view: EpisodeView;
onChange: (view: EpisodeView) => void;
}) {
return (
<div className="flex items-center rounded-lg border border-border/60 p-0.5">
{(
[
{ value: "list", label: "List view", Icon: List },
{ value: "cards", label: "Card view", Icon: LayoutGrid },
] as const
).map(({ value, label, Icon }) => (
<Button
key={value}
variant={view === value ? "secondary" : "ghost"}
size="icon-sm"
aria-label={label}
aria-pressed={view === value}
title={label}
onClick={() => onChange(value)}
>
<Icon />
</Button>
))}
</div>
);
}
export function SeasonEpisodes({
episodes,
view,
...actions
}: EpisodeActions & { episodes: Episode[]; view: EpisodeView }) {
if (view === "cards") {
return (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{episodes.map((ep) => (
<EpisodeCard key={ep.id} episode={ep} {...actions} />
))}
</div>
);
}
return (
<div className="space-y-2">
{episodes.map((ep) => (
<EpisodeRow key={ep.id} episode={ep} {...actions} />
))}
</div>
);
}
function episodeHref(entryId: number, seasonId: number, ep: Episode) {
return `/entry/${entryId}/season/${seasonId}/episode/${ep.id}`;
}
function stop(ev: React.MouseEvent, fn: () => void) {
ev.preventDefault();
ev.stopPropagation();
fn();
}
function SeenLabel({ episode }: { episode: Episode }) {
const dates = (episode.episodeSeens ?? []).map(
(s: EpisodeSeen) => s.date_seen,
);
if (dates.length === 0) return null;
if (dates.length === 1) {
return (
<span className="text-green-600 dark:text-green-400">
Seen {formatDate(dates[0])}
</span>
);
}
return (
<Tooltip>
<TooltipTrigger
render={
<span className="cursor-default text-green-600 underline decoration-dotted dark:text-green-400" />
}
>
Seen {dates.length} times
</TooltipTrigger>
<TooltipContent>
<div className="space-y-0.5 text-xs">
{dates.map((d, i) => (
<p key={i}>{formatDate(d)}</p>
))}
</div>
</TooltipContent>
</Tooltip>
);
}
function EpisodeMeta({ episode }: { episode: Episode }) {
return (
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
{episode.air_date && <span>{formatDate(episode.air_date)}</span>}
{episode.runtime ? (
<span className="inline-flex items-center gap-0.5">
<Clock className="h-3 w-3" />
{formatRuntime(episode.runtime)}
</span>
) : null}
{episode.tmdb_rating ? (
<span className="inline-flex items-center gap-0.5 tabular-nums">
<Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
{episode.tmdb_rating.toFixed(1)}
</span>
) : null}
<SeenLabel episode={episode} />
</div>
);
}
function TypeBadge({ episode }: { episode: Episode }) {
if (isEpisodeUpcoming(episode)) {
return (
<span className="rounded bg-sky-500/15 px-1.5 py-px text-[10px] font-semibold uppercase text-sky-600 dark:text-sky-400">
Upcoming
</span>
);
}
if (
episode.episode_type === "finale" ||
episode.episode_type === "mid_season"
) {
return (
<span className="rounded bg-violet-500/15 px-1.5 py-px text-[10px] font-semibold uppercase text-violet-600 dark:text-violet-400">
{episode.episode_type === "finale" ? "Finale" : "Mid-season"}
</span>
);
}
return null;
}
function Still({
episode,
size,
className,
onPlay,
}: {
episode: Episode;
size: string;
className: string;
onPlay: () => void;
}) {
return (
<div
className={`group/thumb relative shrink-0 cursor-pointer overflow-hidden bg-muted ${className}`}
onClick={(ev) => stop(ev, onPlay)}
role="button"
aria-label={`Play episode ${episode.episode_number}`}
>
{episode.still_path ? (
<img
src={getTmdbPosterUrl(episode.still_path, size)}
alt={episode.name}
loading="lazy"
className="h-full w-full object-cover transition duration-300 group-hover/thumb:scale-[1.03] group-hover/thumb:brightness-50"
/>
) : (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
No image
</div>
)}
<div className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover/thumb:opacity-100">
<PlayCircle className="h-9 w-9 text-white drop-shadow-lg" />
</div>
</div>
);
}
function WatchButton({
episode,
onClick,
}: {
episode: Episode;
onClick: () => void;
}) {
const watched = isEpisodeWatched(episode);
return (
<Button
size="icon"
variant={watched ? "secondary" : "outline"}
className="h-8 w-8 shrink-0"
aria-label={watched ? "Watch again" : "Mark as watched"}
title={watched ? "Add another watch" : "Mark as watched"}
onClick={(ev) => stop(ev, onClick)}
>
<Eye className="h-4 w-4" />
</Button>
);
}
function EpisodeRow({
episode,
entryId,
seasonId,
onPlay,
onMarkWatched,
}: EpisodeActions & { episode: Episode }) {
const watched = isEpisodeWatched(episode);
return (
<Link
to={episodeHref(entryId, seasonId, episode)}
className={`flex items-center gap-3 rounded-xl border p-2 transition-colors hover:bg-accent/40 sm:gap-4 sm:p-2.5 ${
watched ? "border-green-500/25 bg-green-500/[0.03]" : "border-border/60"
}`}
>
<Still
episode={episode}
size="w300"
className="h-16 w-28 rounded-lg sm:h-20 sm:w-36"
onPlay={() => onPlay(episode)}
/>
<div className="min-w-0 flex-1 space-y-1">
<div className="flex items-center gap-2">
<span className="text-xs font-semibold text-muted-foreground tabular-nums">
E{episode.episode_number}
</span>
<span className="truncate font-medium">{episode.name}</span>
{watched && (
<CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />
)}
<TypeBadge episode={episode} />
</div>
<EpisodeMeta episode={episode} />
{episode.overview && (
<p className="line-clamp-2 text-xs text-muted-foreground">
{episode.overview}
</p>
)}
</div>
<WatchButton episode={episode} onClick={() => onMarkWatched(episode)} />
</Link>
);
}
function EpisodeCard({
episode,
entryId,
seasonId,
onPlay,
onMarkWatched,
}: EpisodeActions & { episode: Episode }) {
const watched = isEpisodeWatched(episode);
return (
<Link
to={episodeHref(entryId, seasonId, episode)}
className="group flex flex-col overflow-hidden rounded-xl border border-border/60 bg-card/50 transition-colors hover:bg-accent/40"
>
<div className="relative">
<Still
episode={episode}
size="w780"
className="aspect-video w-full"
onPlay={() => onPlay(episode)}
/>
<span className="pointer-events-none absolute left-2 top-2 rounded-md bg-black/65 px-2 py-0.5 text-xs font-bold text-white tabular-nums backdrop-blur">
E{episode.episode_number}
</span>
{watched && (
<span className="pointer-events-none absolute right-2 top-2 inline-flex items-center gap-1 rounded-full bg-green-500/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow">
<CheckCircle2 className="h-3 w-3" />
Watched
</span>
)}
</div>
<div className="flex flex-1 flex-col gap-1.5 p-3">
<div className="flex items-start justify-between gap-2">
<p className="line-clamp-1 font-semibold">{episode.name}</p>
<TypeBadge episode={episode} />
</div>
<EpisodeMeta episode={episode} />
{episode.overview && (
<p className="line-clamp-3 text-xs text-muted-foreground">
{episode.overview}
</p>
)}
<div className="mt-auto flex justify-end pt-1">
<WatchButton
episode={episode}
onClick={() => onMarkWatched(episode)}
/>
</div>
</div>
</Link>
);
}
@@ -1,9 +1,16 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { ChevronDown, ChevronUp, Play } from "lucide-react";
import { Check, ChevronDown, ChevronUp, Eye } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { EpisodeViewToggle } from "@/components/entries/SeasonEpisodes";
import {
isEpisodeWatched,
loadSeasonView,
saveSeasonView,
type EpisodeView,
} from "@/lib/episodes";
import { getYear, getTmdbPosterUrl } from "@/lib/media-utils";
import type { Season } from "@/types";
@@ -12,8 +19,18 @@ interface SeasonsContainerProps {
entryId: number;
}
// How many seasons show before "Show all", per view
const COLLAPSED = { list: 2, cards: 4 } as const;
export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
const [expanded, setExpanded] = useState(false);
const [view, setView] = useState<EpisodeView>(loadSeasonView);
const [markingSeason, setMarkingSeason] = useState<Season | null>(null);
const changeView = (next: EpisodeView) => {
setView(next);
saveSeasonView(next);
};
// Sort: specials (season 0) at bottom, rest latest to oldest
const sorted = [...seasons].sort((a, b) => {
@@ -22,17 +39,42 @@ export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
return b.season_number - a.season_number;
});
const display = expanded ? sorted : sorted.slice(0, 2);
const limit = COLLAPSED[view];
const display = expanded ? sorted : sorted.slice(0, limit);
const nextToMark = markingSeason ? nextUnwatched(markingSeason) : undefined;
return (
<div className="space-y-3">
<div className="flex items-center justify-between gap-3">
<h3 className="text-lg font-semibold">Seasons</h3>
<div className="space-y-2">
<EpisodeViewToggle view={view} onChange={changeView} />
</div>
{view === "cards" ? (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-4">
{display.map((season) => (
<SeasonItem key={season.id} season={season} entryId={entryId} />
<SeasonCard
key={season.id}
season={season}
entryId={entryId}
onMarkWatched={() => setMarkingSeason(season)}
/>
))}
</div>
{sorted.length > 2 && (
) : (
<div className="space-y-2">
{display.map((season) => (
<SeasonRow
key={season.id}
season={season}
entryId={entryId}
onMarkWatched={() => setMarkingSeason(season)}
/>
))}
</div>
)}
{sorted.length > limit && (
<Button
variant="ghost"
size="sm"
@@ -51,36 +93,63 @@ export function SeasonsContainer({ seasons, entryId }: SeasonsContainerProps) {
)}
</Button>
)}
{/* Marks the season's next unwatched episode */}
{nextToMark && (
<EpisodeSeenEditDialog
open={!!markingSeason}
onOpenChange={(open) => {
if (!open) setMarkingSeason(null);
}}
mode="create"
episodeId={nextToMark.id}
entryId={entryId}
/>
)}
</div>
);
}
function SeasonItem({ season, entryId }: { season: Season; entryId: number }) {
const [dialogOpen, setDialogOpen] = useState(false);
const watchedCount =
season.episodes?.filter(
(ep) =>
ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0),
).length ?? 0;
const totalEpisodes = season.episode_count || season.episodes?.length || 0;
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0;
function seasonProgress(season: Season) {
const watched = season.episodes?.filter(isEpisodeWatched).length ?? 0;
const total = season.episode_count || season.episodes?.length || 0;
return {
watched,
total,
percent: total > 0 ? (watched / total) * 100 : 0,
};
}
const nextUnwatched = season.episodes
function nextUnwatched(season: Season) {
return season.episodes
?.slice()
.sort((a, b) => a.episode_number - b.episode_number)
.find(
(ep) =>
!ep.date_first_seen &&
(!ep.episodeSeens || ep.episodeSeens.length === 0),
);
.find((ep) => !isEpisodeWatched(ep));
}
function stop(ev: React.MouseEvent, fn: () => void) {
ev.preventDefault();
ev.stopPropagation();
fn();
}
function SeasonRow({
season,
entryId,
onMarkWatched,
}: {
season: Season;
entryId: number;
onMarkWatched: () => void;
}) {
const { watched, total, percent } = seasonProgress(season);
const canMark = !!nextUnwatched(season);
return (
<>
<Link
to={`/entry/${entryId}/season/${season.id}`}
className="flex items-center gap-4 rounded-lg border border-border p-3 transition-colors hover:bg-accent/50"
>
{/* Poster thumbnail */}
<div className="h-16 w-11 shrink-0 overflow-hidden rounded bg-muted">
<img
src={getTmdbPosterUrl(season.poster_path, "w92")}
@@ -90,48 +159,142 @@ function SeasonItem({ season, entryId }: { season: Season; entryId: number }) {
/>
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="font-medium text-sm truncate">{season.name}</span>
<span className="truncate text-sm font-medium">{season.name}</span>
<span className="text-xs text-muted-foreground">
{getYear(season.air_date)}
</span>
</div>
<div className="flex items-center gap-2 mt-1">
<Progress value={progress} className="h-1.5 flex-1" />
<span className="text-xs text-muted-foreground shrink-0">
{watchedCount}/{totalEpisodes}
<div className="mt-1 flex items-center gap-2">
<Progress value={percent} className="h-1.5 flex-1" />
<span className="shrink-0 text-xs text-muted-foreground">
{watched}/{total}
</span>
</div>
</div>
{/* Quick watch button - opens dialog */}
{nextUnwatched && (
{canMark && (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setDialogOpen(true);
}}
aria-label="Mark next episode as watched"
title="Mark next episode as watched"
onClick={(e) => stop(e, onMarkWatched)}
>
<Play className="h-4 w-4" />
<Eye className="h-4 w-4" />
</Button>
)}
</Link>
);
}
{nextUnwatched && dialogOpen && (
<EpisodeSeenEditDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
mode="create"
episodeId={nextUnwatched.id}
entryId={entryId}
function SeasonCard({
season,
entryId,
onMarkWatched,
}: {
season: Season;
entryId: number;
onMarkWatched: () => void;
}) {
const { watched, total, percent } = seasonProgress(season);
const canMark = !!nextUnwatched(season);
return (
<Link
to={`/entry/${entryId}/season/${season.id}`}
className="group flex flex-col overflow-hidden rounded-xl border border-border/60 bg-card/50 transition-colors hover:bg-accent/40"
>
<div className="aspect-2/3 overflow-hidden bg-muted">
<img
src={getTmdbPosterUrl(season.poster_path, "w342")}
alt={season.name}
loading="lazy"
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"
/>
</div>
<div className="flex items-center gap-2 p-2.5">
<div className="min-w-0 flex-1">
<p className="line-clamp-1 text-sm font-semibold">{season.name}</p>
<p className="text-xs text-muted-foreground tabular-nums">
{[getYear(season.air_date), `${watched}/${total} eps`]
.filter(Boolean)
.join(" · ")}
</p>
</div>
<ProgressRing
percent={percent}
done={total > 0 && watched >= total}
onClick={canMark ? (e) => stop(e, onMarkWatched) : undefined}
/>
</div>
</Link>
);
}
/** Circular progress with the mark-as-watched button in the middle. */
function ProgressRing({
percent,
done,
onClick,
}: {
percent: number;
done: boolean;
onClick?: (e: React.MouseEvent) => void;
}) {
const size = 44;
const stroke = 3.5;
const radius = (size - stroke) / 2;
const circumference = 2 * Math.PI * radius;
const offset = circumference * (1 - Math.min(100, percent) / 100);
return (
<div
className="relative shrink-0"
style={{ width: size, height: size }}
title={`${Math.round(percent)}% watched`}
>
<svg width={size} height={size} className="-rotate-90" aria-hidden="true">
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
strokeWidth={stroke}
className="stroke-muted"
/>
<circle
cx={size / 2}
cy={size / 2}
r={radius}
fill="none"
strokeWidth={stroke}
strokeLinecap="round"
strokeDasharray={circumference}
strokeDashoffset={offset}
className={`transition-[stroke-dashoffset] duration-500 ${
done ? "stroke-green-500" : "stroke-primary"
}`}
/>
</svg>
{done ? (
<span className="absolute inset-0 flex items-center justify-center text-green-500">
<Check className="h-4 w-4" />
</span>
) : (
<button
type="button"
onClick={onClick}
disabled={!onClick}
aria-label="Mark next episode as watched"
title="Mark next episode as watched"
className="absolute inset-1.5 flex items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none"
>
<Eye className="h-4 w-4" />
</button>
)}
</>
</div>
);
}
@@ -0,0 +1,59 @@
import { useState } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import type { TmdbVideo } from "@/types";
/** Plays an entry's stored TMDB YouTube videos; trailers come first. */
export function TrailerDialog({
open,
onOpenChange,
title,
videos,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
videos: TmdbVideo[];
}) {
const [activeKey, setActiveKey] = useState(videos[0]?.key);
const active = videos.find((v) => v.key === activeKey) ?? videos[0];
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-full max-w-4xl! gap-3 p-3">
<DialogTitle className="pr-8 text-sm">
{title} · {active?.name}
</DialogTitle>
{active && (
<div className="aspect-video w-full overflow-hidden rounded-lg bg-black">
<iframe
key={active.key}
src={`https://www.youtube-nocookie.com/embed/${active.key}?autoplay=1&rel=0`}
title={active.name}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
className="h-full w-full"
/>
</div>
)}
{videos.length > 1 && (
<div className="flex gap-2 overflow-x-auto pb-1">
{videos.map((v) => (
<button
key={v.key}
type="button"
onClick={() => setActiveKey(v.key)}
className={`shrink-0 rounded-md border px-2.5 py-1 text-xs transition-colors ${
v.key === active?.key
? "border-foreground/30 bg-accent font-medium"
: "border-border/60 text-muted-foreground hover:text-foreground"
}`}
>
{v.type}: {v.name}
</button>
))}
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,121 @@
import { useState } from "react";
import { ExternalLink } from "lucide-react";
import { getTmdbImageUrl } from "@/lib/api";
import type { WatchProvider, WatchProviderRegion } from "@/types";
const CATEGORIES: { key: keyof WatchProviderRegion; label: string }[] = [
{ key: "flatrate", label: "Stream" },
{ key: "free", label: "Free" },
{ key: "ads", label: "With ads" },
{ key: "rent", label: "Rent" },
{ key: "buy", label: "Buy" },
];
/** Country from the browser locale (en-US → US), falling back to US. */
function defaultRegion(available: string[]): string {
const fromLocale = navigator.language?.split("-")[1]?.toUpperCase();
if (fromLocale && available.includes(fromLocale)) return fromLocale;
if (available.includes("US")) return "US";
return available[0];
}
const regionName = (() => {
try {
const names = new Intl.DisplayNames(["en"], { type: "region" });
return (code: string) => names.of(code) ?? code;
} catch {
return (code: string) => code;
}
})();
export function WatchProvidersCard({
providers,
}: {
providers: Record<string, WatchProviderRegion> | null | undefined;
}) {
const regions = Object.keys(providers ?? {}).sort((a, b) =>
regionName(a).localeCompare(regionName(b)),
);
const [region, setRegion] = useState(() =>
regions.length ? defaultRegion(regions) : "",
);
if (!providers || regions.length === 0) return null;
const info = providers[region] ?? providers[regions[0]];
const groups = CATEGORIES.map((c) => ({
...c,
list: (info[c.key] as WatchProvider[] | null | undefined) ?? [],
})).filter((g) => g.list.length > 0);
return (
<div className="rounded-xl border border-border/60 bg-card/50 p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Where to watch
</h3>
<select
value={region}
onChange={(e) => setRegion(e.target.value)}
className="max-w-36 rounded-md border border-border/60 bg-background px-1.5 py-0.5 text-xs"
aria-label="Country"
>
{regions.map((r) => (
<option key={r} value={r}>
{regionName(r)}
</option>
))}
</select>
</div>
{groups.length === 0 ? (
<p className="text-sm text-muted-foreground">
Not available in {regionName(region)}.
</p>
) : (
<div className="space-y-3">
{groups.map((g) => (
<div key={g.key} className="space-y-1.5">
<p className="text-[11px] font-medium text-muted-foreground">
{g.label}
</p>
<div className="flex flex-wrap gap-1.5">
{g.list
.slice()
.sort(
(a, b) =>
(a.display_priority ?? 99) - (b.display_priority ?? 99),
)
.map((p) => (
<img
key={p.provider_id}
src={
p.logo_path
? getTmdbImageUrl(p.logo_path, "w92")
: undefined
}
alt={p.provider_name}
title={p.provider_name}
className="h-9 w-9 rounded-lg object-cover ring-1 ring-border/60"
/>
))}
</div>
</div>
))}
</div>
)}
{info.link && (
<a
href={info.link}
target="_blank"
rel="noopener noreferrer"
className="mt-3 inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
Data from JustWatch via TMDB
</a>
)}
</div>
);
}
@@ -0,0 +1,136 @@
import { Link } from "react-router-dom";
import { Film, Tv, Users } from "lucide-react";
import {
MONTH_NAMES,
formatMinutes,
posterUrl,
sessionEpisodeLabel,
sessionLink,
type HistorySession,
type MonthGroup,
} from "@/lib/history";
/** Month sections (newest first), each split into days. */
export function HistoryList({ months }: { months: MonthGroup[] }) {
return (
<div className="space-y-10">
{months.map((m) => (
<section key={m.month} className="space-y-3">
<header className="sticky top-0 z-10 -mx-1 flex flex-wrap items-baseline justify-between gap-2 border-b border-border/60 bg-background/90 px-1 py-2 backdrop-blur">
<h2 className="text-xl font-bold tracking-tight">
{MONTH_NAMES[m.month]}
</h2>
<p className="text-xs text-muted-foreground tabular-nums">
{[
m.movies > 0 &&
`${m.movies} ${m.movies === 1 ? "movie" : "movies"}`,
m.episodes > 0 &&
`${m.episodes} ${m.episodes === 1 ? "episode" : "episodes"}`,
m.minutes > 0 && formatMinutes(m.minutes),
]
.filter(Boolean)
.join(" · ")}
</p>
</header>
<div className="space-y-5">
{groupByDay(m.sessions).map(([day, sessions]) => (
<div key={day} className="grid gap-2 sm:grid-cols-[7rem_1fr]">
<p className="pt-2 text-sm font-medium text-muted-foreground">
{new Date(sessions[0].date).toLocaleDateString("en-US", {
weekday: "short",
month: "short",
day: "numeric",
})}
</p>
<div className="space-y-1.5">
{sessions.map((s) => (
<HistoryRow key={s.key} session={s} />
))}
</div>
</div>
))}
</div>
</section>
))}
</div>
);
}
function groupByDay(sessions: HistorySession[]) {
const days = new Map<string, HistorySession[]>();
for (const s of sessions) {
const list = days.get(s.day) ?? [];
list.push(s);
days.set(s.day, list);
}
return [...days.entries()];
}
function HistoryRow({ session }: { session: HistorySession }) {
const entry = session.entry;
const isMovie = session.kind === "movie";
const single = session.events.length === 1 ? session.events[0] : null;
const buddies = [
...new Map(
session.events.flatMap((e) => e.buddies).map((b) => [b.id, b]),
).values(),
];
return (
<Link
to={sessionLink(session)}
className="group flex items-center gap-3 rounded-lg border border-transparent p-1.5 transition-colors hover:border-border/60 hover:bg-accent/40"
>
<img
src={posterUrl(entry)}
alt=""
loading="lazy"
className="h-16 w-11 shrink-0 rounded-md object-cover ring-1 ring-border/60"
/>
<div className="min-w-0 flex-1">
<p className="line-clamp-1 font-medium">
{entry?.title ?? "Unknown title"}
</p>
<p className="line-clamp-1 text-xs text-muted-foreground">
{isMovie ? (
<span className="inline-flex items-center gap-1">
<Film className="h-3 w-3" /> Movie
{entry?.release_date &&
` · ${new Date(entry.release_date).getFullYear()}`}
</span>
) : (
<span className="inline-flex items-center gap-1">
<Tv className="h-3 w-3" />
{sessionEpisodeLabel(session)}
{single?.episode?.name
? ` · ${single.episode.name}`
: ` · ${session.events.length} episodes`}
</span>
)}
</p>
</div>
<div className="flex shrink-0 flex-col items-end gap-1 text-xs text-muted-foreground">
{session.minutes > 0 && (
<span className="tabular-nums">{formatMinutes(session.minutes)}</span>
)}
{session.unknownDate && (
<span className="rounded bg-amber-500/15 px-1.5 py-px text-[10px] font-medium text-amber-600 dark:text-amber-400">
Date unknown
</span>
)}
{buddies.length > 0 && (
<span
className="inline-flex items-center gap-1"
title={buddies.map((b) => b.name).join(", ")}
>
<Users className="h-3 w-3" />
<span className="max-w-28 truncate">
{buddies.map((b) => b.name).join(", ")}
</span>
</span>
)}
</div>
</Link>
);
}
@@ -0,0 +1,152 @@
import { Link } from "react-router-dom";
import { Film, Tv } from "lucide-react";
import {
MONTH_NAMES,
formatMinutes,
posterUrl,
sessionEpisodeLabel,
sessionLink,
type HistorySession,
type MonthGroup,
} from "@/lib/history";
/**
* Vertical timeline, latest watch at the top down to January. Episodes of a
* show watched back to back on the same day are stacked into one card.
*/
export function HistoryTimeline({ months }: { months: MonthGroup[] }) {
let index = 0; // alternates sides across the whole year
return (
<div className="relative mx-auto max-w-4xl pb-6">
{/* The line */}
<div className="absolute bottom-0 left-4 top-0 w-px bg-border md:left-1/2 md:-translate-x-1/2" />
{months.map((m) => (
<section key={m.month} className="relative">
{/* Month divider */}
<div className="relative flex items-center py-6 md:justify-center">
<div className="absolute inset-x-0 top-1/2 h-px bg-linear-to-r from-transparent via-border to-transparent" />
<span className="relative ml-8 rounded-full border border-border bg-background px-4 py-1 text-sm font-semibold shadow-sm md:ml-0">
{MONTH_NAMES[m.month]}
<span className="ml-2 text-xs font-normal text-muted-foreground tabular-nums">
{m.movies + m.episodes} watched
</span>
</span>
</div>
<ol className="space-y-6">
{m.sessions.map((s) => {
const side = index++ % 2 === 0 ? "left" : "right";
return <TimelineItem key={s.key} session={s} side={side} />;
})}
</ol>
</section>
))}
</div>
);
}
function TimelineItem({
session,
side,
}: {
session: HistorySession;
side: "left" | "right";
}) {
const entry = session.entry;
const count = session.events.length;
const isMovie = session.kind === "movie";
const date = new Date(session.date).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
});
return (
<li
className={`relative flex pl-12 md:w-1/2 md:pl-0 ${
side === "left"
? "md:mr-auto md:justify-end md:pr-10"
: "md:ml-auto md:pl-10"
}`}
>
{/* Dot on the line */}
<span
className={`absolute top-6 left-4 h-3 w-3 -translate-x-1/2 rounded-full ring-4 ring-background ${
isMovie ? "bg-amber-500" : "bg-sky-500"
} ${side === "left" ? "md:right-0 md:left-auto md:translate-x-1/2" : "md:left-0"}`}
/>
<Link
to={sessionLink(session)}
className={`group flex w-full max-w-sm items-start gap-3 rounded-xl border border-border/60 bg-card/60 p-2.5 transition-colors hover:bg-accent/40 ${
side === "left" ? "md:flex-row-reverse md:text-right" : ""
}`}
>
{/* Poster, stacked for multi-episode sessions */}
<div className="relative shrink-0">
{count > 1 && (
<>
<img
src={posterUrl(entry)}
alt=""
className="absolute inset-0 h-full w-full translate-x-2 -translate-y-1 rotate-6 rounded-lg object-cover opacity-40"
/>
<img
src={posterUrl(entry)}
alt=""
className="absolute inset-0 h-full w-full translate-x-1 rotate-3 rounded-lg object-cover opacity-70"
/>
</>
)}
<img
src={posterUrl(entry, "w342")}
alt=""
loading="lazy"
className="relative h-28 w-[4.7rem] rounded-lg object-cover shadow-md ring-1 ring-border/60 transition-transform group-hover:scale-[1.03]"
/>
{count > 1 && (
<span className="absolute -bottom-1.5 -right-1.5 rounded-full bg-sky-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow">
×{count}
</span>
)}
</div>
<div className="min-w-0 flex-1 space-y-1 py-0.5">
<p className="text-xs font-medium text-muted-foreground">
{date}
{session.unknownDate && (
<span className="ml-1.5 rounded bg-amber-500/15 px-1 py-px text-[10px] text-amber-600 dark:text-amber-400">
date unknown
</span>
)}
</p>
<p className="line-clamp-2 font-semibold leading-tight">
{entry?.title ?? "Unknown title"}
</p>
<p
className={`flex items-center gap-1 text-xs text-muted-foreground ${
side === "left" ? "md:justify-end" : ""
}`}
>
{isMovie ? (
<Film className="h-3 w-3" />
) : (
<Tv className="h-3 w-3" />
)}
{isMovie
? "Movie"
: count > 1
? `${sessionEpisodeLabel(session)} · ${count} episodes`
: `${sessionEpisodeLabel(session)} · ${session.events[0].episode?.name ?? ""}`}
</p>
{session.minutes > 0 && (
<p className="text-[11px] text-muted-foreground/80 tabular-nums">
{formatMinutes(session.minutes)}
</p>
)}
</div>
</Link>
</li>
);
}
@@ -0,0 +1,496 @@
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import {
CalendarDays,
Clapperboard,
Flame,
Popcorn,
Repeat,
Sparkles,
Star,
Tv,
Users,
Zap,
} from "lucide-react";
import { getTmdbImageUrl } from "@/lib/api";
import {
MONTH_NAMES,
WEEKDAY_NAMES,
episodeCode,
formatMinutes,
posterUrl,
type YearReview,
} from "@/lib/history";
import type { HistoryEntry, HistoryEvent } from "@/api/history";
const formatDay = (day: string) =>
new Date(`${day}T12:00:00`).toLocaleDateString("en-US", {
weekday: "long",
month: "long",
day: "numeric",
});
export function YearInReview({
year,
review,
entries,
}: {
year: number;
review: YearReview;
entries: Record<number, HistoryEntry>;
}) {
const hours = Math.round(review.totalMinutes / 60);
const maxMonth = Math.max(1, ...review.monthly.map((m) => m.minutes));
const maxWeekday = Math.max(1, ...review.weekdays);
const topWeekday = review.weekdays.indexOf(Math.max(...review.weekdays));
const topMonth = review.monthly.findIndex((m) => m.minutes === maxMonth);
return (
<div className="space-y-6">
{/* Hero */}
<section className="relative overflow-hidden rounded-3xl bg-linear-to-br from-fuchsia-600 via-violet-600 to-indigo-700 p-8 text-white shadow-xl sm:p-10">
<div className="absolute -right-16 -top-16 h-64 w-64 rounded-full bg-white/10 blur-2xl" />
<div className="absolute -bottom-20 left-1/3 h-56 w-56 rounded-full bg-amber-300/20 blur-3xl" />
<div className="relative space-y-6">
<p className="inline-flex items-center gap-2 text-sm font-medium uppercase tracking-[0.2em] text-white/80">
<Sparkles className="h-4 w-4" /> Your {year} in review
</p>
<div>
<p className="text-6xl font-black tracking-tight tabular-nums sm:text-8xl">
{hours.toLocaleString()}
</p>
<p className="text-lg font-medium text-white/85">
hours of movies and TV
{hours >= 24 && (
<span className="text-white/70">
{" "}
— that's {Math.round(hours / 24)} full days
</span>
)}
</p>
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<HeroStat label="Movies" value={review.uniqueMovies} />
<HeroStat label="Episodes" value={review.episodeWatches} />
<HeroStat label="Shows" value={review.uniqueShows} />
<HeroStat label="Days watching" value={review.activeDays} />
</div>
</div>
</section>
{/* Highlights */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{review.longestStreak && review.longestStreak.days > 1 && (
<HighlightCard
icon={<Flame />}
tone="from-orange-500/20 to-red-500/10"
label="Longest streak"
value={`${review.longestStreak.days} days`}
detail={`${shortDay(review.longestStreak.start)} – ${shortDay(review.longestStreak.end)}`}
/>
)}
{review.busiestDay && (
<HighlightCard
icon={<CalendarDays />}
tone="from-sky-500/20 to-cyan-500/10"
label="Busiest day"
value={formatMinutes(review.busiestDay.minutes)}
detail={`${formatDay(review.busiestDay.day)} · ${review.busiestDay.watches} watched`}
/>
)}
{review.biggestBinge && (
<HighlightCard
icon={<Zap />}
tone="from-violet-500/20 to-fuchsia-500/10"
label="Biggest binge"
value={`${review.biggestBinge.episodes} episodes`}
detail={`${review.biggestBinge.entry.title} · ${shortDay(review.biggestBinge.day)}`}
poster={posterUrl(review.biggestBinge.entry)}
/>
)}
<HighlightCard
icon={<Star />}
tone="from-amber-500/20 to-yellow-500/10"
label="Favorite day"
value={WEEKDAY_NAMES[topWeekday]}
detail={`and ${MONTH_NAMES[topMonth]} was your biggest month`}
/>
</div>
<div className="grid gap-6 lg:grid-cols-2">
{/* Top shows */}
{review.topShows.length > 0 && (
<Card title="Top shows" icon={<Tv />}>
<ol className="space-y-2.5">
{review.topShows.map((s, i) => (
<li key={s.entry.id}>
<Link
to={`/entry/${s.entry.id}`}
className="flex items-center gap-3 rounded-lg p-1 transition-colors hover:bg-accent/50"
>
<span className="w-7 text-center text-2xl font-black text-muted-foreground/60 tabular-nums">
{i + 1}
</span>
<img
src={posterUrl(s.entry)}
alt=""
className="h-14 w-10 rounded object-cover ring-1 ring-border/60"
/>
<div className="min-w-0 flex-1">
<p className="line-clamp-1 font-semibold">
{s.entry.title}
</p>
<p className="text-xs text-muted-foreground">
{s.episodes} episodes · {formatMinutes(s.minutes)}
</p>
</div>
</Link>
</li>
))}
</ol>
</Card>
)}
{/* Genres */}
{review.topGenres.length > 0 && (
<Card title="Top genres" icon={<Clapperboard />}>
<div className="space-y-3">
{review.topGenres.map((g, i) => (
<div key={g.name} className="space-y-1">
<div className="flex justify-between text-sm">
<span className="font-medium">{g.name}</span>
<span className="text-muted-foreground tabular-nums">
{Math.round(g.share * 100)}%
</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-muted">
<div
className="h-full rounded-full bg-linear-to-r from-violet-500 to-fuchsia-500"
style={{
width: `${(g.minutes / review.topGenres[0].minutes) * 100}%`,
opacity: 1 - i * 0.1,
}}
/>
</div>
</div>
))}
</div>
</Card>
)}
</div>
{/* Monthly activity */}
<Card title="Month by month" icon={<CalendarDays />}>
<div className="flex h-44 items-end gap-1.5 sm:gap-3">
{review.monthly.map((m, i) => (
<div key={i} className="flex flex-1 flex-col items-center gap-1.5">
<div className="flex h-36 w-full items-end">
<div
title={`${MONTH_NAMES[i]}: ${formatMinutes(m.minutes)} · ${m.movies} movies · ${m.episodes} episodes`}
className={`w-full rounded-t-md transition-all ${
i === topMonth
? "bg-linear-to-t from-fuchsia-600 to-violet-400"
: "bg-linear-to-t from-violet-500/50 to-violet-400/30"
}`}
style={{
height: `${Math.max(2, (m.minutes / maxMonth) * 100)}%`,
}}
/>
</div>
<span className="text-[10px] font-medium text-muted-foreground">
{MONTH_NAMES[i].slice(0, 3)}
</span>
</div>
))}
</div>
</Card>
<div className="grid gap-6 lg:grid-cols-3">
{/* Top rated movies */}
{review.topMovies.length > 0 && (
<Card
title="Your top-rated movies"
icon={<Popcorn />}
className="lg:col-span-2"
>
<div className="grid grid-cols-3 gap-3 sm:grid-cols-5">
{review.topMovies.map((m) => (
<Link
key={m.entry.id}
to={`/entry/${m.entry.id}`}
className="group space-y-1.5"
>
<img
src={posterUrl(m.entry, "w342")}
alt={m.entry.title}
className="aspect-2/3 w-full rounded-lg object-cover ring-1 ring-border/60 transition-transform group-hover:scale-[1.03]"
/>
<p className="line-clamp-1 text-xs font-medium">
{m.entry.title}
</p>
<p className="inline-flex items-center gap-0.5 text-xs text-muted-foreground tabular-nums">
<Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
{m.rating}/10
</p>
</Link>
))}
</div>
</Card>
)}
{/* Weekdays */}
<Card title="When you watch" icon={<CalendarDays />}>
<div className="space-y-2">
{review.weekdays.map((n, d) => (
<div key={d} className="flex items-center gap-2 text-xs">
<span className="w-8 text-muted-foreground">
{WEEKDAY_NAMES[d]}
</span>
<div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">
<div
className={`h-full rounded-full ${d === topWeekday ? "bg-amber-500" : "bg-amber-500/40"}`}
style={{ width: `${(n / maxWeekday) * 100}%` }}
/>
</div>
<span className="w-8 text-right tabular-nums text-muted-foreground">
{n}
</span>
</div>
))}
</div>
</Card>
</div>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{review.rewatches.length > 0 && (
<Card title="On repeat" icon={<Repeat />}>
<ul className="space-y-2">
{review.rewatches.map((r) => (
<li
key={r.entry.id}
className="flex items-center justify-between gap-2 text-sm"
>
<Link
to={`/entry/${r.entry.id}`}
className="line-clamp-1 hover:underline"
>
{r.entry.title}
</Link>
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs tabular-nums">
×{r.watches}
</span>
</li>
))}
</ul>
</Card>
)}
{review.topNetworks.length > 0 && (
<Card title="Top networks" icon={<Tv />}>
<ul className="space-y-2.5">
{review.topNetworks.map((n) => (
<li
key={n.name}
className="flex items-center justify-between gap-2 text-sm"
>
{n.logo_path ? (
<img
src={getTmdbImageUrl(n.logo_path, "w92")}
alt={n.name}
title={n.name}
className="h-5 max-w-24 object-contain dark:invert dark:brightness-200"
/>
) : (
<span>{n.name}</span>
)}
<span className="text-xs text-muted-foreground tabular-nums">
{n.episodes} eps
</span>
</li>
))}
</ul>
</Card>
)}
{review.topBuddies.length > 0 && (
<Card title="Watched together" icon={<Users />}>
<ul className="space-y-2">
{review.topBuddies.map((b) => (
<li
key={b.id}
className="flex items-center justify-between gap-2 text-sm"
>
<Link
to={`/watch-buddies/${b.id}`}
className="hover:underline"
>
{b.name}
</Link>
<span className="text-xs text-muted-foreground tabular-nums">
{b.watches} watches
</span>
</li>
))}
</ul>
</Card>
)}
</div>
{/* Started shows */}
{review.startedShows.length > 0 && (
<Card
title={`New shows you started (${review.startedShows.length})`}
icon={<Sparkles />}
>
<div className="flex gap-3 overflow-x-auto pb-2">
{review.startedShows.map((e) => (
<Link
key={e.id}
to={`/entry/${e.id}`}
className="w-24 shrink-0 space-y-1"
>
<img
src={posterUrl(e, "w342")}
alt={e.title}
className="aspect-2/3 w-full rounded-lg object-cover ring-1 ring-border/60"
/>
<p className="line-clamp-1 text-xs">{e.title}</p>
</Link>
))}
</div>
</Card>
)}
{/* Bookends */}
{review.first && review.last && (
<div className="grid gap-4 sm:grid-cols-2">
<BookendCard
label={`First watch of ${year}`}
event={review.first}
entries={entries}
/>
<BookendCard
label={`Last watch of ${year}`}
event={review.last}
entries={entries}
/>
</div>
)}
</div>
);
}
const shortDay = (day: string) =>
new Date(`${day}T12:00:00`).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
});
function HeroStat({ label, value }: { label: string; value: number }) {
return (
<div className="rounded-2xl bg-white/10 px-4 py-3 backdrop-blur">
<p className="text-3xl font-bold tabular-nums">
{value.toLocaleString()}
</p>
<p className="text-xs font-medium uppercase tracking-wider text-white/75">
{label}
</p>
</div>
);
}
function HighlightCard({
icon,
tone,
label,
value,
detail,
poster,
}: {
icon: ReactNode;
tone: string;
label: string;
value: string;
detail: string;
poster?: string;
}) {
return (
<div
className={`relative overflow-hidden rounded-2xl border border-border/60 bg-linear-to-br ${tone} p-5`}
>
{poster && (
<img
src={poster}
alt=""
className="absolute -right-4 -bottom-6 h-32 w-24 rotate-12 rounded-lg object-cover opacity-30"
/>
)}
<div className="relative space-y-1">
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground [&_svg]:h-3.5 [&_svg]:w-3.5">
{icon}
{label}
</p>
<p className="text-3xl font-black tracking-tight">{value}</p>
<p className="line-clamp-2 text-xs text-muted-foreground">{detail}</p>
</div>
</div>
);
}
function Card({
title,
icon,
children,
className = "",
}: {
title: string;
icon: ReactNode;
children: ReactNode;
className?: string;
}) {
return (
<section
className={`rounded-2xl border border-border/60 bg-card/60 p-5 ${className}`}
>
<h3 className="mb-4 flex items-center gap-2 text-sm font-semibold [&_svg]:h-4 [&_svg]:w-4 [&_svg]:text-muted-foreground">
{icon}
{title}
</h3>
{children}
</section>
);
}
function BookendCard({
label,
event,
entries,
}: {
label: string;
event: HistoryEvent;
entries: Record<number, HistoryEntry>;
}) {
const entry = entries[event.entry_id];
return (
<div className="flex items-center gap-4 rounded-2xl border border-border/60 bg-card/60 p-4">
<img
src={posterUrl(entry, "w342")}
alt=""
className="h-24 w-16 rounded-lg object-cover ring-1 ring-border/60"
/>
<div className="min-w-0 space-y-0.5">
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
{label}
</p>
<p className="line-clamp-1 text-lg font-bold">{entry?.title}</p>
<p className="text-xs text-muted-foreground">
{event.kind === "episode" && `${episodeCode(event.episode)} · `}
{new Date(event.date_seen).toLocaleDateString("en-US", {
month: "long",
day: "numeric",
})}
</p>
</div>
</div>
);
}
@@ -12,9 +12,7 @@ import { Sidebar, MobileSidebarContent } from "./Sidebar";
import { TitleBar } from "./TitleBar";
import { CommandPalette } from "@/components/CommandPalette";
import { useCommandPaletteStore } from "@/stores/useCommandPaletteStore";
const isElectron =
import.meta.env.VITE_ELECTRON === "true" || !!window.electron?.isElectron;
import { isDesktop } from "@/lib/platform";
export function AppLayout() {
const [mobileOpen, setMobileOpen] = useState(false);
@@ -62,7 +60,7 @@ export function AppLayout() {
return (
<div className="flex h-screen flex-col overflow-hidden">
{isElectron && <TitleBar />}
{isDesktop && <TitleBar />}
<CommandPalette />
<div className="flex flex-1 overflow-hidden">
@@ -14,6 +14,7 @@ import {
Sun,
Film,
Video,
History,
} from "lucide-react";
import { useThemeStore } from "@/stores/useThemeStore";
import { Separator } from "@/components/ui/separator";
@@ -26,6 +27,7 @@ const mainNav = [
const libraryNav = [
{ to: "/library", icon: Library, label: "Library" },
{ to: "/watchlist", icon: ListVideo, label: "Watchlist" },
{ to: "/history", icon: History, label: "History" },
{ to: "/collections", icon: FolderOpen, label: "Collections" },
{ to: "/media", icon: Image, label: "Media" },
{ to: "/discovery-videos", icon: Video, label: "Discover" },
@@ -1,17 +1,36 @@
import { Minus, Square, X } from "lucide-react";
import { isTauri } from "@/lib/platform";
// Loaded only inside the Tauri shell so web and Electron bundles don't pull it in eagerly.
const tauriWindow = async () => {
const { getCurrentWindow } = await import("@tauri-apps/api/window");
return getCurrentWindow();
};
const minimize = () =>
isTauri
? void tauriWindow().then((w) => w.minimize())
: window.electron?.windowControls.minimize();
const maximize = () =>
isTauri
? void tauriWindow().then((w) => w.toggleMaximize())
: window.electron?.windowControls.maximize();
const close = () =>
isTauri
? void tauriWindow().then((w) => w.close())
: window.electron?.windowControls.close();
export function TitleBar() {
const minimize = () => window.electron?.windowControls.minimize();
const maximize = () => window.electron?.windowControls.maximize();
const close = () => window.electron?.windowControls.close();
return (
// Electron drags via -webkit-app-region; Tauri via data-tauri-drag-region,
// which only applies to the element that carries it (not its children).
<div
data-tauri-drag-region
className="flex h-14 select-none items-center justify-between border-b border-border bg-background"
style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
>
<div className="flex items-center gap-2 pl-3">
<span className="text-xs font-semibold tracking-wide text-foreground/80">
<div data-tauri-drag-region className="flex h-full flex-1 items-center gap-2 pl-3">
<span className="pointer-events-none text-xs font-semibold tracking-wide text-foreground/80">
SHOWY
</span>
</div>
@@ -154,28 +154,39 @@ export function CollectionDetailsSkeleton() {
export function EntryDetailsSkeleton() {
return (
<div className="animate-in fade-in duration-300">
<div className="h-52 -mx-6 -mt-6 bg-muted animate-pulse rounded-b-lg" />
<div className="max-w-4xl mx-auto flex gap-8 -mt-24">
<div className="w-44 shrink-0 space-y-3">
<Skeleton className="aspect-[2/3] w-full rounded-xl" />
<Skeleton className="h-9 w-full rounded-lg" />
<Skeleton className="h-9 w-full rounded-lg" />
<Skeleton className="h-9 w-full rounded-lg" />
</div>
<div className="flex-1 space-y-4 pt-24">
<Skeleton className="h-9 w-72" />
<Skeleton className="h-4 w-32" />
<div className="flex gap-2">
<Skeleton className="h-5 w-12" />
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
<div className="relative -mx-4 -mt-4 bg-muted/40 md:-mx-6 md:-mt-6">
<div className="mx-auto flex max-w-6xl flex-col items-center gap-6 px-4 pb-8 pt-28 sm:flex-row sm:items-end sm:gap-8 sm:pt-44 md:px-6">
<Skeleton className="aspect-[2/3] w-40 shrink-0 rounded-xl sm:w-52 lg:w-60" />
<div className="w-full flex-1 space-y-4">
<Skeleton className="h-5 w-24 rounded-full" />
<Skeleton className="h-12 w-3/4 max-w-md" />
<Skeleton className="h-4 w-48" />
<div className="flex gap-1.5">
<Skeleton className="h-6 w-16 rounded-full" />
<Skeleton className="h-6 w-20 rounded-full" />
<Skeleton className="h-6 w-14 rounded-full" />
</div>
<div className="flex gap-2">
<Skeleton className="h-8 w-24 rounded-full" />
<Skeleton className="h-8 w-24 rounded-full" />
<Skeleton className="h-8 w-20 rounded-full" />
<Skeleton className="h-11 w-36 rounded-md" />
<Skeleton className="h-11 w-28 rounded-md" />
<Skeleton className="h-11 w-11 rounded-full" />
<Skeleton className="h-11 w-11 rounded-full" />
</div>
<Skeleton className="h-20 w-full" />
</div>
</div>
</div>
<div className="mx-auto mt-4 grid max-w-6xl gap-10 lg:grid-cols-[minmax(0,1fr)_300px]">
<div className="space-y-3">
<Skeleton className="h-6 w-28" />
<Skeleton className="h-24 w-full" />
</div>
<div className="space-y-4">
<div className="grid grid-cols-3 gap-2">
<Skeleton className="h-20 rounded-xl" />
<Skeleton className="h-20 rounded-xl" />
<Skeleton className="h-20 rounded-xl" />
</div>
<Skeleton className="h-40 rounded-xl" />
</div>
</div>
</div>
+62 -1
View File
@@ -2,13 +2,19 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { entriesApi } from "@/api/entries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import type { Entry } from "@/types";
import type { ArtworkType, Entry } from "@/types";
export const entryKeys = {
all: ["entries"] as const,
detail: (id: number) => ["entries", id] as const,
seasons: (id: number) => ["entries", id, "seasons"] as const,
credits: (id: number) => ["entries", id, "credits"] as const,
recommendations: (id: number) => ["entries", id, "recommendations"] as const,
artwork: (id: number) => ["entries", id, "artwork"] as const,
tmdbArtwork: (tmdbId: number, type: string) =>
["entries", "tmdb-artwork", type, tmdbId] as const,
tmdbRecommendations: (tmdbId: number, type: string) =>
["entries", "tmdb-recommendations", type, tmdbId] as const,
tmdbPreview: (tmdbId: number, type: string) =>
["entries", "tmdb-preview", type, tmdbId] as const,
};
@@ -43,6 +49,61 @@ export function useEntrySeasons(id: number) {
});
}
export function useEntryRecommendations(id: number) {
return useQuery({
queryKey: entryKeys.recommendations(id),
queryFn: () => entriesApi.getRecommendations(id),
enabled: !!id,
staleTime: 30 * 60 * 1000,
});
}
export function useTmdbRecommendations(
tmdbId: number,
type: "movie" | "tv",
) {
return useQuery({
queryKey: entryKeys.tmdbRecommendations(tmdbId, type),
queryFn: () => entriesApi.getTmdbRecommendations(type, tmdbId),
enabled: !!tmdbId,
staleTime: 30 * 60 * 1000,
});
}
/** Artwork for a library entry (TMDB + media table), or by TMDB id otherwise. */
export function useArtwork(
source: { entryId: number } | { tmdbId: number; type: "movie" | "tv" },
) {
const isLibrary = "entryId" in source;
return useQuery({
queryKey: isLibrary
? entryKeys.artwork(source.entryId)
: entryKeys.tmdbArtwork(source.tmdbId, source.type),
queryFn: () =>
isLibrary
? entriesApi.getArtwork(source.entryId)
: entriesApi.getTmdbArtwork(source.type, source.tmdbId),
enabled: isLibrary ? !!source.entryId : !!source.tmdbId,
staleTime: 10 * 60 * 1000,
});
}
export function useAddArtwork(entryId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: { type: ArtworkType; file_path: string }) =>
entriesApi.addArtwork(entryId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: entryKeys.artwork(entryId) });
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entryId) });
queryClient.invalidateQueries({ queryKey: entryKeys.all, exact: true });
},
onError: () => {
toast.error("Failed to add artwork");
},
});
}
export function useEntryCredits(id: number) {
return useQuery({
queryKey: entryKeys.credits(id),
+24
View File
@@ -0,0 +1,24 @@
import { useQuery } from "@tanstack/react-query";
import { historyApi } from "@/api/history";
export const historyKeys = {
years: ["history", "years"] as const,
year: (year: number) => ["history", year] as const,
};
export function useHistoryYears() {
return useQuery({
queryKey: historyKeys.years,
queryFn: historyApi.getYears,
staleTime: 5 * 60 * 1000,
});
}
export function useHistoryYear(year: number) {
return useQuery({
queryKey: historyKeys.year(year),
queryFn: () => historyApi.getYear(year),
enabled: !!year,
staleTime: 5 * 60 * 1000,
});
}
+1 -1
View File
@@ -14,7 +14,7 @@ interface TmdbEntryLink {
/**
* Resolves the correct navigation link for a TmdbEntry.
* If the entry is already in the library, links directly to EntryDetailsPage.
* Otherwise, links to the TmdbPreviewPage.
* Otherwise, links to the TMDB preview of the entry details page.
*/
export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink {
const libraryEntries = useLibraryStore((s) => s.entries);
+2 -1
View File
@@ -1,8 +1,9 @@
import axios from 'axios';
import { useAuthStore } from '@/stores/useAuthStore';
import { isDesktopBuild } from '@/lib/platform';
const API_BASE_URL =
import.meta.env.VITE_ELECTRON === 'true'
isDesktopBuild
? 'http://localhost:4000/api/v1'
: import.meta.env.VITE_API_URL || '/api/v1';
+13 -3
View File
@@ -2,7 +2,7 @@ import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
import { getBackdropUrl, getPosterUrl } from "@/lib/media-utils";
import type { Collection, Media } from "@/types";
const DEFAULT_POSTER = "/images/default-poster.png";
export const DEFAULT_POSTER = "/images/default-poster.png";
/**
* Collection poster: uploaded poster, then the collection's own TMDB poster,
@@ -13,7 +13,12 @@ export function getCollectionDisplayPosterUrl(collection: Collection): string {
(m: Media) => m.type === "poster" && m.is_selected,
);
if (selectedPoster?.path) {
return getMediaUrl("collections", "posters", "preview", selectedPoster.path);
return getMediaUrl(
"collections",
"posters",
"preview",
selectedPoster.path,
);
}
if (collection.poster_path) {
@@ -39,7 +44,12 @@ export function getCollectionDisplayBackdropUrl(
(m: Media) => m.type === "backdrop" && m.is_selected,
);
if (selectedBackdrop?.path) {
return getMediaUrl("collections", "backdrops", "full", selectedBackdrop.path);
return getMediaUrl(
"collections",
"backdrops",
"full",
selectedBackdrop.path,
);
}
if (collection.backdrop_path) {
+37
View File
@@ -0,0 +1,37 @@
import type { Episode } from "@/types";
export const isEpisodeWatched = (ep: Episode) =>
!!ep.date_first_seen || (ep.episodeSeens?.length ?? 0) > 0;
export const isEpisodeUpcoming = (ep: Episode) =>
!!ep.air_date && new Date(ep.air_date).getTime() > Date.now();
/** First aired episode not watched yet (what "Continue" should play). */
export const nextUnwatchedEpisode = (episodes: Episode[]) =>
episodes.find((ep) => !isEpisodeWatched(ep) && !isEpisodeUpcoming(ep));
export type EpisodeView = "list" | "cards";
/** Remembered list/cards choice (per browser); falls back to list. */
function loadView(key: string): EpisodeView {
try {
return localStorage.getItem(key) === "cards" ? "cards" : "list";
} catch {
return "list";
}
}
function saveView(key: string, view: EpisodeView) {
try {
localStorage.setItem(key, view);
} catch {
// storage unavailable (private mode); the choice just isn't remembered
}
}
export const loadEpisodeView = () => loadView("showy.episodeView");
export const saveEpisodeView = (view: EpisodeView) =>
saveView("showy.episodeView", view);
export const loadSeasonView = () => loadView("showy.seasonView");
export const saveSeasonView = (view: EpisodeView) =>
saveView("showy.seasonView", view);
+373
View File
@@ -0,0 +1,373 @@
import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
import type { HistoryEntry, HistoryEpisode, HistoryEvent } from "@/api/history";
export type HistoryTypeFilter = "all" | "movies" | "tv";
export const MONTH_NAMES = Array.from({ length: 12 }, (_, m) =>
new Date(2000, m, 1).toLocaleDateString("en-US", { month: "long" }),
);
export const WEEKDAY_NAMES = Array.from({ length: 7 }, (_, d) =>
// 2000-01-02 was a Sunday
new Date(2000, 0, 2 + d).toLocaleDateString("en-US", { weekday: "short" }),
);
const DEFAULT_POSTER = "/images/default-poster.png";
/** Selected local poster first, then the TMDB poster. */
export function posterUrl(entry: HistoryEntry | undefined, size = "w185") {
if (!entry) return DEFAULT_POSTER;
const local = entry.medias?.find((m) => m.type === "poster" && m.isSelected);
if (local) return getMediaUrl("entries", "posters", "preview", local.path);
return entry.poster_path
? getTmdbImageUrl(entry.poster_path, size)
: DEFAULT_POSTER;
}
export function episodeCode(ep: HistoryEpisode | null | undefined) {
if (!ep) return "";
const s = ep.season_number ?? "?";
return `S${s}E${ep.episode_number}`;
}
export function eventRuntime(
event: HistoryEvent,
entries: Record<number, HistoryEntry>,
) {
if (event.kind === "episode") {
return event.episode?.runtime ?? entries[event.entry_id]?.runtime ?? 0;
}
return entries[event.entry_id]?.runtime ?? 0;
}
export function filterEvents(events: HistoryEvent[], type: HistoryTypeFilter) {
if (type === "movies") return events.filter((e) => e.kind === "movie");
if (type === "tv") return events.filter((e) => e.kind === "episode");
return events;
}
/** Local calendar day, e.g. "2024-12-31". */
export function dayKey(date: string | Date) {
const d = new Date(date);
const mm = String(d.getMonth() + 1).padStart(2, "0");
const dd = String(d.getDate()).padStart(2, "0");
return `${d.getFullYear()}-${mm}-${dd}`;
}
export function formatMinutes(minutes: number) {
if (minutes < 60) return `${minutes}m`;
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return m ? `${h}h ${m}m` : `${h}h`;
}
/* ---------- Sessions ---------- */
/**
* A movie watch, or a run of episodes of the same show watched one after the
* other on the same day.
*/
export interface HistorySession {
key: string;
kind: "movie" | "episode";
entry: HistoryEntry | undefined;
entryId: number;
date: string; // latest watch in the session
day: string;
events: HistoryEvent[]; // oldest → newest
minutes: number;
unknownDate: boolean;
}
/** Groups newest-first events into sessions (also newest-first). */
export function buildSessions(
events: HistoryEvent[],
entries: Record<number, HistoryEntry>,
): HistorySession[] {
const sessions: HistorySession[] = [];
for (const event of events) {
const day = dayKey(event.date_seen);
const last = sessions.at(-1);
if (
last &&
event.kind === "episode" &&
last.kind === "episode" &&
last.entryId === event.entry_id &&
last.day === day
) {
last.events.unshift(event);
last.minutes += eventRuntime(event, entries);
last.unknownDate ||= event.accuracy === "UNKNOWN";
continue;
}
sessions.push({
key: event.id,
kind: event.kind,
entry: entries[event.entry_id],
entryId: event.entry_id,
date: event.date_seen,
day,
events: [event],
minutes: eventRuntime(event, entries),
unknownDate: event.accuracy === "UNKNOWN",
});
}
// Episodes within a session in watch order (season, episode)
for (const s of sessions) {
if (s.kind === "episode" && s.events.length > 1) {
s.events.sort(
(a, b) =>
(a.episode?.season_number ?? 0) - (b.episode?.season_number ?? 0) ||
(a.episode?.episode_number ?? 0) - (b.episode?.episode_number ?? 0),
);
}
}
return sessions;
}
/** "S1 E1–E5" for a session's episodes, or "S1 E3" for one. */
export function sessionEpisodeLabel(session: HistorySession) {
const eps = session.events.map((e) => e.episode).filter(Boolean);
if (eps.length === 0) return "";
if (eps.length === 1) return episodeCode(eps[0]);
const first = eps[0]!;
const last = eps.at(-1)!;
if (first.season_number === last.season_number) {
return `S${first.season_number} E${first.episode_number}–E${last.episode_number}`;
}
return `${episodeCode(first)} – ${episodeCode(last)}`;
}
/** Episode page for a single episode, otherwise the entry page. */
export function sessionLink(session: HistorySession) {
if (session.kind === "episode" && session.events.length === 1) {
const ep = session.events[0].episode;
if (ep) {
return `/entry/${session.entryId}/season/${ep.season_id}/episode/${ep.id}`;
}
}
return `/entry/${session.entryId}`;
}
export interface MonthGroup {
month: number; // 0-11
sessions: HistorySession[];
movies: number;
episodes: number;
minutes: number;
}
/** Sessions bucketed by month, December first. Empty months are skipped. */
export function groupByMonth(sessions: HistorySession[]): MonthGroup[] {
const months = new Map<number, MonthGroup>();
for (const s of sessions) {
const month = new Date(s.date).getMonth();
let group = months.get(month);
if (!group) {
group = { month, sessions: [], movies: 0, episodes: 0, minutes: 0 };
months.set(month, group);
}
group.sessions.push(s);
group.minutes += s.minutes;
if (s.kind === "movie") group.movies++;
else group.episodes += s.events.length;
}
return [...months.values()].sort((a, b) => b.month - a.month);
}
/* ---------- Year in review ---------- */
export interface YearReview {
totalMinutes: number;
movieWatches: number;
uniqueMovies: number;
episodeWatches: number;
uniqueShows: number;
activeDays: number;
topShows: { entry: HistoryEntry; episodes: number; minutes: number }[];
topMovies: { entry: HistoryEntry; rating: number; watches: number }[];
rewatches: { entry: HistoryEntry; watches: number }[];
topGenres: { name: string; minutes: number; share: number }[];
topNetworks: { name: string; logo_path: string | null; episodes: number }[];
monthly: { movies: number; episodes: number; minutes: number }[];
weekdays: number[];
busiestDay: { day: string; watches: number; minutes: number } | null;
longestStreak: { days: number; start: string; end: string } | null;
biggestBinge: { entry: HistoryEntry; day: string; episodes: number } | null;
startedShows: HistoryEntry[];
topBuddies: { id: number; name: string; watches: number }[];
first: HistoryEvent | null;
last: HistoryEvent | null;
}
const top = <T>(items: T[], score: (t: T) => number, n: number) =>
[...items].sort((a, b) => score(b) - score(a)).slice(0, n);
/** Year-in-review stats from a year's events (any order). */
export function computeReview(
events: HistoryEvent[],
entries: Record<number, HistoryEntry>,
): YearReview {
const sorted = [...events].sort(
(a, b) => new Date(a.date_seen).getTime() - new Date(b.date_seen).getTime(),
);
let totalMinutes = 0;
const movieCounts = new Map<number, number>();
const showStats = new Map<number, { episodes: number; minutes: number }>();
const genreMinutes = new Map<string, number>();
const networkEpisodes = new Map<string, { logo: string | null; n: number }>();
const monthly = Array.from({ length: 12 }, () => ({
movies: 0,
episodes: 0,
minutes: 0,
}));
const weekdays = Array(7).fill(0) as number[];
const days = new Map<string, { watches: number; minutes: number }>();
const showDays = new Map<string, number>(); // `${entryId}|${day}` → episodes
const firstEpisodeOfShow = new Map<number, HistoryEvent>();
const buddies = new Map<number, { name: string; watches: number }>();
for (const event of sorted) {
const entry = entries[event.entry_id];
const minutes = eventRuntime(event, entries);
const date = new Date(event.date_seen);
const day = dayKey(date);
totalMinutes += minutes;
if (event.kind === "movie") {
movieCounts.set(
event.entry_id,
(movieCounts.get(event.entry_id) ?? 0) + 1,
);
monthly[date.getMonth()].movies++;
} else {
const s = showStats.get(event.entry_id) ?? { episodes: 0, minutes: 0 };
s.episodes++;
s.minutes += minutes;
showStats.set(event.entry_id, s);
monthly[date.getMonth()].episodes++;
const k = `${event.entry_id}|${day}`;
showDays.set(k, (showDays.get(k) ?? 0) + 1);
if (!firstEpisodeOfShow.has(event.entry_id)) {
firstEpisodeOfShow.set(event.entry_id, event);
}
for (const n of entry?.networks ?? []) {
const cur = networkEpisodes.get(n.name) ?? { logo: n.logo_path, n: 0 };
cur.n++;
networkEpisodes.set(n.name, cur);
}
}
monthly[date.getMonth()].minutes += minutes;
weekdays[date.getDay()]++;
const d = days.get(day) ?? { watches: 0, minutes: 0 };
d.watches++;
d.minutes += minutes;
days.set(day, d);
for (const g of entry?.genres ?? []) {
genreMinutes.set(g, (genreMinutes.get(g) ?? 0) + minutes);
}
for (const b of event.buddies) {
const cur = buddies.get(b.id) ?? { name: b.name, watches: 0 };
cur.watches++;
buddies.set(b.id, cur);
}
}
// Longest run of consecutive days with at least one watch
let longestStreak: YearReview["longestStreak"] = null;
const dayList = [...days.keys()].sort();
let runStart = 0;
for (let i = 1; i <= dayList.length; i++) {
const prev = new Date(dayList[i - 1]);
const isNext =
i < dayList.length &&
new Date(dayList[i]).getTime() - prev.getTime() <= 36 * 60 * 60 * 1000;
if (!isNext) {
const length = i - runStart;
if (!longestStreak || length > longestStreak.days) {
longestStreak = {
days: length,
start: dayList[runStart],
end: dayList[i - 1],
};
}
runStart = i;
}
}
const busiest = top([...days.entries()], ([, d]) => d.minutes, 1)[0];
const binge = top([...showDays.entries()], ([, n]) => n, 1)[0];
const totalGenreMinutes =
[...genreMinutes.values()].reduce((a, b) => a + b, 0) || 1;
const movieEntries = [...movieCounts.keys()]
.map((id) => entries[id])
.filter(Boolean);
return {
totalMinutes,
movieWatches: sorted.filter((e) => e.kind === "movie").length,
uniqueMovies: movieCounts.size,
episodeWatches: sorted.filter((e) => e.kind === "episode").length,
uniqueShows: showStats.size,
activeDays: days.size,
topShows: top([...showStats.entries()], ([, s]) => s.episodes, 5)
.filter(([id]) => entries[id])
.map(([id, s]) => ({ entry: entries[id], ...s })),
topMovies: top(movieEntries, (e) => e.entryRating?.user_rating || 0, 5)
.filter((e) => (e.entryRating?.user_rating ?? 0) > 0)
.map((e) => ({
entry: e,
rating: e.entryRating!.user_rating!,
watches: movieCounts.get(e.id) ?? 1,
})),
rewatches: top(
movieEntries.filter((e) => (movieCounts.get(e.id) ?? 0) > 1),
(e) => movieCounts.get(e.id) ?? 0,
5,
).map((e) => ({ entry: e, watches: movieCounts.get(e.id)! })),
topGenres: top([...genreMinutes.entries()], ([, m]) => m, 6).map(
([name, minutes]) => ({
name,
minutes,
share: minutes / totalGenreMinutes,
}),
),
topNetworks: top([...networkEpisodes.entries()], ([, v]) => v.n, 5).map(
([name, v]) => ({ name, logo_path: v.logo, episodes: v.n }),
),
monthly,
weekdays,
busiestDay: busiest
? {
day: busiest[0],
watches: busiest[1].watches,
minutes: busiest[1].minutes,
}
: null,
longestStreak,
biggestBinge:
binge && binge[1] > 1 && entries[Number(binge[0].split("|")[0])]
? {
entry: entries[Number(binge[0].split("|")[0])],
day: binge[0].split("|")[1],
episodes: binge[1],
}
: null,
// Shows whose first episode watched this year was S1E1
startedShows: [...firstEpisodeOfShow.values()]
.filter(
(e) =>
e.episode?.season_number === 1 && e.episode?.episode_number === 1,
)
.map((e) => entries[e.entry_id])
.filter(Boolean),
topBuddies: top([...buddies.entries()], ([, b]) => b.watches, 5).map(
([id, b]) => ({ id, ...b }),
),
first: sorted[0] ?? null,
last: sorted.at(-1) ?? null,
};
}
+37
View File
@@ -29,6 +29,22 @@ export function getPosterUrl(entry: Entry): string {
return DEFAULT_POSTER;
}
/** Same source as getPosterUrl, but at original resolution. */
export function getFullPosterUrl(entry: Entry): string {
const selectedPoster = entry.isInLibrary
? entry.medias?.find((m: Media) => m.type === "poster" && m.is_selected)
: undefined;
if (selectedPoster?.path) {
return getMediaUrl("entries", "posters", "full", selectedPoster.path);
}
if (entry.poster_path) {
return getTmdbImageUrl(entry.poster_path, "original");
}
return DEFAULT_POSTER;
}
export function getBackdropUrl(entry: Entry): string {
if (entry.medias) {
const selectedBackdrop = entry.medias.find(
@@ -121,3 +137,24 @@ export function getYear(dateStr: string | null): string {
if (!dateStr) return "";
return new Date(dateStr).getFullYear().toString();
}
export function calculateAge(
birthday: string | null | undefined,
deathday?: string | null,
): number | null {
if (!birthday) return null;
const birth = new Date(birthday);
if (isNaN(birth.getTime())) return null;
let end = deathday ? new Date(deathday) : new Date();
if (deathday && isNaN(end.getTime())) end = new Date();
let age = end.getFullYear() - birth.getFullYear();
const monthDiff = end.getMonth() - birth.getMonth();
if (monthDiff < 0 || (monthDiff === 0 && end.getDate() < birth.getDate())) {
age--;
}
return age;
}
+22 -1
View File
@@ -10,7 +10,15 @@
* - Genres come as string arrays from the backend mapper
*/
import type { Entry, Collection, Media, Credit, Genre, DiscoveryVideo } from "@/types";
import type {
Entry,
Collection,
Media,
Credit,
Genre,
Network,
DiscoveryVideo,
} from "@/types";
/* ---------- Media ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -46,6 +54,18 @@ export function normalizeCredit(raw: any): Credit {
};
}
/* ---------- Network ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeNetwork(raw: any): Network {
return {
id: raw.id,
name: raw.name,
origin_country: raw.originCountry ?? raw.origin_country ?? null,
homepage: raw.homepage ?? null,
logo_path: raw.logoPath ?? raw.logo_path ?? null,
};
}
/* ---------- Genre ---------- */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function normalizeGenres(raw: any[]): Genre[] {
@@ -82,6 +102,7 @@ export function normalizeEntry(raw: any): Entry {
collections: raw.collections
? raw.collections.map(normalizeCollection)
: undefined,
networks: raw.networks ? raw.networks.map(normalizeNetwork) : undefined,
// Mark as in library when loaded from the library endpoint
isInLibrary: raw.isInLibrary ?? true,
};
+18
View File
@@ -0,0 +1,18 @@
// Which shell the frontend runs in. The build-time flags come from the
// build:electron / build:tauri / dev:tauri scripts; the runtime checks cover
// dev mode, where the shell loads the plain Vite dev server.
export const isTauri =
import.meta.env.VITE_TAURI === "true" ||
(typeof window !== "undefined" && "__TAURI_INTERNALS__" in window);
export const isElectron =
import.meta.env.VITE_ELECTRON === "true" ||
(typeof window !== "undefined" && !!window.electron?.isElectron);
/** Built for a desktop shell: local backend on :4000, hash routing, custom title bar. */
export const isDesktopBuild =
import.meta.env.VITE_ELECTRON === "true" || import.meta.env.VITE_TAURI === "true";
/** Running inside a desktop shell (Electron or Tauri). */
export const isDesktop = isElectron || isTauri;
File diff suppressed because it is too large. Load diff
+359 -146
View File
@@ -1,8 +1,6 @@
import { useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { seasonsApi } from "@/api/seasons";
import { useSeason } from "@/hooks/useSeasons";
import { useParams, Link } from "react-router-dom";
import { useSeason, useSeasonEpisodes } from "@/hooks/useSeasons";
import { useEntry, useEntrySeasons } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import {
@@ -13,20 +11,61 @@ import { StreamingDialog } from "@/components/streaming/StreamingDialog";
import { useStreamingStore } from "@/stores/useStreamingStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { EpisodeWatchHistory } from "@/components/entries/EpisodeWatchHistory";
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { CastList } from "@/components/entries/CastList";
import {
Eye,
DetailCard,
DetailHero,
DetailRow,
DetailSection,
HeroChip,
IconLink,
MetaItem,
} from "@/components/entries/DetailHero";
import {
CalendarDays,
CheckCircle2,
ChevronLeft,
ChevronRight,
Clock,
PlayCircle,
Eye,
Hash,
ListVideo,
Play,
Star,
Tv,
} from "lucide-react";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils";
import type { Episode, EpisodeSeen } from "@/types";
import { isEpisodeUpcoming, isEpisodeWatched } from "@/lib/episodes";
import {
getBackdropUrl,
getTmdbPosterUrl,
formatDate,
formatRuntime,
} from "@/lib/media-utils";
import type { Credit, Episode, EpisodePerson, EpisodeSeen } from "@/types";
/** Stored guest star → the Credit shape CastList renders (links via TMDB id). */
function toGuestCredit(guest: EpisodePerson): Credit {
return {
id: guest.id,
entry_id: 0,
people_id: guest.id,
character: guest.character ?? null,
cast_type: "cast",
department: null,
job: null,
order: guest.order ?? null,
people: {
tmdb_id: guest.id,
name: guest.name,
profile_path: guest.profile_path,
} as Credit["people"],
};
}
const pad = (n: number | null | undefined) => String(n ?? 0).padStart(2, "0");
export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{
@@ -34,26 +73,21 @@ export function EpisodePage() {
seasonId: string;
episodeId: string;
}>();
const navigate = useNavigate();
const entryIdNum = parseInt(entryId!, 10);
const seasonIdNum = parseInt(seasonId!, 10);
const epId = parseInt(episodeId!, 10);
const { data: episodes = [] } = useQuery({
queryKey: ["seasons", parseInt(seasonId!, 10), "episodes"],
queryFn: () => seasonsApi.getEpisodes(parseInt(seasonId!, 10)),
});
const { data: season } = useSeason(parseInt(seasonId!, 10));
const { data: entry } = useEntry(parseInt(entryId!, 10));
const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10));
const entryTitle =
entry?.title ??
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const { data: episodes = [] } = useSeasonEpisodes(seasonIdNum);
const { data: season } = useSeason(seasonIdNum);
const { data: entry } = useEntry(entryIdNum);
const { data: entrySeasons } = useEntrySeasons(entryIdNum);
const libraryEntry = useLibraryStore((s) => s.entries.get(entryIdNum));
const show = entry ?? libraryEntry;
const seasonNumber = season?.season_number;
const { initialize, play } = useStreamingStore();
const [streamingOpen, setStreamingOpen] = useState(false);
const epId = parseInt(episodeId!, 10);
const entryIdNum = parseInt(entryId!, 10);
const episode: Episode | undefined = episodes.find(
(ep: Episode) => ep.id === epId,
);
@@ -64,65 +98,31 @@ export function EpisodePage() {
const [deleteTarget, setDeleteTarget] = useState<number | null>(null);
const [showAddDialog, setShowAddDialog] = useState(false);
// Find prev/next episode
const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId);
const prevEpisode: Episode | undefined =
currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const nextEpisode: Episode | undefined =
currentIndex < episodes.length - 1 ? episodes[currentIndex + 1] : undefined;
currentIndex >= 0 && currentIndex < episodes.length - 1
? episodes[currentIndex + 1]
: undefined;
const episodeHref = (ep: Episode) =>
`/entry/${entryId}/season/${seasonId}/episode/${ep.id}`;
if (!episode) {
return (
<div className="space-y-6">
<Skeleton className="h-48 w-full rounded-lg" />
<Skeleton className="-mx-4 -mt-4 h-80 md:-mx-6 md:-mt-6" />
<div className="mx-auto max-w-6xl space-y-3">
<Skeleton className="h-6 w-48" />
<Skeleton className="h-4 w-80" />
<Skeleton className="h-20 w-full" />
</div>
</div>
);
}
return (
<div className="space-y-8 mx-auto max-w-4xl">
{/* Breadcrumb: Title / Season x / Episode x */}
<div className="flex items-center gap-1.5 text-sm text-muted-foreground">
<Link
to={`/entry/${entryId}`}
className="hover:text-foreground transition-colors truncate max-w-50"
>
{entryTitle || "Entry"}
</Link>
<span>/</span>
<Link
to={`/entry/${entryId}/season/${seasonId}`}
className="hover:text-foreground transition-colors"
>
Season {seasonNumber ?? "?"}
</Link>
<span>/</span>
<span className="text-foreground font-medium">
Episode {episode.episode_number}
</span>
</div>
{/* Top bar: nav breadcrumb + Mark Watched */}
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="font-medium text-foreground">
S{String(seasonNumber ?? 0).padStart(2, "0")} E
{String(episode.episode_number).padStart(2, "0")}
</span>
</div>
<Button size="sm" onClick={() => setShowAddDialog(true)}>
<Eye className="mr-1.5 h-4 w-4" />
Mark as Watched
</Button>
</div>
{/* High-quality thumbnail — click to watch */}
{episode.still_path && (
<div
className="relative overflow-hidden rounded-xl cursor-pointer group"
onClick={() => {
const canPlay = !!entry?.entryIds?.tmdb_id && !!seasonNumber;
const watchEpisode = () => {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
@@ -133,111 +133,285 @@ export function EpisodePage() {
episode: episode.episode_number,
});
setStreamingOpen(true);
}}
};
const watched = isEpisodeWatched(episode);
const upcoming = isEpisodeUpcoming(episode);
const backdrop = episode.still_path
? getTmdbPosterUrl(episode.still_path, "original")
: show
? getBackdropUrl(show)
: null;
const crewBy = (job: "Director" | "Writer") =>
(episode.crew ?? []).filter(
(c, i, all) =>
(job === "Writer"
? c.department === "Writing"
: c.job === "Director") &&
all.findIndex((o) => o.id === c.id && o.department === c.department) ===
i,
);
const directors = crewBy("Director");
const writers = crewBy("Writer");
return (
<div className="animate-page-enter">
<DetailHero backdrop={backdrop}>
<div className="max-w-3xl space-y-4 text-center sm:text-left">
<div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
<Link to={`/entry/${entryId}`}>
<HeroChip>
<Tv />
{show?.title ?? "Show"}
</HeroChip>
</Link>
<Link to={`/entry/${entryId}/season/${seasonId}`}>
<HeroChip>Season {seasonNumber ?? "?"}</HeroChip>
</Link>
<span className="rounded border border-foreground/30 px-1.5 py-px text-xs font-semibold tracking-wide tabular-nums">
S{pad(seasonNumber)}E{pad(episode.episode_number)}
</span>
{episode.episode_type === "finale" && (
<span className="rounded bg-violet-500/15 px-1.5 py-px text-xs font-semibold uppercase text-violet-600 dark:text-violet-400">
Finale
</span>
)}
{upcoming && (
<span className="rounded bg-sky-500/15 px-1.5 py-px text-xs font-semibold uppercase text-sky-600 dark:text-sky-400">
Upcoming
</span>
)}
{watched && (
<span className="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2.5 py-0.5 text-xs font-medium text-green-600 dark:text-green-400">
<CheckCircle2 className="h-3 w-3" /> Watched
</span>
)}
</div>
<h1 className="select-text text-4xl font-extrabold leading-[1.05] tracking-tight text-balance sm:text-5xl">
{episode.name}
</h1>
<div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-sm text-muted-foreground sm:justify-start">
{episode.air_date && (
<span className="font-medium text-foreground/90">
{formatDate(episode.air_date)}
</span>
)}
{episode.runtime ? (
<MetaItem>{formatRuntime(episode.runtime)}</MetaItem>
) : null}
{episode.tmdb_rating ? (
<MetaItem>
<span className="inline-flex items-center gap-1 tabular-nums">
<Star className="h-3.5 w-3.5 fill-yellow-400 text-yellow-400" />
{episode.tmdb_rating.toFixed(1)}
{episode.tmdb_vote_count ? (
<span className="text-xs">
({episode.tmdb_vote_count} votes)
</span>
) : null}
</span>
</MetaItem>
) : null}
</div>
<div className="flex flex-wrap items-center justify-center gap-2 pt-1 sm:justify-start">
<Button
size="lg"
className="h-11 gap-2 px-6"
onClick={watchEpisode}
disabled={!canPlay}
>
<img
src={getTmdbPosterUrl(episode.still_path, "w1280")}
alt={episode.name}
className="w-full max-h-96 object-cover transition-[filter] group-hover:brightness-50"
/>
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<div className="flex items-center gap-2 bg-black/60 backdrop-blur-sm rounded-full px-5 py-2.5">
<PlayCircle className="h-6 w-6 text-white" />
<span className="text-white font-medium text-sm">
Watch Episode
</span>
</div>
</div>
</div>
<Play className="h-4 w-4 fill-current" />
Watch episode
</Button>
<Button
size="lg"
variant="outline"
className="h-11 gap-2 border-border/60 bg-background/60 px-5 backdrop-blur"
onClick={() => setShowAddDialog(true)}
>
<Eye className="h-4 w-4" />
{watched ? "Watch again" : "Mark as watched"}
</Button>
{prevEpisode && (
<IconLink
to={episodeHref(prevEpisode)}
label={`Previous: E${prevEpisode.episode_number}`}
>
<ChevronLeft className="h-4 w-4" />
</IconLink>
)}
{/* Info */}
<div className="space-y-3">
<h1 className="text-2xl font-bold">{episode.name}</h1>
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
{episode.air_date && <span>{formatDate(episode.air_date)}</span>}
{episode.runtime && (
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
{formatRuntime(episode.runtime)}
</span>
{nextEpisode && (
<IconLink
to={episodeHref(nextEpisode)}
label={`Next: E${nextEpisode.episode_number}`}
>
<ChevronRight className="h-4 w-4" />
</IconLink>
)}
</div>
</div>
</DetailHero>
<div className="mx-auto mt-4 grid max-w-6xl gap-10 lg:grid-cols-[minmax(0,1fr)_300px]">
<div className="min-w-0 space-y-10">
{(episode.overview || directors.length > 0 || writers.length > 0) && (
<DetailSection title="Overview">
{episode.overview && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl">
<p className="select-text max-w-prose text-[15px] leading-relaxed text-foreground/85">
{episode.overview}
</p>
)}
{(directors.length > 0 || writers.length > 0) && (
<div className="space-y-1 text-sm">
{[
{ label: "Directed by", people: directors },
{ label: "Written by", people: writers },
]
.filter((g) => g.people.length > 0)
.map((g) => (
<p key={g.label} className="text-muted-foreground">
{g.label}{" "}
{g.people.map((p, i) => (
<span key={p.id}>
{i > 0 && ", "}
<Link
to={`/people/tmdb/${p.id}`}
className="font-medium text-foreground hover:underline"
>
{p.name}
</Link>
</span>
))}
</p>
))}
</div>
)}
</DetailSection>
)}
{/* Guest Stars */}
{episode.guest_stars && episode.guest_stars.length > 0 && (
<>
<Separator />
<CastList credits={episode.guest_stars} />
</>
<CastList
title="Guest Stars"
credits={episode.guest_stars.map(toGuestCredit)}
/>
)}
{/* Watch History */}
{watchHistory.length > 0 && (
<>
<Separator />
<EpisodeWatchHistory
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as
| EpisodeSeen
| undefined;
EpisodeSeen | undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
/>
</>
)}
{/* Prev / Next navigation */}
<Separator />
<div className="flex items-center justify-between gap-2">
{/* Prev / Next */}
{(prevEpisode || nextEpisode) && (
<div className="grid gap-3 sm:grid-cols-2">
{prevEpisode ? (
<Button
variant="outline"
size="sm"
className="flex items-center gap-1 max-w-60"
onClick={() =>
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`,
)
}
>
<ChevronLeft className="h-4 w-4 shrink-0" />
<span className="truncate">
E{prevEpisode.episode_number}: {prevEpisode.name}
</span>
</Button>
<NeighbourCard
episode={prevEpisode}
href={episodeHref(prevEpisode)}
direction="prev"
/>
) : (
<div />
<div className="hidden sm:block" />
)}
{nextEpisode ? (
<Button
variant="outline"
size="sm"
className="flex items-center gap-1 max-w-60 ml-auto"
onClick={() =>
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`,
)
}
{nextEpisode && (
<NeighbourCard
episode={nextEpisode}
href={episodeHref(nextEpisode)}
direction="next"
/>
)}
</div>
)}
</div>
{/* Sidebar */}
<aside className="space-y-4 lg:sticky lg:top-6 lg:self-start">
<DetailCard title="Details">
<dl className="space-y-2.5">
{episode.air_date && (
<DetailRow icon={<CalendarDays />} label="Aired">
{formatDate(episode.air_date)}
</DetailRow>
)}
{episode.runtime ? (
<DetailRow icon={<Clock />} label="Runtime">
{formatRuntime(episode.runtime)}
</DetailRow>
) : null}
{episode.tmdb_rating ? (
<DetailRow icon={<Star />} label="TMDB">
{episode.tmdb_rating.toFixed(1)}/10
</DetailRow>
) : null}
{episode.production_code && (
<DetailRow icon={<Hash />} label="Prod. code">
{episode.production_code}
</DetailRow>
)}
<DetailRow icon={<Eye />} label="Watched">
{watchHistory.length > 0
? watchHistory.length === 1
? formatDate(watchHistory[0].date_seen)
: `${watchHistory.length}× · last ${formatDate(
watchHistory
.map((r) => r.date_seen)
.filter(Boolean)
.sort()
.at(-1) ?? null,
)}`
: "Not yet"}
</DetailRow>
</dl>
</DetailCard>
{episodes.length > 1 && (
<DetailCard title={`Season ${seasonNumber ?? ""} episodes`}>
<ol className="-mx-1 max-h-96 space-y-0.5 overflow-y-auto">
{episodes.map((ep) => {
const current = ep.id === episode.id;
return (
<li key={ep.id}>
<Link
to={episodeHref(ep)}
aria-current={current ? "page" : undefined}
className={`flex items-center gap-2 rounded-md px-1.5 py-1.5 text-sm transition-colors ${
current
? "bg-accent font-semibold"
: "hover:bg-accent/50"
}`}
>
<span className="truncate">
E{nextEpisode.episode_number}: {nextEpisode.name}
<span className="w-7 shrink-0 text-xs text-muted-foreground tabular-nums">
E{ep.episode_number}
</span>
<ChevronRight className="h-4 w-4 shrink-0" />
</Button>
) : (
<div />
<span className="line-clamp-1 flex-1">{ep.name}</span>
{isEpisodeWatched(ep) && (
<CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-green-500" />
)}
</Link>
</li>
);
})}
</ol>
<Link
to={`/entry/${entryId}/season/${seasonId}`}
className="mt-3 inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
<ListVideo className="h-3 w-3" /> Open season
</Link>
</DetailCard>
)}
</aside>
</div>
{/* Add watch record dialog */}
@@ -248,7 +422,7 @@ export function EpisodePage() {
mode="create"
episodeId={episode.id}
entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)}
seasonId={seasonIdNum}
/>
)}
@@ -262,7 +436,7 @@ export function EpisodePage() {
mode="edit"
record={editRecord}
entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)}
seasonId={seasonIdNum}
/>
)}
@@ -282,7 +456,7 @@ export function EpisodePage() {
id: deleteTarget,
entryId: entryIdNum,
episodeId: epId,
seasonId: parseInt(seasonId!, 10),
seasonId: seasonIdNum,
});
setDeleteTarget(null);
}
@@ -304,3 +478,42 @@ export function EpisodePage() {
</div>
);
}
function NeighbourCard({
episode,
href,
direction,
}: {
episode: Episode;
href: string;
direction: "prev" | "next";
}) {
return (
<Link
to={href}
className={`group flex items-center gap-3 rounded-xl border border-border/60 bg-card/50 p-2 transition-colors hover:bg-accent/40 ${
direction === "next" ? "flex-row-reverse text-right" : ""
}`}
>
<div className="h-16 w-28 shrink-0 overflow-hidden rounded-lg bg-muted">
{episode.still_path && (
<img
src={getTmdbPosterUrl(episode.still_path, "w300")}
alt=""
loading="lazy"
className="h-full w-full object-cover transition-transform group-hover:scale-[1.04]"
/>
)}
</div>
<div className="min-w-0 flex-1">
<p className="inline-flex items-center gap-1 text-xs text-muted-foreground">
{direction === "prev" && <ChevronLeft className="h-3 w-3" />}
{direction === "prev" ? "Previous" : "Next"} · E
{episode.episode_number}
{direction === "next" && <ChevronRight className="h-3 w-3" />}
</p>
<p className="line-clamp-1 font-medium">{episode.name}</p>
</div>
</Link>
);
}
+227
View File
@@ -0,0 +1,227 @@
import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import {
ChevronLeft,
ChevronRight,
History as HistoryIcon,
} from "lucide-react";
import { useHistoryYear, useHistoryYears } from "@/hooks/useHistory";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { HistoryList } from "@/components/history/HistoryList";
import { HistoryTimeline } from "@/components/history/HistoryTimeline";
import { YearInReview } from "@/components/history/YearInReview";
import {
buildSessions,
computeReview,
filterEvents,
formatMinutes,
groupByMonth,
eventRuntime,
type HistoryTypeFilter,
} from "@/lib/history";
type HistoryTab = "history" | "timeline" | "review";
const TABS: { value: HistoryTab; label: string }[] = [
{ value: "history", label: "History" },
{ value: "timeline", label: "Timeline" },
{ value: "review", label: "Year in Review" },
];
const TYPE_FILTERS: { value: HistoryTypeFilter; label: string }[] = [
{ value: "all", label: "All" },
{ value: "movies", label: "Movies" },
{ value: "tv", label: "TV" },
];
export function HistoryPage() {
// Tab, year and filters live in the URL so a view can be linked/reloaded
const [params, setParams] = useSearchParams();
const tab = (params.get("tab") as HistoryTab) || "history";
const type = (params.get("type") as HistoryTypeFilter) || "all";
const includeUnknown = params.get("unknown") === "1";
const { data: years = [], isLoading: yearsLoading } = useHistoryYears();
const year = Number(params.get("year")) || years[0]?.year || 0;
const { data, isLoading } = useHistoryYear(year);
const setParam = (key: string, value: string | null) =>
setParams(
(prev) => {
const next = new URLSearchParams(prev);
if (value === null) next.delete(key);
else next.set(key, value);
return next;
},
{ replace: true },
);
const yearIndex = years.findIndex((y) => y.year === year);
const olderYear = years[yearIndex + 1]?.year;
const newerYear = yearIndex > 0 ? years[yearIndex - 1]?.year : undefined;
const filtered = useMemo(
() => (data ? filterEvents(data.events, type) : []),
[data, type],
);
const months = useMemo(
() => (data ? groupByMonth(buildSessions(filtered, data.entries)) : []),
[data, filtered],
);
const unknownCount = filtered.filter((e) => e.accuracy === "UNKNOWN").length;
const review = useMemo(() => {
if (!data) return null;
const events = includeUnknown
? filtered
: filtered.filter((e) => e.accuracy !== "UNKNOWN");
return computeReview(events, data.entries);
}, [data, filtered, includeUnknown]);
const totalMinutes = data
? filtered.reduce((sum, e) => sum + eventRuntime(e, data.entries), 0)
: 0;
if (!yearsLoading && years.length === 0) {
return (
<div className="flex flex-col items-center justify-center gap-3 py-24 text-center">
<HistoryIcon className="h-10 w-10 text-muted-foreground" />
<p className="text-lg font-semibold">No watch history yet</p>
<p className="text-sm text-muted-foreground">
Mark movies or episodes as watched and they'll show up here.
</p>
</div>
);
}
return (
<div className="mx-auto max-w-6xl space-y-6 animate-page-enter">
{/* Header */}
<div className="flex flex-wrap items-end justify-between gap-4">
<div className="space-y-1">
<h1 className="text-3xl font-bold tracking-tight">History</h1>
<p className="text-sm text-muted-foreground tabular-nums">
{data
? `${filtered.length.toLocaleString()} watched in ${year} · ${formatMinutes(totalMinutes)}`
: " "}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{/* Year picker */}
<div className="flex items-center gap-1 rounded-lg border border-border/60 p-0.5">
<Button
variant="ghost"
size="icon-sm"
disabled={!olderYear}
onClick={() => olderYear && setParam("year", String(olderYear))}
aria-label="Previous year"
>
<ChevronLeft />
</Button>
<Select
value={year ? String(year) : ""}
onValueChange={(v) => v && setParam("year", String(v))}
>
<SelectTrigger
size="sm"
className="h-7 min-w-20 border-0 bg-transparent font-semibold tabular-nums shadow-none"
aria-label="Year"
>
<SelectValue placeholder="Year" />
</SelectTrigger>
<SelectContent>
{years.map((y) => (
<SelectItem key={y.year} value={String(y.year)}>
<span className="tabular-nums">{y.year}</span>
<span className="ml-2 text-xs text-muted-foreground">
{y.movies + y.episodes} watched
</span>
</SelectItem>
))}
</SelectContent>
</Select>
<Button
variant="ghost"
size="icon-sm"
disabled={!newerYear}
onClick={() => newerYear && setParam("year", String(newerYear))}
aria-label="Next year"
>
<ChevronRight />
</Button>
</div>
{/* Type filter */}
<Tabs
value={type}
onValueChange={(v) => setParam("type", v === "all" ? null : v)}
>
<TabsList>
{TYPE_FILTERS.map((f) => (
<TabsTrigger key={f.value} value={f.value}>
{f.label}
</TabsTrigger>
))}
</TabsList>
</Tabs>
</div>
</div>
<Tabs
value={tab}
onValueChange={(v) => setParam("tab", v === "history" ? null : v)}
>
<TabsList>
{TABS.map((t) => (
<TabsTrigger key={t.value} value={t.value}>
{t.label}
</TabsTrigger>
))}
</TabsList>
</Tabs>
{isLoading || yearsLoading || !data ? (
<div className="space-y-3">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="h-20 w-full rounded-lg" />
))}
</div>
) : filtered.length === 0 ? (
<p className="py-16 text-center text-sm text-muted-foreground">
Nothing watched in {year}
{type !== "all" && ` (${type === "movies" ? "movies" : "TV"})`}.
</p>
) : tab === "timeline" ? (
<HistoryTimeline months={months} />
) : tab === "review" && review ? (
<div className="space-y-4">
{unknownCount > 0 && (
<label className="flex items-center gap-2 text-xs text-muted-foreground">
<input
type="checkbox"
checked={includeUnknown}
onChange={(e) =>
setParam("unknown", e.target.checked ? "1" : null)
}
/>
Include {unknownCount} watches with unknown dates (imported) —
they can skew streaks, months and busiest days
</label>
)}
<YearInReview year={year} review={review} entries={data.entries} />
</div>
) : (
<HistoryList months={months} />
)}
</div>
);
}
+146 -86
View File
@@ -1,49 +1,57 @@
import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useSearchParams, useNavigationType } from 'react-router-dom';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
import { useSearchParams, useNavigationType } from "react-router-dom";
import { useLibrary } from "@/hooks/useEntries";
import { useLibraryEntries } from "@/stores/useLibraryStore";
import {
useLibraryFiltersStore,
defaultFilters,
} from '@/stores/useLibraryFiltersStore';
} from "@/stores/useLibraryFiltersStore";
import type {
FilterTab,
SortField,
SortDir,
Filters,
} from '@/stores/useLibraryFiltersStore';
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';
} from "@/stores/useLibraryFiltersStore";
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';
} 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';
} from "@/components/ui/select";
import {
Search,
X,
SlidersHorizontal,
ArrowUpDown,
Info,
Heart,
EyeOff,
} from "lucide-react";
import type { Entry } from "@/types";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@/components/ui/tooltip';
} from "@/components/ui/tooltip";
const sortLabels: Record<SortField, string> = {
date_last_seen: 'Last Watched',
createdAt: 'Date Added',
title: 'Title',
release_date: 'Release Date',
rating: 'Rating',
date_last_seen: "Last Watched",
createdAt: "Date Added",
title: "Title",
release_date: "Release Date",
rating: "Rating",
};
function sortEntries(
@@ -54,34 +62,69 @@ function sortEntries(
return [...entries].sort((a, b) => {
let cmp = 0;
switch (field) {
case 'title':
case "title":
cmp = a.title.localeCompare(b.title);
break;
case 'release_date':
case "release_date":
cmp =
new Date(a.release_date || '1900').getTime() -
new Date(b.release_date || '1900').getTime();
new Date(a.release_date || "1900").getTime() -
new Date(b.release_date || "1900").getTime();
break;
case 'rating':
case "rating":
cmp =
(a.entryRatings?.user_rating ?? 0) -
(b.entryRatings?.user_rating ?? 0);
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();
new Date(a.date_last_seen || "1900").getTime() -
new Date(b.date_last_seen || "1900").getTime();
break;
case 'createdAt':
case "createdAt":
cmp = new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
break;
}
return dir === 'desc' ? -cmp : cmp;
return dir === "desc" ? -cmp : cmp;
});
}
const PAGE_SIZE = 28;
interface FilterTogglesProps {
favoritesOnly: boolean;
onFavoritesChange: (value: boolean) => void;
hiddenOnly: boolean;
onHiddenChange: (value: boolean) => void;
}
function FilterToggles({
favoritesOnly,
onFavoritesChange,
hiddenOnly,
onHiddenChange,
}: FilterTogglesProps) {
return (
<div className="flex items-center gap-2">
<Button
variant={favoritesOnly ? "default" : "outline"}
aria-pressed={favoritesOnly}
onClick={() => onFavoritesChange(!favoritesOnly)}
>
<Heart className={favoritesOnly ? "fill-current" : ""} />
Favorites
</Button>
<Button
variant={hiddenOnly ? "default" : "outline"}
aria-pressed={hiddenOnly}
onClick={() => onHiddenChange(!hiddenOnly)}
>
<EyeOff />
Hidden
</Button>
</div>
);
}
export function LibraryPage() {
const { isLoading } = useLibrary();
const [searchParams, setSearchParams] = useSearchParams();
@@ -92,6 +135,10 @@ export function LibraryPage() {
const setActiveTab = useLibraryFiltersStore((s) => s.setActiveTab);
const search = useLibraryFiltersStore((s) => s.search);
const setSearch = useLibraryFiltersStore((s) => s.setSearch);
const favoritesOnly = useLibraryFiltersStore((s) => s.favoritesOnly);
const setFavoritesOnly = useLibraryFiltersStore((s) => s.setFavoritesOnly);
const hiddenOnly = useLibraryFiltersStore((s) => s.hiddenOnly);
const setHiddenOnly = useLibraryFiltersStore((s) => s.setHiddenOnly);
const sortField = useLibraryFiltersStore((s) => s.sortField);
const setSortField = useLibraryFiltersStore((s) => s.setSortField);
const sortDir = useLibraryFiltersStore((s) => s.sortDir);
@@ -105,13 +152,13 @@ export function LibraryPage() {
const [debouncedFilters, setDebouncedFilters] = useState<Filters>(filters);
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const filtersInitialized = useRef(false);
const [statusFilter, setStatusFilter] = useState<string>('');
const [statusFilter, setStatusFilter] = useState<string>("");
const allEntries = useLibraryEntries();
// Reset filters when navigating TO the library (not when pressing back)
useEffect(() => {
if (navigationType !== 'POP') {
if (navigationType !== "POP") {
resetAll();
}
// Only run on mount
@@ -122,9 +169,9 @@ export function LibraryPage() {
useEffect(() => {
if (filtersInitialized.current) return;
filtersInitialized.current = true;
const genre = searchParams.get('genre') || '';
const ratingMin = searchParams.get('ratingMin') || '';
const ratingMax = searchParams.get('ratingMax') || '';
const genre = searchParams.get("genre") || "";
const ratingMin = searchParams.get("ratingMin") || "";
const ratingMax = searchParams.get("ratingMax") || "";
if (genre || ratingMin || ratingMax) {
const newFilters = {
...defaultFilters,
@@ -154,7 +201,15 @@ export function LibraryPage() {
// Reset visible count when filters/search/tab/sort change
useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [activeTab, debouncedSearch, debouncedFilters, sortField, sortDir]);
}, [
activeTab,
favoritesOnly,
hiddenOnly,
debouncedSearch,
debouncedFilters,
sortField,
sortDir,
]);
// Gather unique genres from the library
const allGenres = useMemo(() => {
@@ -173,31 +228,25 @@ export function LibraryPage() {
filters.yearMax ||
!!statusFilter;
// Type tab combines with the favorites/hidden toggles. Hidden mode shows
// only hidden entries (watchlist included); otherwise hidden and watchlist
// entries are excluded.
const baseEntries = useMemo(() => {
switch (activeTab) {
case 'movies':
return allEntries.filter(
(e) => !e.is_tvseries && !e.watchlist && !e.hidden,
);
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);
case 'hidden':
return allEntries.filter((e) => e.hidden);
default:
return allEntries.filter((e) => !e.watchlist && !e.hidden);
}
}, [activeTab, allEntries]);
return allEntries.filter((e) => {
if (activeTab === "movies" && e.is_tvseries) return false;
if (activeTab === "tv" && !e.is_tvseries) return false;
if (favoritesOnly && !e.favorit) return false;
if (hiddenOnly) return !!e.hidden;
return !e.watchlist && !e.hidden;
});
}, [activeTab, favoritesOnly, hiddenOnly, allEntries]);
const filteredEntries = useMemo(() => {
let result = baseEntries;
if (debouncedSearch) {
const q = debouncedSearch.toLowerCase();
const directorPrefix = '@director:';
const directorPrefix = "@director:";
if (q.startsWith(directorPrefix)) {
const dirQuery = q.slice(directorPrefix.length).trim();
if (dirQuery) {
@@ -281,7 +330,7 @@ export function LibraryPage() {
/>
{search && (
<button
onClick={() => setSearch('')}
onClick={() => setSearch("")}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
>
<X className="h-4 w-4" />
@@ -303,19 +352,19 @@ export function LibraryPage() {
<p className="mb-0.5">
<code className="bg-accent px-1 rounded text-[11px]">
@director:name
</code>{' '}
</code>{" "}
— by director
</p>
<p className="text-muted-foreground mb-0.5">
<code className="bg-accent px-1 rounded text-[11px]">
@country:name
</code>{' '}
</code>{" "}
— coming soon
</p>
<p className="text-muted-foreground">
<code className="bg-accent px-1 rounded text-[11px]">
@year:year
</code>{' '}
</code>{" "}
— coming soon
</p>
</PopoverContent>
@@ -330,7 +379,7 @@ export function LibraryPage() {
className="h-9 w-9 shrink-0 relative"
>
<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" />
)}
</Button>
@@ -346,8 +395,8 @@ export function LibraryPage() {
onClick={() => setSortField(value as SortField)}
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
sortField === value
? 'bg-accent text-accent-foreground font-medium'
: 'hover:bg-accent/50'
? "bg-accent text-accent-foreground font-medium"
: "hover:bg-accent/50"
}`}
>
{label}
@@ -356,18 +405,18 @@ export function LibraryPage() {
</div>
<div className="flex gap-1 pt-1 border-t border-border">
<Button
variant={sortDir === 'desc' ? 'default' : 'outline'}
variant={sortDir === "desc" ? "default" : "outline"}
size="sm"
className="flex-1 h-8 text-xs"
onClick={() => setSortDir('desc')}
onClick={() => setSortDir("desc")}
>
↓ Desc
</Button>
<Button
variant={sortDir === 'asc' ? 'default' : 'outline'}
variant={sortDir === "asc" ? "default" : "outline"}
size="sm"
className="flex-1 h-8 text-xs"
onClick={() => setSortDir('asc')}
onClick={() => setSortDir("asc")}
>
↑ Asc
</Button>
@@ -397,7 +446,7 @@ export function LibraryPage() {
onValueChange={(v) =>
setFilters((f) => ({
...f,
genre: v === '_all' ? '' : v || '',
genre: v === "_all" ? "" : v || "",
}))
}
>
@@ -418,7 +467,7 @@ export function LibraryPage() {
<label className="text-sm font-medium">Status</label>
<Select
value={statusFilter}
onValueChange={(v) => setStatusFilter(v === '_all' ? '' : v)}
onValueChange={(v) => setStatusFilter(v === "_all" ? "" : v)}
>
<SelectTrigger className="h-9">
<SelectValue placeholder="Any status" />
@@ -553,13 +602,19 @@ export function LibraryPage() {
value={activeTab}
onValueChange={(v) => setActiveTab(v as FilterTab)}
>
<TabsList className="w-max">
<div className="flex w-max items-center gap-2">
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="movies">Movies</TabsTrigger>
<TabsTrigger value="tv">TV</TabsTrigger>
<TabsTrigger value="favorites">Favorites</TabsTrigger>
<TabsTrigger value="hidden">Hidden</TabsTrigger>
</TabsList>
<FilterToggles
favoritesOnly={favoritesOnly}
onFavoritesChange={setFavoritesOnly}
hiddenOnly={hiddenOnly}
onHiddenChange={setHiddenOnly}
/>
</div>
</Tabs>
</div>
</div>
@@ -587,26 +642,26 @@ export function LibraryPage() {
<p className="mb-0.5">
<code className="bg-accent px-1 rounded text-[11px]">
@director:name
</code>{' '}
</code>{" "}
— by director
</p>
<p className="text-muted-foreground mb-0.5">
<code className="bg-accent px-1 rounded text-[11px]">
@country:name
</code>{' '}
</code>{" "}
— coming soon
</p>
<p className="text-muted-foreground">
<code className="bg-accent px-1 rounded text-[11px]">
@year:year
</code>{' '}
</code>{" "}
— coming soon
</p>
</PopoverContent>
</Popover>
{search && (
<Button variant="ghost" size="sm" onClick={() => setSearch('')}>
<Button variant="ghost" size="sm" onClick={() => setSearch("")}>
<X className="mr-1 h-4 w-4" /> Clear
</Button>
)}
@@ -620,7 +675,7 @@ export function LibraryPage() {
<ArrowUpDown className="h-4 w-4" />
{sortLabels[sortField]}
<span className="text-xs opacity-60">
{sortDir === 'desc' ? '↓' : '↑'}
{sortDir === "desc" ? "↓" : "↑"}
</span>
</Button>
</PopoverTrigger>
@@ -635,8 +690,8 @@ export function LibraryPage() {
onClick={() => setSortField(value as SortField)}
className={`w-full rounded-md px-3 py-1.5 text-left text-sm transition-colors ${
sortField === value
? 'bg-accent text-accent-foreground font-medium'
: 'hover:bg-accent/50'
? "bg-accent text-accent-foreground font-medium"
: "hover:bg-accent/50"
}`}
>
{label}
@@ -645,18 +700,18 @@ export function LibraryPage() {
</div>
<div className="flex gap-1 pt-1 border-t border-border">
<Button
variant={sortDir === 'desc' ? 'default' : 'outline'}
variant={sortDir === "desc" ? "default" : "outline"}
size="sm"
className="flex-1 h-8 text-xs"
onClick={() => setSortDir('desc')}
onClick={() => setSortDir("desc")}
>
↓ Desc
</Button>
<Button
variant={sortDir === 'asc' ? 'default' : 'outline'}
variant={sortDir === "asc" ? "default" : "outline"}
size="sm"
className="flex-1 h-8 text-xs"
onClick={() => setSortDir('asc')}
onClick={() => setSortDir("asc")}
>
↑ Asc
</Button>
@@ -688,7 +743,7 @@ export function LibraryPage() {
onValueChange={(v) =>
setFilters((f) => ({
...f,
genre: v === '_all' ? '' : v || '',
genre: v === "_all" ? "" : v || "",
}))
}
>
@@ -709,7 +764,7 @@ export function LibraryPage() {
<label className="text-sm font-medium">Status</label>
<Select
value={statusFilter}
onValueChange={(v) => setStatusFilter(v === '_all' ? '' : v)}
onValueChange={(v) => setStatusFilter(v === "_all" ? "" : v)}
>
<SelectTrigger className="h-9 w-full">
<SelectValue placeholder="Any status" />
@@ -834,10 +889,15 @@ export function LibraryPage() {
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="movies">Movies</TabsTrigger>
<TabsTrigger value="tv">TV Series</TabsTrigger>
<TabsTrigger value="favorites">Favorites</TabsTrigger>
<TabsTrigger value="hidden">Hidden</TabsTrigger>
</TabsList>
</Tabs>
<FilterToggles
favoritesOnly={favoritesOnly}
onFavoritesChange={setFavoritesOnly}
hiddenOnly={hiddenOnly}
onHiddenChange={setHiddenOnly}
/>
</div>
<EntryLibraryGrid
+18 -1
View File
@@ -8,8 +8,13 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Search, Heart } from "lucide-react";
import { getProfileUrl } from "@/lib/media-utils";
import { getProfileUrl, formatDate, calculateAge } from "@/lib/media-utils";
type PeopleFilter = "all" | "favorite";
@@ -207,6 +212,18 @@ export function PeoplePage() {
<p className="text-sm font-medium line-clamp-2">
{person.name}
</p>
{person.birthday && (
<Tooltip>
<TooltipTrigger render={<span />}>
<span className="text-xs text-muted-foreground">
Born: {formatDate(person.birthday)}
</span>
</TooltipTrigger>
<TooltipContent>
Age: {calculateAge(person.birthday, person.deathday)}
</TooltipContent>
</Tooltip>
)}
</Link>
</div>
))}
+134 -142
View File
@@ -1,4 +1,4 @@
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { useParams, useNavigate } from "react-router-dom";
import { useState, useEffect } from "react";
import {
usePerson,
@@ -13,8 +13,14 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { EntryCard } from "@/components/entries/EntryCard";
import { getProfileUrl, formatDate } from "@/lib/media-utils";
import { getTmdbImageUrl } from "@/lib/api";
import { formatDate, calculateAge } from "@/lib/media-utils";
import {
ChevronLeft,
ChevronRight,
@@ -24,58 +30,131 @@ import {
ExternalLink,
} from "lucide-react";
import type { TmdbEntry } from "@/types";
import type { TmdbFilmographyItem } from "@/api/people";
import type {
TmdbFilmographyItem,
TmdbFilmographyResponse,
} from "@/api/people";
const TMDB_IMG = "https://image.tmdb.org/t/p";
/** Person data normalized from either the local DB or a TMDB preview. */
interface PersonProfile {
name: string;
biography: string | null;
birthday: string | null;
deathday: string | null;
place_of_birth: string | null;
profile_path: string | null;
known_for_department: string | null;
tmdb_id: number | null;
favorite: boolean;
}
/**
* Person page for both sources:
* - `/people/:id`: the person is in the local DB, so details come from there
* and the filmography from TMDB via the local id.
* - `/people/tmdb/:tmdbId`: the person is not in the local DB, so everything
* comes from the TMDB preview. If the preview reports a local id, redirect.
*/
export function PersonDetailsPage() {
const { id, tmdbId } = useParams<{ id?: string; tmdbId?: string }>();
const location = useLocation();
const isTmdbMode = location.pathname.startsWith("/people/tmdb/");
if (isTmdbMode && tmdbId) {
return <TmdbPersonView tmdbId={parseInt(tmdbId, 10)} />;
}
return <LocalPersonView personId={parseInt(id!, 10)} />;
}
/* ─── Local DB person ─── */
function LocalPersonView({ personId }: { personId: number }) {
const navigate = useNavigate();
const { data: person, isLoading, isError } = usePerson(personId);
const { data: tmdbFilmography, isLoading: tmdbLoading } =
usePersonTmdbFilmography(personId);
const localId = id ? parseInt(id, 10) : 0;
const isLocal = !!localId;
const tmdbIdNum = !isLocal && tmdbId ? parseInt(tmdbId, 10) : 0;
// Queries are disabled when their id is 0, so only one source is fetched.
const localPerson = usePerson(localId);
const localFilmography = usePersonTmdbFilmography(localId);
const tmdbPreview = useTmdbPersonPreview(tmdbIdNum);
const updatePerson = useUpdatePerson();
const fetchPerson = useFetchPersonByTmdbId();
useLibrary();
const libraryMap = useLibraryStore((s) => s.entries);
const libraryLoaded = useLibraryStore((s) => s.isLoaded);
const existingLocalId = tmdbPreview.data?.local_id;
useEffect(() => {
if (existingLocalId) {
navigate(`/people/${existingLocalId}`, { replace: true });
}
}, [existingLocalId, navigate]);
const isError = isLocal ? localPerson.isError : tmdbPreview.isError;
if (isError) {
return (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<p className="text-lg font-semibold">Person not found</p>
<p className="text-sm text-muted-foreground">
This person could not be loaded. They may not exist in the database.
{isLocal
? "This person could not be loaded. They may not exist in the database."
: "Could not load person data from TMDB."}
</p>
<Button variant="outline" onClick={() => navigate("/people")}>
Back to People
<Button
variant="outline"
onClick={() => (isLocal ? navigate("/people") : navigate(-1))}
>
{isLocal ? "Back to People" : "Go back"}
</Button>
</div>
);
}
if (isLoading || !person) {
let person: PersonProfile | null = null;
let filmography: TmdbFilmographyResponse | undefined;
let filmographyLoading = false;
if (isLocal && localPerson.data) {
const p = localPerson.data;
person = {
name: p.name,
biography: p.biography ?? null,
birthday: p.birthday ?? null,
deathday: p.deathday ?? null,
place_of_birth: p.place_of_birth ?? null,
profile_path: p.profile_path ?? null,
known_for_department: p.known_for_department ?? null,
tmdb_id: p.tmdb_id ?? null,
favorite: !!p.favorite,
};
filmography = localFilmography.data;
filmographyLoading = localFilmography.isLoading;
} else if (!isLocal && tmdbPreview.data && !existingLocalId) {
const p = tmdbPreview.data;
person = { ...p, favorite: false };
filmography = p.filmography;
}
// Still loading, or about to redirect to the local page.
if (!person) {
return <PersonSkeleton />;
}
const isFavorite = person.favorite;
const toggleFavorite = () => {
updatePerson.mutate({ id: localId, data: { favorite: !isFavorite } });
};
const addToLibrary = () => {
fetchPerson.mutate(tmdbIdNum, {
onSuccess: (added) => {
navigate(`/people/${added.id}`, { replace: true });
},
});
};
return (
<div className="space-y-8 animate-page-enter">
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-8">
<Avatar className="h-32 w-32 shrink-0 sm:h-48 sm:w-48">
<AvatarImage
src={getProfileUrl(person.profile_path)}
src={
person.profile_path
? getTmdbImageUrl(person.profile_path, "w300")
: undefined
}
alt={person.name}
/>
<AvatarFallback className="text-2xl sm:text-3xl">
@@ -88,22 +167,33 @@ function LocalPersonView({ personId }: { personId: number }) {
<div className="space-y-2 text-center sm:text-left sm:space-y-3">
<div className="flex items-center gap-2 justify-center sm:justify-start">
<h1 className="text-2xl font-bold sm:text-3xl">{person.name}</h1>
{isLocal ? (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() =>
updatePerson.mutate({
id: person.id,
data: { favorite: !person.favorite },
})
}
onClick={toggleFavorite}
disabled={updatePerson.isPending}
>
<Heart
className={`h-5 w-5 ${person.favorite ? "fill-red-500 text-red-500" : "text-muted-foreground"}`}
className={`h-5 w-5 ${isFavorite ? "fill-red-500 text-red-500" : "text-muted-foreground"}`}
/>
</Button>
) : (
<Button
onClick={addToLibrary}
disabled={fetchPerson.isPending}
size="sm"
className="ml-1"
>
{fetchPerson.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{fetchPerson.isPending ? "Adding..." : "Add to Library"}
</Button>
)}
</div>
<PersonMeta
known_for_department={person.known_for_department}
@@ -123,117 +213,12 @@ function LocalPersonView({ personId }: { personId: number }) {
<Separator />
<FilmographySection
// Reset pagination when moving between people on the same route
key={isLocal ? `local-${localId}` : `tmdb-${tmdbIdNum}`}
libraryMap={libraryMap}
libraryLoaded={libraryLoaded}
tmdbFilmography={tmdbFilmography}
tmdbLoading={tmdbLoading}
/>
</div>
);
}
/* ─── TMDB person (not in library) ─── */
function TmdbPersonView({ tmdbId }: { tmdbId: number }) {
const navigate = useNavigate();
const { data: preview, isLoading, isError } = useTmdbPersonPreview(tmdbId);
const fetchPerson = useFetchPersonByTmdbId();
useLibrary();
const libraryMap = useLibraryStore((s) => s.entries);
const libraryLoaded = useLibraryStore((s) => s.isLoaded);
// If person already exists in local DB, redirect to their local page
useEffect(() => {
if (preview?.local_id) {
navigate(`/people/${preview.local_id}`, { replace: true });
}
}, [preview?.local_id, navigate]);
if (isError) {
return (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<p className="text-lg font-semibold">Person not found</p>
<p className="text-sm text-muted-foreground">
Could not load person data from TMDB.
</p>
<Button variant="outline" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
if (isLoading || !preview) {
return <PersonSkeleton />;
}
// Redirecting to local page, show skeleton while navigating
if (preview.local_id) {
return <PersonSkeleton />;
}
const profileUrl = preview.profile_path
? `${TMDB_IMG}/w300${preview.profile_path}`
: undefined;
const handleAddToLibrary = () => {
fetchPerson.mutate(tmdbId, {
onSuccess: (person) => {
navigate(`/people/${person.id}`, { replace: true });
},
});
};
return (
<div className="space-y-8 animate-page-enter">
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-8">
<Avatar className="h-32 w-32 shrink-0 sm:h-48 sm:w-48">
<AvatarImage src={profileUrl} alt={preview.name} />
<AvatarFallback className="text-2xl sm:text-3xl">
{preview.name
.split(" ")
.map((n: string) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<div className="space-y-2 text-center sm:text-left sm:space-y-3">
<div className="flex items-center gap-3 justify-center sm:justify-start">
<h1 className="text-2xl font-bold sm:text-3xl">{preview.name}</h1>
<Button
onClick={handleAddToLibrary}
disabled={fetchPerson.isPending}
size="sm"
>
{fetchPerson.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{fetchPerson.isPending ? "Adding..." : "Add to Library"}
</Button>
</div>
<PersonMeta
known_for_department={preview.known_for_department}
birthday={preview.birthday}
deathday={preview.deathday}
place_of_birth={preview.place_of_birth}
tmdb_id={preview.tmdb_id}
/>
{preview.biography && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl line-clamp-6">
{preview.biography}
</p>
)}
</div>
</div>
<Separator />
<FilmographySection
libraryMap={libraryMap}
libraryLoaded={libraryLoaded}
tmdbFilmography={preview.filmography}
tmdbLoading={false}
tmdbFilmography={filmography}
tmdbLoading={filmographyLoading}
/>
</div>
);
@@ -260,7 +245,14 @@ function PersonMeta({
{birthday && (
<>
<span>•</span>
<span>Born: {formatDate(birthday)}</span>
<Tooltip>
<TooltipTrigger render={<span className="cursor-default" />}>
Born: {formatDate(birthday)}
</TooltipTrigger>
<TooltipContent>
Age: {calculateAge(birthday, deathday)}
</TooltipContent>
</Tooltip>
</>
)}
{deathday && (
@@ -1,364 +0,0 @@
import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
useTmdbPersonPreview,
useFetchPersonByTmdbId,
} from "@/hooks/usePeople";
import { useLibrary } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
import { Button } from "@/components/ui/button";
import { EntryCard } from "@/components/entries/EntryCard";
import { getProfileUrl, formatDate } from "@/lib/media-utils";
import { Plus, Loader2, ChevronLeft, ChevronRight } from "lucide-react";
import type { TmdbEntry } from "@/types";
import type { TmdbFilmographyItem } from "@/api/people";
const TMDB_IMG = "https://image.tmdb.org/t/p";
export function PersonTmdbRedirectPage() {
const { tmdbId } = useParams<{ tmdbId: string }>();
const navigate = useNavigate();
const tmdbIdNum = parseInt(tmdbId!, 10);
const { data: preview, isLoading, isError } = useTmdbPersonPreview(tmdbIdNum);
const fetchPerson = useFetchPersonByTmdbId();
useLibrary();
const libraryMap = useLibraryStore((s) => s.entries);
const libraryLoaded = useLibraryStore((s) => s.isLoaded);
if (isLoading || !preview) {
return (
<div className="space-y-6">
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-6">
<Skeleton className="h-32 w-32 rounded-full sm:h-48 sm:w-48" />
<div className="flex-1 space-y-3 w-full">
<Skeleton className="h-8 w-48 mx-auto sm:mx-0" />
<Skeleton className="h-4 w-32 mx-auto sm:mx-0" />
<Skeleton className="h-20 w-full" />
</div>
</div>
</div>
);
}
if (isError) {
return (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<p className="text-lg font-semibold">Person not found</p>
<p className="text-sm text-muted-foreground">
Could not load person data from TMDB.
</p>
<Button variant="outline" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
const profileUrl = preview.profile_path
? `${TMDB_IMG}/w300${preview.profile_path}`
: undefined;
const handleAddToLibrary = () => {
fetchPerson.mutate(tmdbIdNum, {
onSuccess: (person) => {
navigate(`/people/${person.id}`, { replace: true });
},
});
};
return (
<div className="space-y-8 animate-page-enter">
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-8">
<Avatar className="h-32 w-32 shrink-0 sm:h-48 sm:w-48">
<AvatarImage src={profileUrl} alt={preview.name} />
<AvatarFallback className="text-2xl sm:text-3xl">
{preview.name
.split(" ")
.map((n: string) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<div className="space-y-2 text-center sm:text-left sm:space-y-3">
<div className="flex items-center gap-3 justify-center sm:justify-start">
<h1 className="text-2xl font-bold sm:text-3xl">{preview.name}</h1>
<Button
onClick={handleAddToLibrary}
disabled={fetchPerson.isPending}
size="sm"
>
{fetchPerson.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{fetchPerson.isPending ? "Adding..." : "Add to Library"}
</Button>
</div>
<div className="flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground sm:justify-start sm:gap-3">
{preview.known_for_department && (
<span>{preview.known_for_department}</span>
)}
{preview.birthday && (
<>
<span>•</span>
<span>Born: {formatDate(preview.birthday)}</span>
</>
)}
{preview.deathday && (
<>
<span>•</span>
<span>Died: {formatDate(preview.deathday)}</span>
</>
)}
{preview.place_of_birth && (
<>
<span>•</span>
<span>{preview.place_of_birth}</span>
</>
)}
</div>
{preview.biography && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl line-clamp-6">
{preview.biography}
</p>
)}
</div>
</div>
<Separator />
<TmdbFilmographySection
filmography={preview.filmography}
libraryMap={libraryMap}
libraryLoaded={libraryLoaded}
/>
</div>
);
}
interface TmdbFilmographySectionProps {
filmography: { cast: TmdbFilmographyItem[]; crew: TmdbFilmographyItem[] };
libraryMap: Map<number, import("@/types").Entry>;
libraryLoaded: boolean;
}
function TmdbFilmographySection({
filmography,
libraryMap,
libraryLoaded,
}: TmdbFilmographySectionProps) {
const [libraryPage, setLibraryPage] = useState(0);
const [otherPage, setOtherPage] = useState(0);
const PAGE_SIZE = 6;
const GRID =
"grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6";
if (!libraryLoaded) {
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Filmography</h2>
<div className={GRID}>
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 rounded-lg" />
))}
</div>
</div>
);
}
const allCredits = [
...(filmography.cast ?? []),
...(filmography.crew?.filter(
(c) => c.job === "Director" || c.department === "Directing",
) ?? []),
];
const seenIds = new Set<number>();
const deduped = allCredits.filter((c) => {
if (seenIds.has(c.id)) return false;
seenIds.add(c.id);
return true;
});
const tmdbIdToLibraryEntry = new Map<number, import("@/types").Entry>();
for (const entry of libraryMap.values()) {
if (entry.entryIds?.tmdb_id != null) {
tmdbIdToLibraryEntry.set(Number(entry.entryIds.tmdb_id), entry);
}
}
const sorted = [...deduped].sort(
(a, b) => (b.popularity ?? 0) - (a.popularity ?? 0),
);
const libraryCredits = sorted.filter((c) => tmdbIdToLibraryEntry.has(c.id));
const isSelfRole = (character?: string) => {
if (!character) return false;
const lower = character.toLowerCase().trim();
return (
lower === "self" ||
lower.startsWith("self -") ||
lower.startsWith("self (") ||
lower === "themselves" ||
lower === "himself" ||
lower === "herself"
);
};
const otherCredits = sorted
.filter((c) => !tmdbIdToLibraryEntry.has(c.id))
.sort((a, b) => {
const aSelf = isSelfRole(a.character) ? 1 : 0;
const bSelf = isSelfRole(b.character) ? 1 : 0;
if (aSelf !== bSelf) return aSelf - bSelf;
const dateA = new Date(
a.release_date || a.first_air_date || "1900",
).getTime();
const dateB = new Date(
b.release_date || b.first_air_date || "1900",
).getTime();
return dateB - dateA;
});
if (sorted.length === 0) {
return (
<div className="space-y-4">
<h2 className="text-xl font-semibold">Filmography</h2>
<p className="text-sm text-muted-foreground">No filmography found.</p>
</div>
);
}
const librarySlice = libraryCredits.slice(
libraryPage * PAGE_SIZE,
(libraryPage + 1) * PAGE_SIZE,
);
const otherSlice = otherCredits.slice(
otherPage * PAGE_SIZE,
(otherPage + 1) * PAGE_SIZE,
);
const libraryTotalPages = Math.ceil(libraryCredits.length / PAGE_SIZE);
const otherTotalPages = Math.ceil(otherCredits.length / PAGE_SIZE);
return (
<div className="space-y-8">
<h2 className="text-xl font-semibold">Filmography</h2>
{libraryCredits.length > 0 && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
In Your Library ({libraryCredits.length})
</h3>
{libraryTotalPages > 1 && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={libraryPage === 0}
onClick={() => setLibraryPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="text-xs text-muted-foreground tabular-nums">
{libraryPage + 1}/{libraryTotalPages}
</span>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={libraryPage === libraryTotalPages - 1}
onClick={() => setLibraryPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
)}
</div>
<div className={GRID}>
{librarySlice.map((credit) => {
const entry = tmdbIdToLibraryEntry.get(credit.id)!;
return (
<div key={credit.id} className="space-y-1">
<EntryCard entry={entry} />
{credit.character && (
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">
{credit.character}
</p>
)}
</div>
);
})}
</div>
</div>
)}
{otherCredits.length > 0 && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wide">
Not in Library ({otherCredits.length})
</h3>
{otherTotalPages > 1 && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={otherPage === 0}
onClick={() => setOtherPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="text-xs text-muted-foreground tabular-nums">
{otherPage + 1}/{otherTotalPages}
</span>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={otherPage === otherTotalPages - 1}
onClick={() => setOtherPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
)}
</div>
<div className={GRID}>
{otherSlice.map((credit) => {
const tmdbEntry: TmdbEntry = {
id: credit.id,
title: credit.title,
name: credit.name,
poster_path: credit.poster_path,
backdrop_path: null,
release_date: credit.release_date,
first_air_date: credit.first_air_date,
media_type: credit.media_type,
overview: "",
vote_average: 0,
vote_count: 0,
genre_ids: [],
popularity: credit.popularity ?? 0,
};
return (
<div key={credit.id} className="space-y-1">
<EntryCard tmdbEntry={tmdbEntry} />
{credit.character && (
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">
{credit.character}
</p>
)}
</div>
);
})}
</div>
</div>
)}
</div>
);
}
+204 -227
View File
@@ -15,7 +15,6 @@ import { useStreamingStore } from "@/stores/useStreamingStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";
import { StarRating } from "@/components/ui/star-rating";
import {
DropdownMenu,
DropdownMenuContent,
@@ -23,51 +22,77 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Eye,
CheckCircle2,
ArrowLeft,
ListChecks,
PlayCircle,
Ellipsis,
MoreHorizontal,
Play,
RefreshCw,
Star,
Tv,
CheckCircle2,
} from "lucide-react";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { getTmdbPosterUrl, getYear, formatDate } from "@/lib/media-utils";
import type { Episode, EpisodeSeen } from "@/types";
DetailHero,
DetailSection,
HeroChip,
IconAction,
MetaItem,
} from "@/components/entries/DetailHero";
import {
EpisodeViewToggle,
SeasonEpisodes,
} from "@/components/entries/SeasonEpisodes";
import {
isEpisodeWatched,
loadEpisodeView,
nextUnwatchedEpisode,
saveEpisodeView,
type EpisodeView,
} from "@/lib/episodes";
import {
getBackdropUrl,
getTmdbPosterUrl,
getYear,
formatDate,
formatRuntime,
} from "@/lib/media-utils";
import type { Episode } from "@/types";
export function SeasonPage() {
const { entryId, seasonId } = useParams<{
entryId: string;
seasonId: string;
}>();
const { data: season, isLoading } = useSeason(parseInt(seasonId!, 10));
const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10));
const { data: entry } = useEntry(parseInt(entryId!, 10));
const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10));
const entryTitle =
entry?.title ??
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const entryIdNum = parseInt(entryId!, 10);
const seasonIdNum = parseInt(seasonId!, 10);
const { data: season, isLoading } = useSeason(seasonIdNum);
const { data: episodes = [] } = useSeasonEpisodes(seasonIdNum);
const { data: entry } = useEntry(entryIdNum);
const { data: entrySeasons } = useEntrySeasons(entryIdNum);
const libraryEntry = useLibraryStore((s) => s.entries.get(entryIdNum));
const show = entry ?? libraryEntry;
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 [view, setView] = useState<EpisodeView>(loadEpisodeView);
const handleWatchEpisode = (season: number, episodeNumber: number) => {
if (!entry?.entryIds?.tmdb_id) return;
const changeView = (next: EpisodeView) => {
setView(next);
saveEpisodeView(next);
};
const handleWatchEpisode = (episode: Episode) => {
if (!entry?.entryIds?.tmdb_id || !season) return;
initialize();
play({
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season,
episode: episodeNumber,
season: season.season_number,
episode: episode.episode_number,
});
setStreamingOpen(true);
};
@@ -75,71 +100,159 @@ export function SeasonPage() {
if (isLoading || !season) {
return (
<div className="space-y-6">
<div className="flex gap-6">
<Skeleton className="h-56 w-36 shrink-0 rounded-lg" />
<div className="flex-1 space-y-3">
<Skeleton className="h-6 w-48" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-64" />
</div>
<Skeleton className="-mx-4 -mt-4 h-72 md:-mx-6 md:-mt-6" />
<div className="mx-auto max-w-6xl space-y-3">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-20 w-full rounded-xl" />
))}
</div>
</div>
);
}
const watchedCount = episodes.filter(
(ep: Episode) =>
ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0),
).length;
const watchedCount = episodes.filter(isEpisodeWatched).length;
const totalEpisodes = episodes.length;
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0;
const totalRuntime = episodes.reduce((sum, ep) => sum + (ep.runtime ?? 0), 0);
const airDates = episodes
.map((ep) => ep.air_date)
.filter(Boolean)
.sort() as string[];
const nextUp = nextUnwatchedEpisode(episodes);
const userRating = season.user_rating ?? 0;
const backdrop = show ? getBackdropUrl(show) : null;
return (
<div className="space-y-8 animate-page-enter mx-auto max-w-4xl">
{/* Breadcrumb: Title / Season x */}
<div className="flex items-center gap-1.5 text-sm text-muted-foreground">
<div className="animate-page-enter">
<DetailHero backdrop={backdrop}>
<Link
to={`/entry/${entryId}`}
className="hover:text-foreground transition-colors truncate max-w-50"
className="mb-6 inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-background/60 py-1 pl-2 pr-3 text-sm font-medium backdrop-blur transition-colors hover:bg-accent"
>
{entryTitle || "Entry"}
<ArrowLeft className="h-4 w-4" />
Back to {show?.title ?? "show"}
</Link>
<span>/</span>
<span className="text-foreground font-medium">
Season {season.season_number}
<div className="flex flex-col items-center gap-6 sm:flex-row sm:items-end sm:gap-8">
<img
src={getTmdbPosterUrl(season.poster_path, "w500")}
alt={season.name}
className="aspect-2/3 w-36 shrink-0 rounded-xl object-cover shadow-2xl shadow-black/50 ring-1 ring-white/10 sm:w-48 lg:w-52"
/>
<div className="min-w-0 flex-1 space-y-4 text-center sm:text-left">
<div className="flex flex-wrap items-center justify-center gap-2 sm:justify-start">
<Link to={`/entry/${entryId}`}>
<HeroChip>
<Tv />
{show?.title ?? "Show"}
</HeroChip>
</Link>
<HeroChip>Season {season.season_number}</HeroChip>
{progress === 100 && totalEpisodes > 0 && (
<span className="inline-flex items-center gap-1 rounded-full bg-green-500/15 px-2.5 py-0.5 text-xs font-medium text-green-600 dark:text-green-400">
<CheckCircle2 className="h-3 w-3" /> Completed
</span>
)}
</div>
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:gap-6">
<img
src={getTmdbPosterUrl(season.poster_path, "w185")}
alt={season.name}
className="h-40 w-28 shrink-0 rounded-lg object-cover shadow-lg self-center sm:self-start sm:h-56 sm:w-36"
/>
<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>
{/* Actions dropdown — top right */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="outline"
className="shrink-0 self-end sm:self-start"
<h1 className="select-text text-4xl font-extrabold leading-[1.05] tracking-tight text-balance sm:text-5xl">
{season.name}
</h1>
<div className="flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-sm text-muted-foreground sm:justify-start">
{season.air_date && (
<span className="font-medium text-foreground/90">
{getYear(season.air_date)}
</span>
)}
<MetaItem>
{totalEpisodes} {totalEpisodes === 1 ? "episode" : "episodes"}
</MetaItem>
{totalRuntime > 0 && (
<MetaItem>{formatRuntime(totalRuntime)}</MetaItem>
)}
{airDates.length > 1 && (
<MetaItem>
{formatDate(airDates[0])} – {formatDate(airDates.at(-1)!)}
</MetaItem>
)}
</div>
{/* Ratings + progress */}
<div className="flex flex-wrap items-center justify-center gap-x-5 gap-y-3 sm:justify-start">
<button
type="button"
onClick={() => setShowRatingDialog(true)}
className="inline-flex items-center gap-1.5 rounded-full border border-border/60 bg-background/60 px-3 py-1 text-sm backdrop-blur transition-colors hover:bg-accent"
>
<Ellipsis className="h-4 w-4" />
<Star
className={`h-4 w-4 ${userRating > 0 ? "fill-yellow-400 text-yellow-400" : "text-muted-foreground"}`}
/>
{userRating > 0 ? (
<span className="font-semibold tabular-nums">
{userRating}/10
</span>
) : (
<span className="text-muted-foreground">Rate season</span>
)}
</button>
{season.tmdb_rating ? (
<span className="text-sm text-muted-foreground tabular-nums">
TMDB{" "}
<span className="font-semibold text-sky-500">
{season.tmdb_rating.toFixed(1)}
</span>
</span>
) : null}
<div className="flex w-56 items-center gap-2">
<Progress value={progress} className="h-2 flex-1" />
<span className="text-xs font-medium tabular-nums text-muted-foreground">
{watchedCount}/{totalEpisodes}
</span>
</div>
</div>
{/* Actions */}
<div className="flex flex-wrap items-center justify-center gap-2 pt-1 sm:justify-start">
{nextUp && (
<Button
size="lg"
className="h-11 gap-2 px-6"
onClick={() => handleWatchEpisode(nextUp)}
disabled={!entry?.entryIds?.tmdb_id}
>
<Play className="h-4 w-4 fill-current" />
{watchedCount > 0 ? "Continue" : "Start"}: E
{nextUp.episode_number}
</Button>
)}
<IconAction
label="Mark season watched"
onClick={() => setShowMarkAllDialog(true)}
>
<ListChecks className="h-4 w-4" />
</IconAction>
<IconAction
label={userRating > 0 ? "Change rating" : "Rate season"}
onClick={() => setShowRatingDialog(true)}
active={userRating > 0}
>
<Star className="h-4 w-4" />
</IconAction>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="outline"
size="icon-lg"
className="h-11 w-11 rounded-full border-border/60 bg-background/60 backdrop-blur"
aria-label="More actions"
/>
}
>
<MoreHorizontal className="h-4 w-4" />
</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}
@@ -147,173 +260,39 @@ export function SeasonPage() {
<RefreshCw
className={`mr-2 h-4 w-4 ${refreshSeason.isPending ? "animate-spin" : ""}`}
/>
Refresh Season
{refreshSeason.isPending
? "Refreshing..."
: "Refresh season"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>Season {season.season_number}</span>
{season.air_date && (
<>
<span>•</span>
<span>{getYear(season.air_date)}</span>
</>
)}
<span>•</span>
<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" />
<span className="text-sm font-medium">
{watchedCount}/{totalEpisodes}
</span>
</div>
</DetailHero>
<div className="mx-auto mt-4 max-w-6xl space-y-10">
{season.overview && (
<p className="text-sm text-muted-foreground max-w-lg">
<DetailSection title="Overview">
<p className="select-text max-w-prose text-[15px] leading-relaxed text-foreground/85">
{season.overview}
</p>
</DetailSection>
)}
</div>
</div>
{/* Episodes */}
<div className="space-y-3">
<h3 className="text-lg font-semibold">Episodes</h3>
<div className="space-y-2">
{episodes.map((episode: Episode) => {
const isWatched =
!!episode.date_first_seen ||
(episode.episodeSeens && episode.episodeSeens.length > 0);
const seenDates = (episode.episodeSeens ?? []).map(
(s: EpisodeSeen) => s.date_seen,
);
return (
<Link
key={episode.id}
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="flex gap-3 rounded-lg border border-border p-2 transition-colors hover:bg-accent/50 sm:gap-4 sm:p-3"
<DetailSection
title="Episodes"
action={<EpisodeViewToggle view={view} onChange={changeView} />}
>
{/* Thumbnail — click to watch */}
<div
className="relative h-14 w-24 shrink-0 overflow-hidden rounded bg-muted sm:h-16 sm:w-28 group/thumb cursor-pointer"
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
if (!entry?.entryIds?.tmdb_id) return;
handleWatchEpisode(
season.season_number,
episode.episode_number,
);
}}
>
{episode.still_path ? (
<img
src={getTmdbPosterUrl(episode.still_path, "w300")}
alt={episode.name}
className="h-full w-full object-cover transition-[filter] group-hover/thumb:brightness-50"
loading="lazy"
<SeasonEpisodes
episodes={episodes}
view={view}
entryId={entryIdNum}
seasonId={seasonIdNum}
onPlay={handleWatchEpisode}
onMarkWatched={setDialogEpisode}
/>
) : (
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground bg-muted group-hover/thumb:bg-muted/70 transition-colors">
No Image
</div>
)}
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover/thumb:opacity-100 transition-opacity">
<PlayCircle className="h-7 w-7 text-white drop-shadow-lg" />
</div>
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
E{episode.episode_number}
</span>
<span className="text-sm font-medium truncate">
{episode.name}
</span>
{isWatched && (
<CheckCircle2 className="h-4 w-4 shrink-0 text-green-500" />
)}
</div>
<div className="flex items-center gap-2 flex-wrap">
{episode.air_date && (
<p className="text-xs text-muted-foreground">
{formatDate(episode.air_date)}
</p>
)}
{seenDates.length > 0 && (
<>
<span className="text-xs text-muted-foreground">•</span>
{seenDates.length === 1 ? (
<span className="text-xs text-green-600 dark:text-green-400">
Seen {formatDate(seenDates[0])}
</span>
) : (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<span className="text-xs text-green-600 dark:text-green-400 cursor-default underline decoration-dotted">
Seen {seenDates.length} times
</span>
</TooltipTrigger>
<TooltipContent>
<div className="space-y-0.5 text-xs">
{seenDates.map((d: string, i: number) => (
<p key={i}>{formatDate(d)}</p>
))}
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</>
)}
</div>
{episode.overview && (
<p className="mt-1 text-xs text-muted-foreground line-clamp-2">
{episode.overview}
</p>
)}
</div>
{/* Watch button — always clickable to add another seen record */}
<Button
size="icon"
variant={isWatched ? "secondary" : "outline"}
className="h-8 w-8 shrink-0 self-center"
onClick={(ev) => {
ev.preventDefault();
ev.stopPropagation();
setDialogEpisode(episode);
}}
>
<Eye className="h-4 w-4" />
</Button>
</Link>
);
})}
</div>
</DetailSection>
</div>
{/* Episode Seen Dialog */}
@@ -325,8 +304,8 @@ export function SeasonPage() {
}}
mode="create"
episodeId={dialogEpisode.id}
entryId={parseInt(entryId!, 10)}
seasonId={parseInt(seasonId!, 10)}
entryId={entryIdNum}
seasonId={seasonIdNum}
/>
)}
@@ -334,19 +313,17 @@ export function SeasonPage() {
<MarkSeasonWatchedDialog
open={showMarkAllDialog}
onOpenChange={setShowMarkAllDialog}
entryId={parseInt(entryId!, 10)}
seasonId={parseInt(seasonId!, 10)}
entryId={entryIdNum}
seasonId={seasonIdNum}
episodes={episodes}
/>
{/* Season Rating dialog */}
{season && (
<SeasonRatingDialog
open={showRatingDialog}
onOpenChange={setShowRatingDialog}
season={season}
/>
)}
{/* Streaming dialog */}
{entry && streamingOpen && (
+133 -1
View File
@@ -17,7 +17,8 @@ import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Save, Search, Trash2, Loader2 } from "lucide-react";
import { Progress } from "@/components/ui/progress";
import { Save, Search, Trash2, Loader2, RefreshCw } from "lucide-react";
import type { Settings } from "@/types";
const settingsSchema = z.object({
@@ -162,6 +163,125 @@ function DuplicateCreditsSection() {
);
}
function StaleRefreshSection() {
const [hours, setHours] = useState(24);
const queryClient = useQueryClient();
const status = useQuery({
queryKey: ["maintenance", "stale-entries", hours],
queryFn: () => maintenanceApi.getStaleEntries(hours),
// Poll while a job is running so progress updates live
refetchInterval: (query) => (query.state.data?.job.running ? 2000 : false),
});
const start = useMutation({
mutationFn: () => maintenanceApi.startStaleRefresh(hours),
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: ["maintenance", "stale-entries"],
}),
});
const cancel = useMutation({
mutationFn: maintenanceApi.cancelStaleRefresh,
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: ["maintenance", "stale-entries"],
}),
});
const job = status.data?.job;
const running = !!job?.running;
const progress = job?.total
? Math.round(((job.done ?? 0) / job.total) * 100)
: 0;
return (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
Re-fetches details, seasons, episodes and credits from TMDB for entries
not refreshed recently. Requests are rate limited, so a large library
takes a while. Entries with auto sync off are skipped.
</p>
<div className="flex flex-wrap items-center gap-2">
<Label htmlFor="stale-hours" className="text-xs">
Older than
</Label>
<Input
id="stale-hours"
type="number"
min={0}
value={hours}
onChange={(e) => setHours(Math.max(0, Number(e.target.value) || 0))}
className="h-8 w-20"
disabled={running}
/>
<span className="text-xs text-muted-foreground">hours</span>
<span className="text-xs text-muted-foreground">
·{" "}
{status.isLoading
? "counting…"
: `${status.data?.count ?? 0} entries due`}
</span>
</div>
<div className="flex items-center gap-2">
{running ? (
<Button
variant="outline"
size="sm"
onClick={() => cancel.mutate()}
disabled={cancel.isPending || job?.cancelRequested}
>
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
{job?.cancelRequested ? "Cancelling…" : "Cancel"}
</Button>
) : (
<Button
variant="outline"
size="sm"
onClick={() => start.mutate()}
disabled={start.isPending || !status.data?.count}
>
{start.isPending ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="mr-1.5 h-3.5 w-3.5" />
)}
Refresh stale entries
</Button>
)}
</div>
{job && job.total != null && (
<div className="space-y-1.5">
<Progress value={progress} className="h-1.5" />
<p className="text-xs text-muted-foreground">
{running
? "Refreshing"
: job.cancelRequested
? "Cancelled"
: "Finished"}
: {job.done}/{job.total} · {job.succeeded} ok
{job.failed &&
job.failed.length > 0 &&
` · ${job.failed.length} failed`}
{running && job.current && ` · ${job.current.title}`}
</p>
{!running && job.failed && job.failed.length > 0 && (
<ul className="max-h-28 overflow-y-auto text-xs text-destructive">
{job.failed.map((f) => (
<li key={f.id}>
{f.title}: {f.error}
</li>
))}
</ul>
)}
</div>
)}
</div>
);
}
function WatchStatusesSection() {
const [fixResult, setFixResult] = useState<{
completed: number;
@@ -419,6 +539,18 @@ export function SettingsPage() {
<TabsContent value="maintenance" className="mt-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<Card>
<CardHeader>
<CardTitle>TMDB Refresh</CardTitle>
<CardDescription>
Keep library data in sync with The Movie Database.
</CardDescription>
</CardHeader>
<CardContent>
<StaleRefreshSection />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Media Cleanup</CardTitle>
@@ -1,261 +0,0 @@
import { useParams, useNavigate } from "react-router-dom";
import { useEffect } from "react";
import { useTmdbPreview, useCreateEntry } from "@/hooks/useEntries";
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 { Plus, Loader2, ExternalLink } from "lucide-react";
import { EntryDetailsSkeleton } from "@/components/skeletons/PageSkeletons";
import { CastList } from "@/components/entries/CastList";
import { getYear, formatRuntime } from "@/lib/media-utils";
import type { Credit } from "@/types";
const TMDB_IMG = "https://image.tmdb.org/t/p";
export function TmdbPreviewPage() {
const { type, tmdbId } = useParams<{ type: string; tmdbId: string }>();
const navigate = useNavigate();
const tmdbIdNum = parseInt(tmdbId!, 10);
const mediaType = type as "movie" | "tv";
const {
data: preview,
isLoading,
isError,
} = useTmdbPreview(tmdbIdNum, mediaType);
const createEntry = useCreateEntry();
// Check if already in library
const libraryEntry = useLibraryStore((s) => {
for (const e of s.entries.values()) {
if (e.entryIds?.tmdb_id === tmdbIdNum) return e;
}
return null;
});
// Redirect immediately if entry is already in library — skip the preview step
useEffect(() => {
if (libraryEntry) {
navigate(`/entry/${libraryEntry.id}`, { replace: true });
}
}, [libraryEntry, navigate]);
// Track recently viewed for command palette
const addRecentlyViewed = useCommandPaletteStore((s) => s.addRecentlyViewed);
useEffect(() => {
if (preview) {
addRecentlyViewed({
id: `tmdb-${tmdbIdNum}`,
title: preview.title,
type: mediaType,
poster_path: preview.poster_path,
libraryId: libraryEntry?.id,
tmdbId: tmdbIdNum,
});
}
}, [tmdbIdNum, preview?.title]);
if (isLoading || !preview) {
return <EntryDetailsSkeleton />;
}
if (isError) {
return (
<div className="flex flex-col items-center justify-center gap-4 py-20">
<p className="text-muted-foreground">Could not load entry from TMDB.</p>
<Button variant="outline" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
const backdrop = preview.backdrop_path
? `${TMDB_IMG}/w1280${preview.backdrop_path}`
: null;
const poster = preview.poster_path
? `${TMDB_IMG}/w500${preview.poster_path}`
: "/images/default-poster.png";
const handleAddToLibrary = () => {
createEntry.mutate(
{ tmdb_id: preview.tmdb_id, is_tvserie: preview.is_tvseries },
{
onSuccess: (newEntry) =>
navigate(`/entry/${newEntry.id}`, { replace: true }),
},
);
};
return (
<div>
{/* Backdrop banner */}
<div className="relative -mx-6 -mt-6 h-52 overflow-hidden">
{backdrop ? (
<img
src={backdrop}
alt=""
className="h-full w-full object-cover opacity-25 blur-sm scale-105"
/>
) : (
<div className="h-full w-full bg-linear-to-br from-primary/15 to-primary/5" />
)}
<div className="absolute inset-0 bg-linear-to-t from-background via-background/60 to-transparent" />
</div>
{/* Main content */}
<div className="mx-auto max-w-4xl">
{/* Add to Library button — top right */}
<div className="flex justify-end gap-2 -mt-10 relative z-10 mb-2">
{libraryEntry ? (
<Button
variant="outline"
onClick={() => navigate(`/entry/${libraryEntry.id}`)}
>
Already in Library — View
</Button>
) : (
<Button
onClick={handleAddToLibrary}
disabled={createEntry.isPending}
>
{createEntry.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{createEntry.isPending ? "Adding..." : "Add to Library"}
</Button>
)}
</div>
{/* Two-column header: poster | info */}
<div className="flex flex-col gap-6 relative items-start sm:flex-row sm:gap-8 sm:-mt-8">
{/* LEFT: Poster */}
<div className="w-32 sm:w-44 shrink-0 self-start mx-auto sm:mx-0">
<img
src={poster}
alt={preview.title}
className="w-full aspect-2/3 rounded-xl object-cover shadow-2xl ring-1 ring-border/50"
/>
{/* External links */}
<div className="flex items-center justify-center gap-3 mt-3">
{preview.tmdb_id && (
<a
href={`https://www.themoviedb.org/${preview.is_tvseries ? "tv" : "movie"}/${preview.tmdb_id}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-3 w-3" />
TMDB
</a>
)}
{preview.imdb_id && (
<a
href={`https://www.imdb.com/title/${preview.imdb_id}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-3 w-3" />
IMDb
</a>
)}
</div>
</div>
{/* RIGHT: Info */}
<div className="flex-1 min-w-0 space-y-4">
{/* Title */}
<div>
<h1 className="text-3xl font-bold leading-tight">
{preview.title}
</h1>
</div>
{/* Meta */}
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
{preview.release_date && (
<span>{getYear(preview.release_date)}</span>
)}
{preview.is_tvseries && preview.status && (
<>
<span>•</span>
<span>{preview.status}</span>
</>
)}
{preview.runtime && !preview.is_tvseries && (
<>
{preview.release_date && <span>•</span>}
<span>{formatRuntime(preview.runtime)}</span>
</>
)}
</div>
{/* TV series season count */}
{preview.is_tvseries && preview.number_of_seasons != null && (
<div className="flex items-center gap-2 text-sm">
<Badge variant="secondary">
{preview.number_of_seasons}{" "}
{preview.number_of_seasons === 1 ? "Season" : "Seasons"}
</Badge>
{preview.number_of_episodes != null && (
<span className="text-muted-foreground">
({preview.number_of_episodes} episodes)
</span>
)}
</div>
)}
{/* Genres */}
{preview.genres.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{preview.genres.map((g) => (
<Badge key={g.id} variant="outline" className="text-xs">
{g.name}
</Badge>
))}
</div>
)}
{/* Rating */}
{preview.vote_average != null && preview.vote_average > 0 && (
<div className="flex items-center gap-2">
<span className="inline-flex items-center gap-1 rounded-full bg-blue-500/10 border border-blue-500/20 px-3 py-1 text-sm text-blue-600 dark:text-blue-400 font-medium">
<span className="font-bold">TMDB:</span>
{preview.vote_average.toFixed(1)}/10
</span>
</div>
)}
{/* Storyline */}
{preview.storyline && (
<>
<p className="text-sm text-muted-foreground leading-relaxed max-w-prose">
{preview.storyline}
</p>
</>
)}
</div>
</div>
{/* Sections */}
<div className="mt-10 space-y-8">
{preview.credits && preview.credits.length > 0 && (
<>
<Separator />
<CastList
credits={preview.credits as unknown as Credit[]}
maxItems={12}
allCastHref={`/entry/tmdb/${mediaType}/${tmdbIdNum}/cast`}
/>
</>
)}
</div>
</div>
</div>
);
}
+14 -8
View File
@@ -1,6 +1,7 @@
import { createBrowserRouter, createHashRouter } from "react-router-dom";
import { lazy, Suspense, type ReactNode } from "react";
import { AppLayout } from "@/components/layout/AppLayout";
import { isDesktopBuild } from "@/lib/platform";
import {
DashboardSkeleton,
HomeSkeleton,
@@ -26,6 +27,9 @@ const HomePage = lazy(() =>
const DashboardPage = lazy(() =>
import("@/pages/DashboardPage").then((m) => ({ default: m.DashboardPage })),
);
const HistoryPage = lazy(() =>
import("@/pages/HistoryPage").then((m) => ({ default: m.HistoryPage })),
);
const LibraryPage = lazy(() =>
import("@/pages/LibraryPage").then((m) => ({ default: m.LibraryPage })),
);
@@ -53,11 +57,6 @@ const EntryDetailsPage = lazy(() =>
default: m.EntryDetailsPage,
})),
);
const TmdbPreviewPage = lazy(() =>
import("@/pages/TmdbPreviewPage").then((m) => ({
default: m.TmdbPreviewPage,
})),
);
const TmdbCastsPage = lazy(() =>
import("@/pages/TmdbCastsPage").then((m) => ({
default: m.TmdbCastsPage,
@@ -119,8 +118,7 @@ function SuspensePage({
);
}
const isElectron = import.meta.env.VITE_ELECTRON === "true";
const createRouter = isElectron ? createHashRouter : createBrowserRouter;
const createRouter = isDesktopBuild ? createHashRouter : createBrowserRouter;
export const router = createRouter([
{
@@ -166,6 +164,14 @@ export const router = createRouter([
</SuspensePage>
),
},
{
path: "/history",
element: (
<SuspensePage fallback={<WatchlistSkeleton />}>
<HistoryPage />
</SuspensePage>
),
},
{
path: "/watchlist",
element: (
@@ -226,7 +232,7 @@ export const router = createRouter([
path: "/entry/tmdb/:type/:tmdbId",
element: (
<SuspensePage fallback={<EntryDetailsSkeleton />}>
<TmdbPreviewPage />
<EntryDetailsPage />
</SuspensePage>
),
},
@@ -1,6 +1,6 @@
import { create } from "zustand";
type FilterTab = "all" | "movies" | "tv" | "favorites" | "hidden";
type FilterTab = "all" | "movies" | "tv";
type SortField =
| "date_last_seen"
| "createdAt"
@@ -25,9 +25,13 @@ interface LibraryFiltersState {
sortField: SortField;
sortDir: SortDir;
filters: Filters;
favoritesOnly: boolean;
hiddenOnly: boolean;
setActiveTab: (tab: FilterTab) => void;
setSearch: (search: string) => void;
setFavoritesOnly: (value: boolean) => void;
setHiddenOnly: (value: boolean) => void;
setSortField: (field: SortField) => void;
setSortDir: (dir: SortDir) => void;
setFilters: (updater: Filters | ((prev: Filters) => Filters)) => void;
@@ -51,9 +55,13 @@ export const useLibraryFiltersStore = create<LibraryFiltersState>((set) => ({
sortField: "date_last_seen",
sortDir: "desc",
filters: defaultFilters,
favoritesOnly: false,
hiddenOnly: false,
setActiveTab: (tab) => set({ activeTab: tab }),
setSearch: (search) => set({ search }),
setFavoritesOnly: (value) => set({ favoritesOnly: value }),
setHiddenOnly: (value) => set({ hiddenOnly: value }),
setSortField: (field) => set({ sortField: field }),
setSortDir: (dir) => set({ sortDir: dir }),
setFilters: (updater) =>
@@ -68,6 +76,8 @@ export const useLibraryFiltersStore = create<LibraryFiltersState>((set) => ({
sortField: "date_last_seen",
sortDir: "desc",
filters: defaultFilters,
favoritesOnly: false,
hiddenOnly: false,
}),
}));
+142 -2
View File
@@ -2,17 +2,88 @@
export interface EntryIds {
tmdb_id: number | null;
imdb_id: string | null;
tvdb_id: number | null;
tvdb_id: number | string | null;
wikidata_id?: string | null;
facebook_id?: string | null;
instagram_id?: string | null;
twitter_id?: string | null;
}
export interface EntryRatings {
id?: number;
user_rating: number | null;
tmdb_rating: number | null;
tmdb_vote_count?: number | null;
imdb_rating: number | null;
rotten_tomatoes_rating: number | null;
}
/* ---------- TMDB detail blocks stored on Entry ---------- */
export interface TmdbVideo {
key: string;
name: string;
type: string;
official: boolean;
published_at: string | null;
iso_639_1: string | null;
}
export interface WatchProvider {
provider_id: number;
provider_name: string;
logo_path: string | null;
display_priority: number | null;
}
export interface WatchProviderRegion {
link: string | null;
flatrate?: WatchProvider[] | null;
free?: WatchProvider[] | null;
ads?: WatchProvider[] | null;
rent?: WatchProvider[] | null;
buy?: WatchProvider[] | null;
}
export interface ProductionCompany {
id: number;
name: string;
logo_path: string | null;
origin_country: string | null;
}
export interface SpokenLanguage {
iso_639_1: string;
english_name: string;
name: string;
}
export interface TvCreator {
id: number;
name: string;
profile_path: string | null;
}
export interface EpisodeSummary {
id: number;
name: string;
season_number: number;
episode_number: number;
air_date: string | null;
episode_type: string | null;
runtime: number | null;
still_path: string | null;
}
export interface EpisodePerson {
id: number;
name: string;
profile_path: string | null;
character?: string | null;
order?: number | null;
job?: string | null;
department?: string | null;
}
export interface Media {
id: number;
mediaable: "entry" | "people" | "collection" | "season" | "episode";
@@ -60,6 +131,33 @@ export interface Entry {
entrySeens?: EntrySeen[];
episodeSeens?: EpisodeSeen[];
networks?: Network[];
// TMDB details (detail endpoint only for the JSON blocks)
certification?: string | null;
network_studio?: string | null;
adult?: boolean;
tmdb_popularity?: number | null;
original_language?: string | null;
origin_country?: string[] | null;
spoken_languages?: SpokenLanguage[] | null;
production_countries?: { iso_3166_1: string; name: string }[] | null;
production_companies?: ProductionCompany[] | null;
homepage?: string | null;
budget?: number | null;
revenue?: number | null;
tagline?: string | null;
keywords?: string[] | null;
tmdb_videos?: TmdbVideo[] | null;
watch_providers?: Record<string, WatchProviderRegion> | null;
alternative_titles?: { iso_3166_1: string; title: string; type: string }[] | null;
tv_type?: string | null;
created_by?: TvCreator[] | null;
number_of_seasons?: number | null;
number_of_episodes?: number | null;
last_air_date?: string | null;
in_production?: boolean | null;
next_episode_to_air?: EpisodeSummary | null;
last_episode_to_air?: EpisodeSummary | null;
last_fetch?: string | null;
// Computed for library
isInLibrary?: boolean;
isInWatchlist?: boolean;
@@ -93,6 +191,9 @@ export interface Episode {
air_date: string | null;
user_rating: number | null;
tmdb_rating: number | null;
tmdb_vote_count?: number | null;
production_code?: string | null;
crew?: EpisodePerson[] | null;
still_path: string | null;
overview: string | null;
date_first_seen: string | null;
@@ -100,7 +201,7 @@ export interface Episode {
createdAt: string;
updatedAt: string;
episodeSeens?: EpisodeSeen[];
guest_stars?: Credit[];
guest_stars?: EpisodePerson[] | null;
entry?: Entry;
season?: Season;
}
@@ -325,4 +426,43 @@ export interface TmdbPreview {
homepage: string | null;
imdb_id: string | null;
credits: TmdbPreviewCredit[];
/** Same shape as a library Entry, built from the TMDB data */
entry?: Entry;
seasons?: TmdbPreviewSeason[];
}
export interface TmdbPreviewSeason {
id: number;
name: string;
season_number: number;
episode_count: number;
air_date: string | null;
poster_path: string | null;
overview: string | null;
tmdb_rating: number | null;
}
/* ---------- Artwork (TMDB images merged with the media table) ---------- */
export type ArtworkType = "poster" | "backdrop" | "logo";
export interface ArtworkItem {
/** TMDB file path; null for local-only media (custom uploads, old downloads) */
file_path: string | null;
width: number | null;
height: number | null;
aspect_ratio: number | null;
language: string | null;
vote_average: number;
vote_count: number;
in_library: boolean;
media_id?: number | null;
media_path?: string | null;
is_selected?: boolean;
is_custom?: boolean;
}
export interface ArtworkResponse {
posters: ArtworkItem[];
backdrops: ArtworkItem[];
logos: ArtworkItem[];
}
+6 -1
View File
@@ -4,10 +4,13 @@ import tailwindcss from '@tailwindcss/vite'
import path from 'path'
const isElectron = process.env.VITE_ELECTRON === 'true';
const isTauri = process.env.VITE_TAURI === 'true';
// https://vite.dev/config/
export default defineConfig({
base: isElectron ? './' : '/',
base: isElectron || isTauri ? './' : '/',
// Keep Rust/Tauri output visible in the terminal during `tauri dev`.
clearScreen: !isTauri,
plugins: [react(), tailwindcss()],
resolve: {
alias: {
@@ -16,6 +19,8 @@ export default defineConfig({
},
server: {
port: 4200,
// Tauri loads devUrl http://localhost:4200, so never fall back to another port.
strictPort: isTauri,
proxy: {
'/api': {
target: 'http://showyback.coolguy.space',
+6
View File
@@ -0,0 +1,6 @@
node_modules
frontend_build
src-tauri/target
src-tauri/gen
src-tauri/binaries/*
!src-tauri/binaries/.gitkeep
+128
View File
@@ -0,0 +1,128 @@
# Showy — Tauri desktop app
A Tauri v2 shell for Showy, built side by side with the Electron app in `../electron`
(which stays untouched). It loads the React frontend from `../react_frontend` and
starts the Node backend from `../backend` alongside the window.
```
tauri/
├─ package.json # Tauri CLI + scripts
├─ scripts/prepare-sidecar.mjs # copies dist/backend/backend.exe into src-tauri/binaries
├─ frontend_build/ # output of `pnpm build:tauri` (git-ignored)
└─ src-tauri/
├─ tauri.conf.json # window, dev URL, frontend dist, bundle
├─ tauri.bundle.conf.json # adds the backend sidecar; merged in only for `pnpm build`
├─ capabilities/default.json # window permissions for the custom title bar
├─ icons/ # generated from electron/assets/icon.ico
└─ src/
├─ lib.rs # app setup, stops the backend on exit
└─ backend.rs # starts/stops the backend process
```
## Prerequisites (Windows)
- **Rust** (stable, MSVC toolchain): install with [rustup](https://rustup.rs/), target
`x86_64-pc-windows-msvc`.
- **Microsoft C++ Build Tools**: "Desktop development with C++" workload from Visual Studio
Build Tools (needed by the MSVC Rust toolchain).
- **WebView2 runtime**: preinstalled on Windows 11. On Windows 10 install the Evergreen
runtime from Microsoft.
- **Node.js** (22.x is used here) and **pnpm**.
- **Tauri CLI**: installed per project as `@tauri-apps/cli` (`pnpm install` in this folder).
`cargo install tauri-cli --version "^2"` also works if you prefer `cargo tauri ...`.
- For the backend: a running **MySQL** and `backend/settings.json` (see
`backend/settings.json.example`), with dependencies installed in `backend/`.
## Run in dev
```bash
cd react_frontend && pnpm install
cd ../backend && pnpm install
cd ../tauri && pnpm install
pnpm dev
```
`pnpm dev` (= `tauri dev`) does the following:
1. Runs `pnpm --dir ../react_frontend dev:tauri`: Vite on `http://localhost:4200` with
`VITE_TAURI=true` (API base `http://localhost:4000/api/v1`, hash router, custom title bar).
2. Builds and starts the Rust app, which opens the window on the dev server (with hot reload)
and opens DevTools, like Electron's dev mode (set `SHOWY_NO_DEVTOOLS=1` to skip).
3. Starts the backend with `node server.js` in `../backend`. Its output shows in the same
terminal. When the window closes the backend is stopped, and so is anything it spawned (a
Windows job object kills the process tree, even if the app crashes).
If something already listens on port 4000 (e.g. you run `pnpm dev` in `backend/` yourself), the
app does **not** start a second backend and uses the one that is running.
Environment overrides:
| Variable | Effect |
| --- | --- |
| `SHOWY_SKIP_BACKEND=1` | never start a backend |
| `SHOWY_BACKEND_DIR=<path>` | backend folder for dev builds (default `../backend`) |
| `SHOWY_BACKEND_EXE=<path>` | run this executable as the backend (dev or release) |
| `SHOWY_NO_DEVTOOLS=1` | don't open DevTools in dev builds |
The first `tauri dev` compiles all Rust dependencies, which takes several minutes. Later runs
take seconds.
## Build
```bash
cd backend && npm run package # pkg -> dist/backend/backend.exe
cd ../tauri && pnpm build-backend # copies it to src-tauri/binaries/backend-x86_64-pc-windows-msvc.exe
pnpm build # tauri build (runs `pnpm build:tauri` in react_frontend first)
```
Output:
- `src-tauri/target/release/showy.exe`: the app (the sidecar must sit next to it as `backend.exe`).
- `src-tauri/target/release/bundle/nsis/Showy_2.0.0_x64-setup.exe`: an installer that puts
`showy.exe` and `backend.exe` side by side.
In release builds the backend runs without a console, and its output goes to
`%LOCALAPPDATA%\x4lo.showy\logs\backend.log`.
The frontend build for Tauri goes to `tauri/frontend_build`. The web build (`pnpm build`) and
the Electron build (`pnpm build:electron`) are unchanged.
## Frontend changes
- `react_frontend/src/lib/platform.ts`: `isTauri`, `isElectron`, `isDesktop`, `isDesktopBuild`.
- `api.ts` and `router.tsx` use `isDesktopBuild` (Electron **or** Tauri build), so both desktop
builds talk to `localhost:4000` and use the hash router.
- `TitleBar.tsx`: on Tauri the buttons call `@tauri-apps/api/window` (`minimize`,
`toggleMaximize`, `close`), which is loaded lazily. Dragging uses `data-tauri-drag-region`.
Electron keeps using `window.electron.windowControls` and `-webkit-app-region`.
- `vite.config.ts`: `base: './'`, `strictPort` and no screen clearing when `VITE_TAURI=true`.
- New scripts: `dev:tauri`, `build:tauri`.
## Status / missing compared with Electron
Tested on Windows 11 in dev mode: the window opens on the Vite dev server, the backend starts
and answers the webview on port 4000, the title-bar window commands (minimize, maximize/restore,
close) work, and closing the window stops the backend.
Not done yet / differences:
- **The release build has not been tested yet.** It needs `dist/backend/backend.exe`, and there
is a known problem with the pkg backend: `configService.getUserDataPath()` uses `__dirname`,
which points inside pkg's read-only snapshot. So the packaged backend cannot find or create
`settings.json`. The backend needs to read its settings next to the executable
(`path.dirname(process.execPath)` when `process.pkg` is set) or from a folder the shell passes
in, e.g. via `PARENT_PROCESS.tauri_path` (the app data dir, already sent). `sharp` and
`ffmpeg-static` native files also need checking in the pkg build.
- **Backend model**: Electron `require`s `server.js` in its own process. Tauri runs it as a
separate process (`node` in dev, the pkg `backend.exe` in release).
- **`PARENT_PROCESS`**: Electron sends `{ electron_path: userData }`. Tauri sends
`{ tauri_path: <app data dir> }`. The backend doesn't read either today.
- **Generic IPC**: Electron's preload also exposes `window.electron.ipcRenderer`. The frontend
doesn't use it, so Tauri has no equivalent (only window controls).
- **Title bar on the login page**: the window has no native frame, and the login page renders
outside `AppLayout`, so there is no title bar to drag or close the window until you log in.
Electron behaves the same way.
- **Dev API target**: Electron's `npm run dev` loads the plain `vite` dev server, which proxies
`/api` to the remote backend. Tauri dev uses the local backend on port 4000.
- No auto-update, tray icon, single-instance lock or code signing (Electron has none of these
either). The bundle target is NSIS. Electron produces an unpacked `dir` build instead.
+17
View File
@@ -0,0 +1,17 @@
{
"name": "showy_tauri",
"version": "2.0.0",
"private": true,
"description": "Showy Desktop App (Tauri)",
"scripts": {
"tauri": "tauri",
"dev": "tauri dev",
"build-front": "pnpm --dir ../react_frontend build:tauri",
"build-backend": "node scripts/prepare-sidecar.mjs",
"build": "tauri build --config src-tauri/tauri.bundle.conf.json",
"icons": "tauri icon ../electron/assets/icon.ico"
},
"devDependencies": {
"@tauri-apps/cli": "^2.9.0"
}
}
+140
View File
@@ -0,0 +1,140 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
devDependencies:
'@tauri-apps/cli':
specifier: ^2.9.0
version: 2.12.4
packages:
'@tauri-apps/cli-darwin-arm64@2.12.4':
resolution: {integrity: sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@tauri-apps/cli-darwin-x64@2.12.4':
resolution: {integrity: sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
resolution: {integrity: sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
resolution: {integrity: sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
resolution: {integrity: sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
resolution: {integrity: sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
resolution: {integrity: sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tauri-apps/cli-linux-x64-musl@2.12.4':
resolution: {integrity: sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
resolution: {integrity: sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
resolution: {integrity: sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
resolution: {integrity: sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@tauri-apps/cli@2.12.4':
resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}
engines: {node: '>= 10'}
hasBin: true
snapshots:
'@tauri-apps/cli-darwin-arm64@2.12.4':
optional: true
'@tauri-apps/cli-darwin-x64@2.12.4':
optional: true
'@tauri-apps/cli-linux-arm-gnueabihf@2.12.4':
optional: true
'@tauri-apps/cli-linux-arm64-gnu@2.12.4':
optional: true
'@tauri-apps/cli-linux-arm64-musl@2.12.4':
optional: true
'@tauri-apps/cli-linux-riscv64-gnu@2.12.4':
optional: true
'@tauri-apps/cli-linux-x64-gnu@2.12.4':
optional: true
'@tauri-apps/cli-linux-x64-musl@2.12.4':
optional: true
'@tauri-apps/cli-win32-arm64-msvc@2.12.4':
optional: true
'@tauri-apps/cli-win32-ia32-msvc@2.12.4':
optional: true
'@tauri-apps/cli-win32-x64-msvc@2.12.4':
optional: true
'@tauri-apps/cli@2.12.4':
optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 2.12.4
'@tauri-apps/cli-darwin-x64': 2.12.4
'@tauri-apps/cli-linux-arm-gnueabihf': 2.12.4
'@tauri-apps/cli-linux-arm64-gnu': 2.12.4
'@tauri-apps/cli-linux-arm64-musl': 2.12.4
'@tauri-apps/cli-linux-riscv64-gnu': 2.12.4
'@tauri-apps/cli-linux-x64-gnu': 2.12.4
'@tauri-apps/cli-linux-x64-musl': 2.12.4
'@tauri-apps/cli-win32-arm64-msvc': 2.12.4
'@tauri-apps/cli-win32-ia32-msvc': 2.12.4
'@tauri-apps/cli-win32-x64-msvc': 2.12.4
+36
View File
@@ -0,0 +1,36 @@
// Copies the pkg-packaged backend (dist/backend/backend.exe) into
// src-tauri/binaries/ under the name Tauri expects for an external binary:
// backend-<rust target triple>[.exe].
//
// Build the backend first: cd backend && npm run package
import { execSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(here, "..", "..");
const ext = process.platform === "win32" ? ".exe" : "";
const source = join(repoRoot, "dist", "backend", `backend${ext}`);
const triple = execSync("rustc -vV", { encoding: "utf8" })
.split("\n")
.find((line) => line.startsWith("host:"))
?.slice("host:".length)
.trim();
if (!triple) {
console.error("Could not read the Rust host triple from `rustc -vV`.");
process.exit(1);
}
if (!existsSync(source)) {
console.error(`Backend executable not found: ${source}`);
console.error("Build it first: cd backend && npm run package");
process.exit(1);
}
const targetDir = resolve(here, "..", "src-tauri", "binaries");
mkdirSync(targetDir, { recursive: true });
const target = join(targetDir, `backend-${triple}${ext}`);
copyFileSync(source, target);
console.log(`Copied ${source} -> ${target}`);
+4376
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "showy"
version = "2.0.0"
description = "Showy Desktop App"
edition = "2021"
[lib]
name = "showy_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
serde_json = "1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_JobObjects",
"Win32_System_Threading",
] }
[profile.release]
codegen-units = 1
lto = true
opt-level = "s"
panic = "abort"
strip = true
View File
Whitespace-only changes.
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+14
View File
@@ -0,0 +1,14 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Permissions for the main Showy window (custom title bar controls).",
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-internal-toggle-maximize",
"core:window:allow-close",
"core:window:allow-start-dragging"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

+222
View File
@@ -0,0 +1,222 @@
//! Starts the Showy Node backend next to the Tauri window and stops it on exit.
//!
//! - Debug builds (`tauri dev`) run `node server.js` from the repo's `backend/` folder.
//! - Release builds run the `pkg`-packaged `backend.exe` sidecar that the bundler
//! places next to the app executable.
//! - If something already listens on the backend port, nothing is spawned and the
//! app talks to that process (handy when the backend runs in its own terminal).
//!
//! Environment overrides:
//! - `SHOWY_SKIP_BACKEND=1` never spawn a backend
//! - `SHOWY_BACKEND_DIR=<path>` backend folder used in debug builds
//! - `SHOWY_BACKEND_EXE=<path>` run this executable instead (any build)
use std::fs::{self, File};
use std::net::{SocketAddr, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::Mutex;
use std::time::Duration;
use tauri::{AppHandle, Manager};
/// The frontend calls `http://localhost:4000/api/v1` in desktop builds.
pub const BACKEND_PORT: u16 = 4000;
#[derive(Default)]
pub struct BackendState {
child: Mutex<Option<Child>>,
#[cfg(windows)]
job: Mutex<Option<job::Job>>,
}
impl BackendState {
pub fn stop(&self) {
if let Some(mut child) = self.child.lock().unwrap().take() {
log(&format!("stopping backend (pid {})", child.id()));
let _ = child.kill();
let _ = child.wait();
}
// Closing the job handle kills anything the backend spawned (e.g. ffmpeg).
#[cfg(windows)]
drop(self.job.lock().unwrap().take());
}
}
pub fn start(app: &AppHandle) -> BackendState {
let state = BackendState::default();
if std::env::var_os("SHOWY_SKIP_BACKEND").is_some() {
log("SHOWY_SKIP_BACKEND is set, not starting the backend");
return state;
}
if port_in_use(BACKEND_PORT) {
log(&format!(
"port {BACKEND_PORT} is already in use, using the backend that is already running"
));
return state;
}
let mut cmd = match backend_command() {
Ok(cmd) => cmd,
Err(err) => {
log(&format!("cannot start backend: {err}"));
return state;
}
};
// Same contract as the Electron shell: tell the backend where the desktop
// app keeps its own data.
let data_dir = app.path().app_data_dir().ok();
cmd.env(
"PARENT_PROCESS",
serde_json::json!({ "tauri_path": data_dir }).to_string(),
);
if cfg!(debug_assertions) {
// Backend logs go to the same terminal as `tauri dev`.
cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
} else {
// No console in release builds: write the backend output to a log file.
let log_file = app.path().app_log_dir().ok().and_then(|dir| {
fs::create_dir_all(&dir).ok()?;
File::create(dir.join("backend.log")).ok()
});
match log_file.and_then(|f| f.try_clone().ok().map(|f2| (f, f2))) {
Some((out, err)) => {
cmd.stdout(out).stderr(err);
}
None => {
cmd.stdout(Stdio::null()).stderr(Stdio::null());
}
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
}
cmd.stdin(Stdio::null());
match cmd.spawn() {
Ok(child) => {
log(&format!("backend started (pid {})", child.id()));
#[cfg(windows)]
if let Some(job) = job::Job::kill_on_close() {
if job.assign(&child) {
*state.job.lock().unwrap() = Some(job);
}
}
*state.child.lock().unwrap() = Some(child);
}
Err(err) => log(&format!("failed to spawn backend: {err}")),
}
state
}
fn backend_command() -> Result<Command, String> {
if let Some(exe) = std::env::var_os("SHOWY_BACKEND_EXE") {
let exe = PathBuf::from(exe);
return exe_command(exe);
}
if cfg!(debug_assertions) {
let dir = std::env::var_os("SHOWY_BACKEND_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../backend")
});
let dir = dir.canonicalize().map_err(|e| format!("{}: {e}", dir.display()))?;
if !dir.join("server.js").is_file() {
return Err(format!("no server.js in {}", dir.display()));
}
let mut cmd = Command::new("node");
cmd.arg("server.js").current_dir(dir);
Ok(cmd)
} else {
let exe_dir = std::env::current_exe()
.map_err(|e| e.to_string())?
.parent()
.map(PathBuf::from)
.ok_or("cannot resolve the app folder")?;
let name = if cfg!(windows) { "backend.exe" } else { "backend" };
exe_command(exe_dir.join(name))
}
}
fn exe_command(exe: PathBuf) -> Result<Command, String> {
if !exe.is_file() {
return Err(format!("backend executable not found: {}", exe.display()));
}
let mut cmd = Command::new(&exe);
if let Some(dir) = exe.parent() {
cmd.current_dir(dir);
}
Ok(cmd)
}
fn port_in_use(port: u16) -> bool {
let addr = SocketAddr::from(([127, 0, 0, 1], port));
TcpStream::connect_timeout(&addr, Duration::from_millis(300)).is_ok()
}
fn log(msg: &str) {
eprintln!("[showy] {msg}");
}
/// A Windows job object that kills every process in it when its handle closes,
/// including when the app crashes, so the backend never outlives the window.
#[cfg(windows)]
mod job {
use std::os::windows::io::AsRawHandle;
use std::process::Child;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
pub struct Job(HANDLE);
// The handle is only used behind a Mutex and closed once.
unsafe impl Send for Job {}
impl Job {
pub fn kill_on_close() -> Option<Job> {
unsafe {
let handle = CreateJobObjectW(std::ptr::null(), std::ptr::null());
if handle.is_null() {
return None;
}
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let ok = SetInformationJobObject(
handle,
JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
std::mem::size_of_val(&info) as u32,
);
if ok == 0 {
CloseHandle(handle);
return None;
}
Some(Job(handle))
}
}
pub fn assign(&self, child: &Child) -> bool {
unsafe { AssignProcessToJobObject(self.0, child.as_raw_handle() as HANDLE) != 0 }
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0);
}
}
}
}
+29
View File
@@ -0,0 +1,29 @@
mod backend;
use tauri::{Manager, RunEvent};
pub fn run() {
let app = tauri::Builder::default()
.setup(|app| {
let state = backend::start(app.handle());
app.manage(state);
#[cfg(debug_assertions)]
if std::env::var("SHOWY_NO_DEVTOOLS").is_err() {
if let Some(window) = app.get_webview_window("main") {
window.open_devtools();
}
}
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building the Showy Tauri app");
app.run(|handle, event| {
if let RunEvent::Exit = event {
if let Some(state) = handle.try_state::<backend::BackendState>() {
state.stop();
}
}
});
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents an additional console window on Windows in release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
showy_lib::run()
}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more