Author SHA1 Message Date
X4Lo 229ecef902 Update docs vault and README for recent features
- New notes: History, Artwork
- Rewrite TMDB Integration: single detail request, entry mapper, rate
  limiter, refresh sync, stale-entry refresh, recommendations
- Update pages, routing, API reference, models, database migrations,
  services, components, hooks, API clients, settings, media system,
  library, Electron (Tauri in progress) and known issues
- Rewrite README for the current React/Express stack and setup
2026-11-05 19:55:04 +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
39 changed files with 3579 additions and 700 deletions

No files matched your search

+66 -73
View File
@@ -1,116 +1,109 @@
# Showy - Movies & Series Library Tracker
# Showy — Movies & Series Library Tracker
**Showy** is a comprehensive application designed to help you manage your movies and series library. Built with **Angular 17**, **Node.js**, **Express**, and **MySQL**, and optionally packaged with **Electron**, Showy allows you to track your watch progress, manage your watchlist, view upcoming releases on a calendar, and organize official and custom collections. The app also features a dashboard for quick insights into your library. The entire application is **dockerized** for easy setup and deployment.
**Showy** is a personal, single-user app for tracking the movies and TV series you watch. It pulls metadata from **TMDB**, keeps your library, watch history and ratings in **MySQL**, and runs as a web app or a **desktop app** (Electron, with a Tauri version in progress).
---
## Features
- **Library Management**:
- Add movies and series to your library.
- Track watch progress for movies and episodes.
- Add movies and series to your watchlist.
- **Calendar**:
- View upcoming movies and episodes in a calendar view.
- Never miss a release date for your favorite shows or movies.
- **Collections**:
- Browse official collections (e.g., Marvel Cinematic Universe, Harry Potter series).
- Create and manage custom collections (e.g., "90s Classics", "Christmas Movies").
- **Dashboard**:
- Get an overview of your library stats.
- View recently added movies/series, upcoming releases, and watch progress.
- **Optional Desktop App**:
- Use Showy as a desktop application with Electron for a seamless experience.
- **Dockerized**:
- Easy setup and deployment using Docker and Docker Compose.
- **Library** — add movies and shows from TMDB; favorites, hidden entries, watchlist; filter by type, genre, rating and year
- **Entry pages** — full-bleed hero, trailer player, cast and crew, seasons (list or card view), where to watch, keywords, recommendations, budget/box office, certification and external links. Titles **not in your library** open on the same page from TMDB data, with *Add to Library*
- **Artwork** — every TMDB poster, backdrop and logo for a title, merged with your local media, with one-click *Add*
- **Watch tracking** — movies and episodes with exact/estimated/unknown dates, watch buddies, rewatches, season "mark all watched" (single date or spread over a range)
- **Season & episode pages** — progress, *Continue* to the next unwatched episode, directors/writers, guest stars
- **History** — everything you watched by year, as a list, a timeline, or a Spotify-style **Year in Review**
- **Calendar** — upcoming episodes
- **Collections** — TMDB collections and your own
- **People** — cast and crew pages with filmography split into "in your library" and "not in library"
- **Dashboard** — watch time, activity, genres, ratings and growth charts
- **Discovery Videos** — a personal video vault linked to library entries
- **In-app streaming** and a **command palette** (search, recently viewed, quick navigation)
- **Maintenance** — background **TMDB refresh** of stale entries (rate limited), orphan media/people cleanup, duplicate credits, watch-status fixes
---
## Technologies Used
## Tech Stack
- **Frontend**: Angular 17
- **Backend**: Node.js, Express
- **Database**: MySQL
- **Optional Desktop Integration**: Electron
- **Containerization**: Docker, Docker Compose
| Layer | Technologies |
|---|---|
| Frontend | React 19, TypeScript, Vite 8, Tailwind CSS 4, Base UI (shadcn-style components), TanStack Query 5, Zustand 5, React Router 7, Recharts |
| Backend | Node.js, Express 4, Sequelize 6, MySQL 8, Axios, Sharp, JWT auth |
| Data | [TMDB API v3](https://developer.themoviedb.org/) (rate limited, proxied by the backend) |
| Desktop | Electron 45 (`electron/`); Tauri v2 in progress on the `feat/tauri-app` branch |
---
## Project Structure
```
showy/
├── frontend/ # Angular 17 frontend
│ ├── src/
│ │ ├── app/ # Angular components, services, modules
│ │ ├── assets/ # Static assets (images, styles)
│ │ └── environments/ # Environment configurations
│ ├── Dockerfile # Dockerfile for the frontend
│ └── ...
├── backend/ # Node.js + Express backend
│ ├── config/ # Database and app configurations
│ ├── controllers/ # API controllers
│ ├── models/ # Database models
│ ├── routes/ # API routes
│ ├── Dockerfile # Dockerfile for the backend
│ └── ...
├── electron/ # Electron configuration (optional)
├── docker-compose.yml # Docker Compose configuration
└── README.md # This file
Showy/
├── backend/ # Express + Sequelize API (models, routes, controllers, services, mappers)
│ ├── config/ # DB connection, relations, startup migrations, data seeding
│ └── settings.json # Runtime settings (TMDB key, ports, auth) — copy from settings.json.example
├── react_frontend/ # React + Vite frontend (the current UI)
├── electron/ # Electron desktop shell
├── docs-vault/ # Project documentation (Obsidian vault) — start at Index.md
├── frontend/ # Legacy Angular frontend (still used by docker-compose)
└── docker-compose.yml
```
---
## Getting Started
### Prerequisites
- Docker
- Docker Compose
- Node.js 18+ and **pnpm**
- MySQL 8 with a database named `Showzy` (connection settings in `backend/config/database.js`)
- A TMDB API key
### Installation
1. **Clone the repository**:
### 1. Backend
```bash
git clone https://github.com/X4Lo/showy.git
cd showy
cd backend
pnpm install
cp settings.json.example settings.json # then set tmdbApiKey, userDataPath, authPassword, jwtSecret
pnpm dev # http://localhost:4000/api/v1
```
2. **Set up environment variables**:
- Create a `.env` file in the `backend` directory with the following variables:
On start the backend syncs the schema and runs `config/migrations.js`, which adds any new columns to an existing database (additive only).
### 2. Frontend
```bash
PORT=3000
DB_HOST=mysql
DB_USER=root
DB_PASSWORD=yourpassword
DB_NAME=showy
cd react_frontend
pnpm install
pnpm dev # http://localhost:4200
```
1. **Build and run the application with Docker Compose**:
The Vite dev server proxies `/api` to the backend; change the `proxy.target` in `vite.config.ts` to point at `http://localhost:4000` for local development.
### 3. Desktop app (optional)
```bash
docker-compose up --build
cd electron
pnpm install
pnpm build-front # builds the frontend into electron/frontend_build
pnpm start
```
4. **Access the app**:
- Frontend: Open your browser and navigate to `http://localhost:4200`.
- Backend API: Access the API at `http://localhost:3000`.
5. **(Optional) Run the app with Electron**:
- Follow the instructions in the `electron/README.md` to build and run the desktop app.
See [`docs-vault/Electron.md`](docs-vault/Electron.md) for packaging. The Tauri version lives in `tauri/` on the `feat/tauri-app` branch (see its `tauri/README.md`).
## Acknowledgments
### Docker
- Thanks to the Angular, Node.js, and Express communities for their amazing tools and libraries.
- Special thanks to (mention any libraries or tools you used, e.g., TMDB API for movie data).
`docker-compose up --build` starts MySQL, the backend (port 4000) and the **legacy Angular** frontend (port 3000). The React frontend isn't in Docker yet.
---
## Documentation
Detailed docs live in [`docs-vault/`](docs-vault/Index.md) — architecture, API reference, database models, TMDB integration, every page and feature, and known issues.
---
## Contact
For questions or feedback, feel free to reach out:
- **Mohammed Abad**: [mohammedabad.me@gmail.com](mailto:mohammedabad.me@gmail.com)
- **GitHub**: [X4Lo](https://github.com/X4Lo)
- **Mohammed Abad**: [mohammedabad.me@gmail.com](mailto:mohammedabad.me@gmail.com)
- **GitHub**: [X4Lo](https://github.com/X4Lo)
---
Enjoy managing your movies and series with **Showy**! 🎬🍿
Data provided by [TMDB](https://www.themoviedb.org/). This product uses the TMDB API but is not endorsed or certified by TMDB.
+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;
+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);
+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();
+12
View File
@@ -199,3 +199,15 @@ Response types:
- **Duplicate credits:** `{ groups: number, duplicates: number, deleted: number }`
- **Auto-fix watch statuses:** `{ completed: number, watching: number, planToWatch: number }`
- **Impossible seen dates:** Scan → `{ count: number }`, Fix → `{ count: number, added: number }`
## entries.ts — additions
`getRecommendations(id)`, `getTmdbRecommendations(type, tmdbId)`, `getArtwork(id)`, `getTmdbArtwork(type, tmdbId)`, `addArtwork(id, { type, file_path })`
## maintenance.ts — additions
`getStaleEntries(hours)`, `startStaleRefresh(hours)` (202 or 409), `cancelStaleRefresh()`
## history.ts
`historyApi.getYears()`, `historyApi.getYear(year)` — types `HistoryYear`, `HistoryEntry`, `HistoryEpisode`, `HistoryEvent`, `HistoryYearData`
+32 -2
View File
@@ -57,7 +57,10 @@ All endpoints are prefixed with `/api/v1`. See [[Backend]] for server setup.
| `DELETE` | `/entries/:id` | Delete entry and all related data |
| `GET` | `/entries/:id/seasons` | Get all seasons for a TV entry |
| `GET` | `/entries/:id/credits` | Get ALL credits (cast + crew) for an entry, with associated `person` populated. Used by [[Pages#EntryCastsPage\|EntryCastsPage]] |
| `PUT` | `/entries/:id/refresh` | Force refresh from TMDB |
| `GET` | `/entries/:id/recommendations` | Live TMDB recommendations for a library entry (not stored) |
| `GET` | `/entries/:id/artwork` | TMDB posters/backdrops/logos merged with the entry's media — see [[Artwork]] |
| `POST` | `/entries/:id/artwork` | Download a TMDB image into the media table: `{ type, file_path }` |
| `PUT` | `/entries/:id/refresh` | Force refresh from TMDB (details, ids, ratings, genres, networks, seasons, episodes, credits) |
| `PUT` | `/entries/:id/fetch-collection` | Fetch/create TMDB collection for entry |
| `GET` | `/entries/sync-series` | Batch refresh all non-ended TV series |
| `POST` | `/entries/:id/media` | Upload media (multipart — poster/backdrop/logo) |
@@ -73,7 +76,9 @@ All endpoints are prefixed with `/api/v1`. See [[Backend]] for server setup.
| `GET` | `/entries/tmdb/top-rated/:type` | Top-rated movies/tv |
| `GET` | `/entries/tmdb/upcoming/movie` | Upcoming movies |
| `GET` | `/entries/tmdb/search?query=&page=` | Multi-search |
| `GET` | `/entries/tmdb/preview/:type/:tmdbId` | Preview TMDB entry (movie/tv) before adding — returns local + TMDB data |
| `GET` | `/entries/tmdb/preview/:type/:tmdbId` | Preview a TMDB entry before adding. Includes `entry` (same shape as a library entry), `seasons` and `credits` (cast + directors) |
| `GET` | `/entries/tmdb/recommendations/:type/:tmdbId` | Recommendations by TMDB id (entries not in the library) |
| `GET` | `/entries/tmdb/artwork/:type/:tmdbId` | TMDB artwork by TMDB id (read-only) |
---
@@ -228,6 +233,19 @@ See [[Statistics]] for chart details.
---
## History
> [!info] File: `routes/history.routes.js` → `services/historyService.js`
See [[History]].
| Method | Path | Description |
|---|---|---|
| `GET` | `/history/years` | Years with watches, newest first: `[{ year, movies, episodes }]` |
| `GET` | `/history/:year` | Every movie/episode watch in a year, newest first: `{ year, entries: { [id]: entry }, events: [...] }` |
---
## Settings
> [!info] File: `routes/settings.routes.js` → `controllers/settingsController.js`
@@ -302,6 +320,18 @@ See [[Settings Page#Cleanup]] for the UI.
---
### Stale Entries Refresh
| Method | Path | Description |
|---|---|---|
| `GET` | `/maintenance/stale-entries?hours=24` | Count of entries not refreshed in the last `hours` + current job status |
| `POST` | `/maintenance/stale-entries/refresh?hours=24` | Start refreshing them in the background (`202`; `409` if already running) |
| `DELETE` | `/maintenance/stale-entries/refresh` | Cancel the running job |
Entries with auto sync off are skipped. TMDB requests go through the [[TMDB Integration#Rate Limiting|rate limiter]].
---
## Import
> [!info] File: `routes/import.routes.js` → `controllers/importController.js`
+48
View File
@@ -0,0 +1,48 @@
---
title: Artwork
tags:
- feature
- media
- tmdb
---
# Artwork
## Overview
The **Artwork** section at the bottom of [[Pages#EntryDetailsPage|EntryDetailsPage]] lists every TMDB poster, backdrop and logo for the title, merged with the entry's [[Media System|media table]].
## UI
- Tabs: **Posters / Backdrops / Logos** with counts
- **Two rows** shown per tab (columns follow the breakpoint); **Show more** adds two rows
- Language filter (no-text images first, then English, then the original language); **In library** toggle
- Badges: **In library** / **Selected**; language tag; TMDB vote average on hover
- Click an image to open it full size
- Library entries: **Add** downloads the original into the media table; titles not in the library are read-only
## Matching
Media rows record the TMDB `file_path` they were downloaded from in `media.tmdb_path` (`tmdbPath`). A TMDB image is **in library** when a media row of the same type has that path. Media without a path (custom uploads, images downloaded before the column existed) appear as local-only items first.
> [!warning] Older downloads
> Images downloaded before `tmdb_path` existed can't be matched, so the same TMDB image can be added again. See [[Known Issues]].
## Adding
`POST /entries/:id/artwork { type, file_path }`:
1. Validates the type (`poster` / `backdrop` / `logo`) and path
2. Returns the existing row if that image is already in the library
3. Downloads `https://image.tmdb.org/t/p/original{file_path}` into `images/entries/{type}s/`
4. Creates the media row — **selected** only if no image of that type is selected yet
5. Generates the preview file
## Implementation
| Layer | File |
|---|---|
| Service | `backend/services/artworkService.js` |
| Endpoints | `GET /entries/:id/artwork`, `POST /entries/:id/artwork`, `GET /entries/tmdb/artwork/:type/:tmdbId` |
| Hooks | `useArtwork`, `useAddArtwork` in `react_frontend/src/hooks/useEntries.ts` |
| Component | `react_frontend/src/components/entries/ArtworkSection.tsx` |
+20
View File
@@ -82,6 +82,26 @@ See [[Discovery Videos]].
| `VideoDropzone` | `discovery-videos/VideoDropzone.tsx` | Native HTML5 drag & drop zone (no dependency) |
| `EntryMultiSelect` | `discovery-videos/EntryMultiSelect.tsx` | Search-first library entry picker (debounced 250 ms) reading from [[Stores\|library store]] |
## Entry Detail Components
| Component | File | Purpose |
|---|---|---|
| `ArtworkSection` | `components/entries/ArtworkSection.tsx` | [[Artwork]] tabs, language filter, add to library |
| `WatchProvidersCard` | `components/entries/WatchProvidersCard.tsx` | Where to watch, per country |
| `TrailerDialog` | `components/entries/TrailerDialog.tsx` | In-app YouTube player for stored TMDB videos |
| `RecommendationsSection` | `components/entries/RecommendationsSection.tsx` | "More like this" by entry id or TMDB id |
| `SeasonsContainer` | `components/entries/SeasonsContainer.tsx` | Seasons with list/cards toggle; cards show a circular progress ring around the mark-watched button |
| `SeasonEpisodes`, `EpisodeViewToggle` | `components/entries/SeasonEpisodes.tsx` | Season page episodes in list or card view |
| `DetailHero` (+ `MetaItem`, `HeroChip`, `IconAction`, `IconLink`, `DetailSection`, `DetailCard`, `DetailRow`) | `components/entries/DetailHero.tsx` | Shared hero and building blocks for the season and episode pages |
## History Components
| Component | File | Purpose |
|---|---|---|
| `HistoryList` | `components/history/HistoryList.tsx` | Months → days → rows |
| `HistoryTimeline` | `components/history/HistoryTimeline.tsx` | Vertical timeline with month dividers |
| `YearInReview` | `components/history/YearInReview.tsx` | Wrapped-style stats |
## Skeletons
> [!info] File: `components/skeletons/PageSkeletons.tsx`
+2
View File
@@ -15,6 +15,7 @@ MySQL database named **Showzy**, managed by Sequelize 6 ORM.
- Connection: `localhost`, user `root`, password `password`
- Sync mode: `sequelize.sync({ alter: false })` — no auto-alter in production
- Migrations: `config/migrations.js` runs after sync on every start. It adds any column a model defines that the table lacks (additive only, nothing is dropped) and widens a few changed types (`certification`, `last_fetch`, `network_studio`, `networks.name`). New model attributes reach existing databases automatically on the next start.
- Logging: writes SQL to `sequelize.log`
- Genre seeding: 27 TMDB genres auto-seeded on startup
@@ -109,6 +110,7 @@ See [[Models]] for detailed field definitions of every model.
## Important Files
- `backend/config/database.js` — Sequelize connection
- `backend/config/migrations.js` — Startup column migrations
- `backend/config/relations.js` — All associations
- `backend/config/dataInitializer.js` — Genre seeding
- `backend/config/sequelizeHooks.js` — Collection order hooks
+3
View File
@@ -7,6 +7,9 @@ tags:
# Electron
> [!note] Tauri in progress
> A Tauri v2 version of the desktop app is being built in `tauri/` on the `feat/tauri-app` branch (not merged yet). Electron stays as is until it's ready. Dev mode works on Windows; the release build is blocked by the packaged backend resolving `settings.json` from inside pkg's read-only bundle. See `tauri/README.md` on that branch.
## Overview
Electron 34 wraps the Showy backend + React frontend into a standalone desktop application for Windows. The backend runs **in-process** (no child process spawn), and the app uses a custom frameless title bar with IPC-driven window controls.
+59
View File
@@ -0,0 +1,59 @@
---
title: History
tags:
- feature
- history
- watch-tracking
---
# History
## Overview
Everything you watched, by year, at `/history` (sidebar → History, or the command palette). Built from [[Watch Tracking|EntrySeen and EpisodeSeen]] records.
## Controls
- **Year picker** — only years with watches; previous / next arrows
- **Type filter** — All / Movies / TV
- Tab, year and filter are kept in the URL: `/history?tab=timeline&year=2024&type=tv`
## Tabs
### History
Months newest first, each with a sticky header (movies, episodes, watch time). Inside each month, watches are grouped by day. Each row shows the poster, title, episode, runtime and who you watched with.
### Timeline
A vertical line from the latest watch at the top down to January, with a divider per month. Poster cards alternate sides on wide screens; the dot colour marks movies (amber) or TV (blue).
### Year in Review
Wrapped-style stats: total hours (and full days), movies, episodes, shows, days watching, longest streak, busiest day, biggest binge, favourite weekday and month, top 5 shows, top genres by time, month-by-month and weekday charts, top-rated movies, rewatches, top networks, watch buddies, new shows started (first episode watched was S1E1), and the first and last watch of the year.
## Sessions
Episodes of the same show watched back to back on the same day are grouped into one **session** (e.g. "S1 E1–E5 · 5 episodes"). Lists and the timeline show sessions; the review counts individual watches.
## Unknown Dates
Watches with `accuracy = UNKNOWN` (bulk imports) are badged "Date unknown". The Year in Review leaves them out by default because they distort streaks, busiest days and monthly charts; a checkbox includes them.
## Implementation
| Layer | File |
|---|---|
| Endpoints | `backend/routes/history.routes.js` — `GET /history/years`, `GET /history/:year` |
| Service | `backend/services/historyService.js` |
| API client / hooks | `react_frontend/src/api/history.ts`, `react_frontend/src/hooks/useHistory.ts` |
| Grouping & stats | `react_frontend/src/lib/history.ts` — `buildSessions`, `groupByMonth`, `computeReview` |
| Page | `react_frontend/src/pages/HistoryPage.tsx` |
| Tabs | `react_frontend/src/components/history/` — `HistoryList`, `HistoryTimeline`, `YearInReview` |
`GET /history/:year` returns each title once in `entries` (poster, runtime, genres, networks, rating) and references it from every watch in `events`. A busy year (~1,650 watches) is about 530 KB.
## See Also
- [[Watch Tracking]]
- [[Statistics]] — all-time charts on the dashboard
+13
View File
@@ -140,6 +140,19 @@ See [[Discovery Videos]].
| `useUpdateVideo()` | Mutation | `PUT /discovery-videos/:id` |
| `useDeleteVideo()` | Mutation | `DELETE /discovery-videos/:id` |
## useEntries — TMDB data additions
- `useEntryRecommendations(id)` / `useTmdbRecommendations(tmdbId, type)` — "More like this"
- `useArtwork({ entryId } | { tmdbId, type })` / `useAddArtwork(entryId)` — [[Artwork]]
- `useTmdbPreview(tmdbId, type)` — also returns the entry-shaped `entry` used by the unified details page
## useHistory
> [!info] File: `hooks/useHistory.ts`
- `useHistoryYears()` — `GET /history/years`
- `useHistoryYear(year)` — `GET /history/:year`
## useDebounce
> [!info] File: `hooks/useDebounce.ts`
+4 -2
View File
@@ -23,7 +23,7 @@ aliases:
- [[Tech Stack]] — All technologies and versions
- [[Deployment]] — Docker Compose setup
- [[Env]] — Environment variables and configuration
- [[Electron]] — Desktop wrapper details
- [[Electron]] — Desktop wrapper details (a Tauri version is in progress)
## Backend
@@ -35,12 +35,13 @@ aliases:
- [[Error Handling]] — Custom error classes and middleware
- [[TMDB Integration]] — External API proxy and data fetching
- [[Media System]] — Image storage, download, optimization, previews
- [[Artwork]] — TMDB posters/backdrops/logos merged with the media table
- [[Import System]] — Bulk import flows
## Frontend
- [[Frontend]] — React app structure, patterns, conventions
- [[Routing]] — All 17 routes with lazy loading
- [[Routing]] — All routes with lazy loading
- [[Pages]] — Every page component
- [[Components]] — All UI components by category
- [[Hooks]] — Custom hooks (queries, mutations, utilities)
@@ -55,6 +56,7 @@ aliases:
- [[Library]] — Entry management, watchlist, favorites
- [[Collections]] — TMDB and user collections
- [[Watch Tracking]] — EntrySeen, EpisodeSeen, accuracy system
- [[History]] — History list, timeline and year in review
- [[Streaming]] — In-app streaming system with 4 providers (8 servers)
- [[Calendar]] — Upcoming episodes view
- [[Discovery Videos]] — Personal video vault (upload + link to library entries)
+26 -3
View File
@@ -49,6 +49,12 @@ Tracked bugs and technical debt items.
- **Impact:** DoS risk if backend is exposed
- **Fix:** Gate behind dev-mode check
### Packaged Backend Can't Find settings.json
- **Issue:** `configService` resolves `settings.json` from `__dirname`, which points inside pkg's read-only snapshot in `backend.exe`
- **Impact:** Blocks the Tauri release build (sidecar backend); see [[Electron]]
- **Fix:** Resolve settings next to the executable (`process.execPath`) or a user data folder when running under pkg
## Frontend
### Implicit `any` Types in SeasonPage
@@ -71,6 +77,23 @@ Tracked bugs and technical debt items.
- **Impact:** [[Normalizers]] layer exists to handle this, but it's fragile
- **Fix:** Standardize backend response format (ideally all snake_case)
### Web Build Fails Type Checking
- **Issue:** `tsc -b` (and so `pnpm build`) reports ~41 existing errors, mostly `asChild` on Base UI components and `string | null` select values (LibraryPage, WatchlistPage, several dialogs)
- **Impact:** The plain web build fails; Vite dev, Electron and Tauri dev still run
- **Fix:** Replace `asChild` with `render` props and narrow select values
### Old Media Not Matched in Artwork
- **Issue:** Images downloaded before `media.tmdb_path` existed have no TMDB path
- **Impact:** They show as local-only in [[Artwork]], and the same TMDB image can be added again as a duplicate
- **Fix:** Backfill by re-downloading, or compare image hashes
### Unknown-Date Watches
- **Issue:** ~311 imported movie watches have `accuracy = UNKNOWN`
- **Impact:** Badged in [[History]] and excluded from the Year in Review by default (toggle to include)
## Database
### Franchise Model Unused
@@ -82,9 +105,9 @@ Tracked bugs and technical debt items.
### No Database Migrations
- **Issue:** Schema changes rely on `sequelize.sync({ alter })` which is disabled (`doUpdate = false`)
- **Impact:** Manual schema management required for changes
- **Fix:** Implement proper Sequelize migrations
- **Issue:** `sequelize.sync({ alter })` is disabled; `config/migrations.js` only adds missing columns and widens a fixed list of types
- **Impact:** Renames, drops and index changes still need manual SQL
- **Fix:** Adopt versioned Sequelize migrations if the schema starts changing in non-additive ways
## Docker
+3 -2
View File
@@ -51,9 +51,10 @@ All entries are held in [[Stores|useLibraryStore]] as a `Map<number, Entry>` for
## Pages
- [[Pages#LibraryPage|LibraryPage]] — Grid of all library entries
- [[Pages#LibraryPage|LibraryPage]] — Grid of all library entries (All / Movies / TV tabs + Favorites and Hidden toggles)
- [[Pages#WatchlistPage|WatchlistPage]] — Grid of watchlist entries
- [[Pages#EntryDetailsPage|EntryDetailsPage]] — Entry detail view
- [[Pages#EntryDetailsPage|EntryDetailsPage]] — Entry detail view (also used for titles not in the library)
- [[History]] — Everything watched, by year
## Related
+5
View File
@@ -66,6 +66,7 @@ Key fields:
- `path` — UUID filename on disk
- `isSelected` — the "active" image displayed in UI
- `isCustom` — user-uploaded (vs TMDB-downloaded)
- `tmdbPath` — TMDB `file_path` the image came from; recorded on every TMDB download so [[Artwork]] can mark images already in the library
## Serving URLs
@@ -96,6 +97,10 @@ See [[Media Utilities]] for how the frontend resolves which image to display:
1. Local selected media → 2. TMDB fallback → 3. Default placeholder
## Artwork
Entry pages list every TMDB poster, backdrop and logo merged with the media table, and can download any of them into it. See [[Artwork]].
## Maintenance
See [[Settings Page#Cleanup]] for orphan file/record detection and removal.
+41 -5
View File
@@ -34,8 +34,8 @@ The core model — represents a movie or TV series.
| `tagline` | STRING(200) | |
| `storyline` | STRING(3000) | |
| `country` | STRING(30) | |
| `certification` | INTEGER | |
| `network_studio` | STRING(40) | |
| `certification` | STRING(20) | e.g. `R`, `TV-14` (US first, then origin country) |
| `network_studio` | STRING(100) | First network, else first production company |
| `collection_id` | INTEGER | TMDB collection ID |
| `max_cast` | INTEGER | Default `10` |
| `credit_fetched` | BOOLEAN | Default `false` |
@@ -51,8 +51,28 @@ The core model — represents a movie or TV series.
| `banner_path` | STRING(200) | TMDB backdrop path |
| `date_first_seen` | DATEONLY | |
| `date_last_seen` | DATEONLY | |
| `last_fetch` | DATEONLY | Used by [[Services#Lazy Refresh\|lazy refresh]] |
| `last_fetch` | DATE | Last TMDB refresh (date + time); used by the [[API Reference#Stale Entries Refresh\|stale refresh]] |
| `entry_sync_status` | STRING(50) | Nullable. e.g. `"RequireCreditsSync"` |
| `adult` | BOOLEAN | |
| `tmdb_popularity` | FLOAT | |
| `original_language` | STRING(10) | |
| `origin_country` | JSON | `string[]` |
| `homepage` | STRING(500) | |
| `budget` / `revenue` | BIGINT | Movies only |
| `tv_type` | STRING(30) | TV only, e.g. `Scripted` |
| `number_of_seasons` / `number_of_episodes` | INTEGER | TV only |
| `last_air_date` | DATEONLY | TV only |
| `in_production` | BOOLEAN | TV only |
| `spoken_languages`, `production_countries`, `production_companies` | JSON | Detail page only* |
| `keywords` | JSON | `string[]`, up to 30* |
| `tmdb_videos` | JSON | YouTube trailers/teasers, up to 12* (not `videos`: that name is the Discovery Videos association) |
| `watch_providers` | JSON | Per-country stream/rent/buy providers* |
| `alternative_titles` | JSON | * |
| `created_by`, `next_episode_to_air`, `last_episode_to_air` | JSON | TV only* |
\* Listed in `Entry.DETAIL_ONLY_ATTRIBUTES` and excluded from the library list query (`GET /entries`) to keep it small.
All TMDB fields are filled by `mappers/entryMapper.js` — see [[TMDB Integration#Entry Mapper]].
**Has:** [[#EntryId]] (1:1), [[#EntryRating]] (1:1), [[#EntrySeen]] (1:N), [[#Season]] (1:N), [[#Credit]] (1:N), Genres (M:N), Networks (M:N), Collections (M:N), Media (polymorphic)
@@ -67,6 +87,7 @@ The core model — represents a movie or TV series.
| `id` | INTEGER PK AUTO | |
| `tmdb_id` | STRING(30) | |
| `imdb_id` | STRING(30) | |
| `tvdb_id` | STRING(30) | From the season's `external_ids` |
| `entry_id` | INTEGER FK | → Entry |
| `name` | STRING(500) | |
| `overview` | STRING(3000) | |
@@ -105,6 +126,10 @@ The core model — represents a movie or TV series.
| `air_date` | DATE | |
| `user_rating` | FLOAT | |
| `tmdb_rating` | FLOAT | |
| `tmdb_vote_count` | INTEGER | |
| `production_code` | STRING(50) | |
| `crew` | JSON | Directors + writers (`{ id, name, job, department, profile_path }`) |
| `guest_stars` | JSON | Up to 25 (`{ id, name, character, profile_path, order }`) |
| `still_path` | STRING(200) | |
| `date_first_seen` | DATEONLY | |
| `date_last_seen` | DATEONLY | |
@@ -163,6 +188,7 @@ Polymorphic image record. See [[Media System]].
| `mediaableId` | INTEGER | Polymorphic FK |
| `type` | STRING(50) | `'poster'`, `'backdrop'`, `'logo'`, `'still'`, `'profile'` |
| `path` | STRING(200) | UUID filename on disk |
| `tmdbPath` | STRING(200) | `tmdb_path` — TMDB `file_path` the image was downloaded from; null for custom uploads and images downloaded before it existed. Used by [[Artwork]] |
| `isLocal` | BOOLEAN | |
| `isSelected` | BOOLEAN | Default `false` — the "active" media |
| `isCustom` | BOOLEAN | Default `false` — user-uploaded |
@@ -245,6 +271,7 @@ See [[People]].
| `id` | INTEGER PK AUTO | |
| `tmdb_id` | STRING(100) | |
| `name` | STRING(100) | |
| `original_name` | STRING(200) | |
| `birthday` | DATEONLY | |
| `deathday` | DATEONLY | Nullable |
| `gender` | INTEGER | TMDB gender codes |
@@ -277,6 +304,12 @@ External ID storage (1:1 with Entry).
| `tmdb_id` | STRING(30) |
| `imdb_id` | STRING(30) |
| `tvdb_id` | STRING(30) |
| `wikidata_id` | STRING(30) |
| `facebook_id` | STRING(100) |
| `instagram_id` | STRING(100) |
| `twitter_id` | STRING(100) |
All filled from TMDB `external_ids` (TV series only have their IMDb id there).
**No timestamps.**
@@ -294,6 +327,7 @@ Multi-source ratings (1:1 with Entry).
| `entry_id` | INTEGER FK → Entry |
| `user_rating` | FLOAT |
| `tmdb_rating` | FLOAT |
| `tmdb_vote_count` | INTEGER |
| `imdb_rating` | FLOAT |
| `rotten_tomatoes_rating` | FLOAT |
@@ -324,7 +358,7 @@ Join table: Entry ↔ Network. Composite PK: `(network_id, entry_id)`. Has `orde
| Field | Type | Notes |
|---|---|---|
| `id` | INTEGER PK | TMDB genre ID (not auto-increment) |
| `name` | STRING(30) | |
| `name` | STRING(100) | |
**No timestamps.** Seeded with 27 TMDB genres on startup.
@@ -337,13 +371,15 @@ Join table: Entry ↔ Network. Composite PK: `(network_id, entry_id)`. Has `orde
| Field | Type |
|---|---|
| `id` | INTEGER PK (TMDB ID) |
| `name` | STRING(30) |
| `name` | STRING(100) |
| `originCountry` | STRING(100) |
| `homepage` | STRING(100) |
| `logoPath` | STRING(200) |
| `posterPath` | STRING(200) |
| `backdropPath` | STRING(200) |
`originCountry` and `logoPath` are filled from TMDB's `origin_country` / `logo_path` and refreshed with the entry.
**No timestamps.**
---
+36 -27
View File
@@ -30,6 +30,10 @@ Charts: `WatchActivityChart`, `WatchTimeChart`, `CouchDayChart`, `LibraryGrowthC
Entry grid showing all non-watchlist, non-hidden entries from [[Stores|library store]]. See [[Library]].
- Type tabs: **All / Movies / TV**
- **Favorites** and **Hidden** are independent toggle buttons that combine with the type tab (e.g. TV + Favorites = favorite shows). Hidden mode shows only hidden entries (watchlist included).
- Filter state lives in `useLibraryFiltersStore` (`favoritesOnly`, `hiddenOnly`)
## DiscoverPage
TMDB browse by category: popular, trending, top-rated, upcoming. Uses `useTmdb` infinite queries.
@@ -69,16 +73,17 @@ Monthly [[Calendar]] view showing upcoming episode air dates. Uses `episodesApi.
## EntryDetailsPage
The main entry detail view. Width constrained to `max-w-4xl`.
One page for both cases (`pages/EntryDetailsPage.tsx`):
Sections:
- `/entry/:id` — a library entry, loaded from the local DB
- `/entry/tmdb/:type/:tmdbId` — not in the library; renders the TMDB preview (`GET /entries/tmdb/preview/:type/:tmdbId` returns an `entry` object in the same shape as a library entry). Library-only actions are hidden and **Add to Library** replaces them. If the title is already in the library, the page redirects to `/entry/:id`.
- Backdrop + poster + title + metadata
- Actions: watchlist, favorite, refresh, settings, rating
- Watch history (movies) → [[Watch Tracking]]
- Seasons list (TV) → links to SeasonPage
- Cast list → links to PersonDetailsPage; shows episode count for TV; "All Cast & Crew" link → EntryCastsPage
- Media gallery → [[Media System]]
Layout (`max-w-6xl`):
- **Hero** — full-bleed backdrop fading into the page, large poster (click → full-size popup), type/certification/status chips, title (selectable), tagline, year · runtime/seasons · "Created by" (TV) · "Directed by"
- **Action bar** — Watch (streaming), Trailer (in-app player from stored TMDB videos, YouTube search fallback), mark watched, rate, favorite, add to collection, ⋯ menu (watch history / status, hide, refresh, manage media, settings, delete)
- **Main column** — Overview, Keywords, Cast ([[Components#Entry Components|CastList]]), Seasons ([[Components#Entry Components|SeasonsContainer]] with list/cards toggle), In Collections, More like this (live TMDB recommendations), [[Artwork]]
- **Sidebar** — IMDb / TMDB (+ vote count) / your rating tiles, Details card (release, runtime, episodes, last aired, next episode, network logos, type, language, budget, box office, studio, country, watched), external links (TMDB, IMDb, website, Wikidata, Instagram, X, Facebook), **Where to watch** card (per-country providers, defaults to the browser's region)
## EntryCastsPage
@@ -95,26 +100,22 @@ Full cast & crew grid for an entry. Route: `/entry/:id/cast`. Width: `max-w-4xl`
## SeasonPage
Season detail with episode list. Width: `max-w-4xl`.
Season detail (`max-w-6xl`), same visual language as the entry page.
- Breadcrumb: `Title / Season x` (see [[Navigation]])
- Episode progress bar
- **Mark Season Watched** button (always visible) → opens [[Components#Dialogs|MarkSeasonWatchedDialog]]
- **Single Date mode**: marks all unwatched episodes on one date
- **Scatter Mode**: distributes episodes evenly across a date range (start → end)
- Episode list with watch status
- Links to EpisodePage
- **Hero** — show backdrop, season poster, "← Back to {show}" button, show and season chips, "Completed" badge, year · episodes · total runtime · air-date range
- Rating chip (opens SeasonRatingDialog), TMDB rating, progress bar
- **Start / Continue: E#** — plays the first aired, unwatched episode
- Mark season watched → [[Components#Dialogs|MarkSeasonWatchedDialog]] (single date or scatter mode), rate, ⋯ (refresh season)
- **Episodes** with a **List / Cards** toggle (remembered per browser): stills (click to play), air date, runtime, TMDB rating, seen dates, finale / mid-season / upcoming badges, mark-watched button
## EpisodePage
Episode detail with watch history. Width: `max-w-4xl`.
Episode detail (`max-w-6xl`).
- Breadcrumb: `Title / Season x / Episode x` (see [[Navigation]])
- Episode thumbnail (TMDB still)
- `S##E##` display using `season.season_number` (not DB id)
- Prev/next episode navigation
- Watch history management
- Cast list
- **Hero** — episode still as backdrop, show / season chips, `S##E##`, finale / upcoming / watched badges, title, air date · runtime · TMDB rating + votes
- Actions: **Watch episode**, **Mark as watched / Watch again**, previous / next episode
- Main column: overview with "Directed by" / "Written by" (stored episode crew), Guest Stars (stored, linked by TMDB id), watch history (edit / delete), previous / next cards
- Sidebar: details card (aired, runtime, TMDB, production code, watched) and the season's episode list with the current one highlighted
## PeoplePage
@@ -122,15 +123,23 @@ Browse and search people (actors, directors). Both local DB and TMDB search.
## PersonDetailsPage
Person profile with biography, filmography. Uses lazy-fetch via [[Services#PeopleManager]].
One page for both cases (`pages/PersonDetailsPage.tsx`):
## PersonTmdbRedirectPage
- `/people/:id` — person in the local DB (favorite toggle; filmography from TMDB via the local id)
- `/people/tmdb/:tmdbId` — not in the DB; everything from the TMDB preview, with **Add to Library**. If TMDB reports a local id, redirects to `/people/:id`.
Takes a TMDB person ID, fetches/creates the local person record, redirects to `PersonDetailsPage`.
Both render one header (photo, name, department, born / died with age tooltip, place of birth, TMDB link, biography) and one filmography split into **In your library** and **Not in library**.
## HistoryPage
Watch history at `/history`. See [[History]].
- Year picker (only years with watches) and All / Movies / TV filter; tab, year and filter live in the URL (`?tab=&year=&type=`)
- Tabs: **History** (by month and day), **Timeline** (latest → January, month dividers, stacked binge sessions), **Year in Review** (wrapped-style stats)
## SettingsPage
App configuration + maintenance. See [[Settings Page]].
- General settings (TMDB API key, backend port)
- Cleanup section (orphan files, orphan media records)
- Maintenance: **TMDB Refresh** (stale entries job), media cleanup, watch statuses, duplicate credits, missing directors, impossible seen dates
+7 -1
View File
@@ -24,17 +24,23 @@ Every page uses `React.lazy()` with a custom `<Suspense>` skeleton fallback.
| `/library` | `LibraryPage` | `LibrarySkeleton` | [[Library]] grid/list |
| `/discover/:category` | `DiscoverPage` | `HomeSkeleton` | TMDB browse (popular, trending, top-rated, upcoming) |
| `/watchlist` | `WatchlistPage` | `WatchlistSkeleton` | Watchlist entries |
| `/history` | `HistoryPage` | `WatchlistSkeleton` | [[History]] — list, timeline, year in review |
| `/collections` | `CollectionsPage` | `CollectionsSkeleton` | [[Collections]] overview |
| `/collections/:id` | `CollectionDetailsPage` | `CollectionDetailsSkeleton` | Collection with entries |
| `/media` | `MediaPage` | `MediaSkeleton` | Media management |
| `/discovery-videos` | `DiscoveryVideosPage` | `DiscoveryVideosSkeleton` | Personal video vault — see [[Discovery Videos]] |
| `/calendar` | `CalendarPage` | `CalendarSkeleton` | [[Calendar]] upcoming episodes |
| `/entry/tmdb/:type/:tmdbId` | `EntryDetailsPage` | `EntryDetailsSkeleton` | Entry not in the library (TMDB preview, same page) |
| `/entry/tmdb/:type/:tmdbId/cast` | `TmdbCastsPage` | `PeopleSkeleton` | Full cast of a TMDB-only entry |
| `/entry/:id` | `EntryDetailsPage` | `EntryDetailsSkeleton` | Entry details, seasons, cast |
| `/entry/:id/cast` | `EntryCastsPage` | `EntryDetailsSkeleton` | Full cast & crew |
| `/entry/:entryId/season/:seasonId` | `SeasonPage` | `SeasonSkeleton` | Season episodes |
| `/entry/:entryId/season/:seasonId/episode/:episodeId` | `EpisodePage` | `EpisodeSkeleton` | Episode details |
| `/people` | `PeoplePage` | `PeopleSkeleton` | [[People]] browse |
| `/people/:id` | `PersonDetailsPage` | `PersonDetailsSkeleton` | Person profile + filmography |
| `/people/tmdb/:tmdbId` | `PersonTmdbRedirectPage` | `PersonDetailsSkeleton` | TMDB person → local redirect |
| `/people/tmdb/:tmdbId` | `PersonDetailsPage` | `PersonDetailsSkeleton` | Person not in the DB (TMDB data, same page) |
| `/watch-buddies` | `WatchBuddiesPage` | `PeopleSkeleton` | Watch buddies |
| `/watch-buddies/:id` | `WatchBuddyProfilePage` | `PeopleSkeleton` | Buddy profile |
| `/settings` | `SettingsPage` | `SettingsSkeleton` | [[Settings Page]] |
## Layout
+26 -6
View File
@@ -172,9 +172,9 @@ CRUD for [[Collections]]. Handles `UserCollectionEntry` join records.
See [[TMDB Integration]].
14 methods wrapping TMDB API v3 calls:
Every request goes through `tmdbGet(path, params)` — a rate-limited queue (20 req/s, 8 concurrent) with retries on 429 / 5xx / network errors. The API key is never logged.
`fetchEntryData`, `fetchSeasonData`, `fetchEntryMedia`, `fetchCollectionData`, `fetchEntryCredits`, `fetchPersonDetails`, `fetchPersonCombinedCredits`, `fetchTrending`, `fetchPopular`, `fetchTopRated`, `fetchUpcoming`, `searchMulti`, `searchPeople`, `fetchPopularPeople`
Methods: `fetchEntryData` (details + appended blocks), `fetchSeasonData`, `fetchEntryMedia`, `fetchEntryRecommendations`, `fetchCollectionData`, `fetchEntryCredits`, `fetchPersonDetails`, `fetchPersonCombinedCredits`, `fetchTrending`, `fetchPopular`, `fetchTopRated`, `fetchUpcoming`, `searchMulti`, `searchPeople`, `fetchPopularPeople`
### configService
@@ -218,11 +218,31 @@ See [[Import System]].
> [!info] File: `backend/services/maintenanceService.js`
See [[Settings Page#Cleanup]].
See [[Settings Page]].
- `deleteOrphanFiles(dry)` — Files on disk without DB records
- `deleteOrphanMediaRecords(dry)` — DB records without files on disk
- Both return `{ posters, logos, backdrops, stills }` counts
- `deleteOrphanFiles(dry)` / `deleteOrphanMediaRecords(dry)` — return `{ posters, logos, backdrops, stills }` counts
- `deleteOrphanPeople`, `fixMissingDirectors`, `cleanDuplicateCredits`, `autoFixWatchStatuses`, `fixImpossibleSeenDates`
- `getStaleEntries(hours)` — entries never fetched or fetched more than `hours` ago (auto sync on)
- `startStaleRefresh(hours)` / `getStaleRefreshStatus()` / `cancelStaleRefresh()` — background job that refreshes stale entries one at a time via `entryManager.refrechEntryById`
### artworkService
> [!info] File: `backend/services/artworkService.js`
See [[Artwork]].
- `getEntryArtwork(entryId)` — TMDB images merged with the entry's media rows (`in_library`, `media_id`, `is_selected`)
- `getTmdbArtwork(type, tmdbId)` — TMDB images only
- `addEntryArtwork(entryId, { type, file_path })` — downloads the original into the media table (deduplicated by `tmdbPath`; selected if none of that type is)
### historyService
> [!info] File: `backend/services/historyService.js`
See [[History]].
- `getYears()` — years with watches and their movie/episode counts
- `getYear(year)` — every watch in a year with entries listed once
### logService
+10 -1
View File
@@ -10,7 +10,7 @@ tags:
## Overview
App configuration and maintenance tools at `/settings`. Contains two card sections.
App configuration and maintenance tools at `/settings`, in two tabs: **General** and **Maintenance**.
## General Settings
@@ -23,6 +23,15 @@ Form using react-hook-form + zod validation.
Saved via `PUT /api/v1/settings`.
## TMDB Refresh
First card on the Maintenance tab. Refreshes entries whose `last_fetch` is older than N hours (default 24) — details, ids, ratings, genres, networks, seasons, episodes and credits.
- Shows how many entries are due; **Refresh stale entries** starts a background job, **Cancel** stops it
- Live progress (polled every 2s while running): done/total, ok, failed, current title; failures listed when finished
- Rate limited, so a large library takes a while; entries with auto sync off are skipped
- Endpoints: [[API Reference#Stale Entries Refresh]]
## Cleanup
Maintenance tools for cleaning up orphaned data. Uses backend maintenance endpoints.
+1 -1
View File
@@ -65,7 +65,7 @@ useStreamingStore (Zustand)
## Data Flow
1. User clicks "Watch Now" / "Continue Watching" on [[Entry Details Page|EntryDetailsPage]]
1. User clicks "Watch Now" / "Continue Watching" on [[Pages#EntryDetailsPage|EntryDetailsPage]]
2. `StreamingSection` determines the request (movie or TV + season/episode)
3. `useStreamingStore.play()` builds a URL via the active server's provider adapter
4. `StreamingPlayer` renders an iframe with the embed URL
+65 -39
View File
@@ -10,33 +10,47 @@ tags:
## Overview
Showy uses **TMDB API v3** as its primary source for movie and TV metadata. All TMDB calls are proxied through the backend — the frontend never contacts TMDB directly.
Showy uses **TMDB API v3** as its source for movie, TV and people metadata. All TMDB calls go through the backend — the frontend never talks to TMDB directly, so the API key stays server-side.
## Configuration
- API base URL: `https://api.themoviedb.org/3`
- API key stored in `settings.json` → `tmdbApiKey`
- Managed by `configService`
- API base URL: `settings.json` → `tmdbApiUrl` (e.g. `https://api.themoviedb.org/3/`)
- API key: `settings.json` → `tmdbApiKey`
- Read by `configService`
## Rate Limiting
> [!info] File: `backend/services/tmdbService.js` → `tmdbGet(path, params)`
Every TMDB request goes through one queue so bulk jobs (like the [[API Reference#Stale Entries Refresh|stale entries refresh]]) never get the IP blocked:
- **20 requests per second**, **8 in flight** at once (TMDB allows ~50/s)
- **429** → waits for `Retry-After`, then retries; **5xx / network errors** → exponential backoff
- Up to 4 attempts per request
- Requests are logged as `TMDB GET <path>?<params>` **without** the API key
Measured: 45 requests went out at 20 / 20 / 5 per second, all succeeded.
The legacy [[Import System]] keeps its own extra throttle (35 requests per 10 s) on top.
## tmdbService
> [!info] File: `backend/services/tmdbService.js`
### Entry Data
| Method | TMDB Endpoint | Returns |
| Method | TMDB Endpoint | Notes |
|---|---|---|
| `fetchEntryData(tmdbId, isTV)` | `/movie/{id}` or `/tv/{id}` | Full entry metadata |
| `fetchSeasonData(tmdbId, seasonNum)` | `/tv/{id}/season/{num}` | Season with episodes |
| `fetchEntryMedia(tmdbId, isTV)` | `/movie/{id}/images` or `/tv/{id}/images` | Posters, backdrops, logos |
| `fetchEntryCredits(tmdbId, isTV)` | `/movie/{id}/credits` or `/tv/{id}/credits` | Cast and crew |
| `fetchCollectionData(collectionId)` | `/collection/{id}` | Collection with parts |
| `fetchEntryData(tmdbId, isTV)` | `/movie/{id}` or `/tv/{id}` | Appends `external_ids`, `release_dates` (movie) / `content_ratings` (TV), `keywords`, `videos`, `watch/providers`, `alternative_titles` in the same request |
| `fetchSeasonData(tmdbId, seasonNum)` | `/tv/{id}/season/{num}` | Appends `external_ids`; episodes include `crew` and `guest_stars` |
| `fetchEntryMedia(tmdbId, isTV)` | `/{type}/{id}/images` | All languages (no `language` param) |
| `fetchEntryCredits(tmdbId, isTV)` | `/movie/{id}/credits` or `/tv/{id}/aggregate_credits` | |
| `fetchEntryRecommendations(tmdbId, isTV, page)` | `/{type}/{id}/recommendations` | Live, never stored |
| `fetchCollectionData(collectionId)` | `/collection/{id}` | |
### Person Data
| Method | TMDB Endpoint |
|---|---|
| `fetchPersonDetails(tmdbId)` | `/person/{id}` |
| `fetchPersonDetails(tmdbId)` | `/person/{id}` (+ `external_ids`) |
| `fetchPersonCombinedCredits(tmdbId)` | `/person/{id}/combined_credits` |
### Browse & Search
@@ -51,41 +65,53 @@ Showy uses **TMDB API v3** as its primary source for movie and TV metadata. All
| `searchPeople(query)` | `/search/person` |
| `fetchPopularPeople()` | `/person/popular` |
## Frontend TMDB Proxy
All methods return `null` on failure (after retries) and log the error.
The frontend accesses TMDB data through backend proxy endpoints (see [[API Reference#TMDB Proxy]]):
## Entry Mapper
> [!info] File: `backend/mappers/entryMapper.js`
One place that turns TMDB responses into column values. Used by entry creation (`entryService.createEntry`), the refresh (`entryManager.refrechEntryById`), the season refresh (`seasonController.refreshSeason`), the legacy importer (`models-services/entryService.saveEntry`) and the TMDB preview endpoint.
| Function | Fills |
|---|---|
| `mapEntryFields(data)` | Entry columns — title, dates, runtime (TV falls back to `episode_run_time` then the last episode's runtime), certification (US → GB → origin country; theatrical first for movies), network/studio, budget/revenue, languages, countries, companies, homepage, keywords, trimmed videos and watch providers, alternative titles, TV type/creators/season & episode counts/last air date/next & last episode |
| `mapEntryIds(data)` | IMDb (from `external_ids` for TV), TVDB, Wikidata, Facebook, Instagram, X |
| `mapEntryRatings(data)` | `tmdb_rating`, `tmdb_vote_count` |
| `mapSeasonFields(seasonData)` | Season columns incl. `tvdb_id` |
| `mapEpisodeFields(episode)` | Episode columns incl. vote count, production code, directors/writers, guest stars |
See [[Models#Entry]] for every stored field.
## Refresh
`PUT /entries/:id/refresh` (and the stale job) re-fetches and updates:
- Entry, ids and ratings via the mapper
- Genres and networks — **synced both ways** (added and removed); network name, country and logo refreshed
- Seasons and episodes (matched by TMDB id)
- Credits and people
### Stale Entries Refresh
`POST /maintenance/stale-entries/refresh?hours=24` refreshes, one at a time, every entry whose `last_fetch` is older than `hours` (or never set), skipping entries with auto sync off. Progress is available from `GET /maintenance/stale-entries`; the UI is the TMDB Refresh card in [[Settings Page#TMDB Refresh]].
## Frontend TMDB Proxy
```
Frontend → /api/v1/entries/tmdb/trending/movie → Backend → TMDB API → Response
```
This keeps the API key server-side.
See [[API Reference#TMDB Proxy]]. The preview endpoint (`/entries/tmdb/preview/:type/:tmdbId`) returns an `entry` object in the same shape as a library entry, so [[Pages#EntryDetailsPage|EntryDetailsPage]] renders titles that aren't in the library.
## Image URLs
TMDB image base URL: `https://image.tmdb.org/t/p/`
Common sizes used:
- Posters: `w185`, `w342`, `w500`
- Backdrops: `w780`, `w1280`, `original`
- Stills: `w300`, `w780`, `original`
- Profiles: `w185`, `w300`
- Logos / providers: `w92`, `w500`
- Posters: `w342`, `w500`, `w780`
- Backdrops: `w780`, `w1280`
- Stills: `w300`, `w1280`
- Profiles: `w185`
See [[Media Utilities]] for frontend URL resolution and [[Media System]] for local image caching.
## Lazy Refresh Pattern
Used by [[Services#EntryManager]] and [[Services#PeopleManager]]:
1. Check `last_fetch` or `fully_fetched` field
2. If stale (>24h) or never fetched → call TMDB
3. Update local data + set `last_fetch` to today
4. TV series with `status = "Ended"` skip refresh
## Rate Limiting
The [[Import System]] self-throttles to stay under TMDB limits:
- Max 35 requests per 10 seconds
- 500ms delay between individual requests
See [[Media Utilities]] for frontend URL resolution, [[Media System]] for local caching and [[Artwork]] for browsing and adding TMDB images.
+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),
};
@@ -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",
@@ -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,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">
<h3 className="text-lg font-semibold">Seasons</h3>
<div className="space-y-2">
{display.map((season) => (
<SeasonItem key={season.id} season={season} entryId={entryId} />
))}
<div className="flex items-center justify-between gap-3">
<h3 className="text-lg font-semibold">Seasons</h3>
<EpisodeViewToggle view={view} onChange={changeView} />
</div>
{sorted.length > 2 && (
{view === "cards" ? (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-4">
{display.map((season) => (
<SeasonCard
key={season.id}
season={season}
entryId={entryId}
onMarkWatched={() => setMarkingSeason(season)}
/>
))}
</div>
) : (
<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,87 +93,208 @@ 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")}
alt={season.name}
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
{/* Info */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<span className="font-medium text-sm truncate">{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}
</span>
</div>
</div>
{/* Quick watch button - opens dialog */}
{nextUnwatched && (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setDialogOpen(true);
}}
>
<Play className="h-4 w-4" />
</Button>
)}
</Link>
{nextUnwatched && dialogOpen && (
<EpisodeSeenEditDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
mode="create"
episodeId={nextUnwatched.id}
entryId={entryId}
<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"
>
<div className="h-16 w-11 shrink-0 overflow-hidden rounded bg-muted">
<img
src={getTmdbPosterUrl(season.poster_path, "w92")}
alt={season.name}
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<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="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>
{canMark && (
<Button
size="icon"
variant="ghost"
className="h-8 w-8 shrink-0"
aria-label="Mark next episode as watched"
title="Mark next episode as watched"
onClick={(e) => stop(e, onMarkWatched)}
>
<Eye className="h-4 w-4" />
</Button>
)}
</>
</Link>
);
}
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,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>
);
}
@@ -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" },
+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,
});
}
+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,
};
}
+368 -209
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,19 +11,39 @@ 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 { 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). */
@@ -47,32 +65,29 @@ function toGuestCredit(guest: EpisodePerson): Credit {
};
}
const pad = (n: number | null | undefined) => String(n ?? 0).padStart(2, "0");
export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{
entryId: string;
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,
);
@@ -83,215 +98,320 @@ 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="h-6 w-48" />
<Skeleton className="h-4 w-80" />
<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-20 w-full" />
</div>
</div>
);
}
const canPlay = !!entry?.entryIds?.tmdb_id && !!seasonNumber;
const watchEpisode = () => {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: seasonNumber,
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="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={() => {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: seasonNumber,
episode: episode.episode_number,
});
setStreamingOpen(true);
}}
>
<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
<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>
</div>
)}
{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}
>
<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>
)}
{nextEpisode && (
<IconLink
to={episodeHref(nextEpisode)}
label={`Next: E${nextEpisode.episode_number}`}
>
<ChevronRight className="h-4 w-4" />
</IconLink>
)}
</div>
</div>
)}
</DetailHero>
{/* Info */}
<div className="space-y-3">
<h1 className="text-2xl font-bold">{episode.name}</h1>
<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="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>
)}
<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>
{episode.guest_stars && episode.guest_stars.length > 0 && (
<CastList
title="Guest Stars"
credits={episode.guest_stars.map(toGuestCredit)}
/>
)}
{watchHistory.length > 0 && (
<EpisodeWatchHistory
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as
EpisodeSeen | undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
/>
)}
{/* Prev / Next */}
{(prevEpisode || nextEpisode) && (
<div className="grid gap-3 sm:grid-cols-2">
{prevEpisode ? (
<NeighbourCard
episode={prevEpisode}
href={episodeHref(prevEpisode)}
direction="prev"
/>
) : (
<div className="hidden sm:block" />
)}
{nextEpisode && (
<NeighbourCard
episode={nextEpisode}
href={episodeHref(nextEpisode)}
direction="next"
/>
)}
</div>
)}
</div>
{episode.overview && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl">
{episode.overview}
</p>
)}
{/* 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>
{episode.crew && episode.crew.length > 0 && (
<div className="space-y-1 text-sm">
{(["Director", "Writer"] as const).map((job) => {
const people = 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,
);
if (people.length === 0) return null;
return (
<p key={job} className="text-muted-foreground">
{job === "Director" ? "Directed by" : "Written by"}{" "}
{people.map((p, i) => (
<span key={p.id}>
{i > 0 && ", "}
{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={`/people/tmdb/${p.id}`}
className="font-medium text-foreground hover:underline"
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"
}`}
>
{p.name}
<span className="w-7 shrink-0 text-xs text-muted-foreground tabular-nums">
E{ep.episode_number}
</span>
<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>
</span>
))}
</p>
);
})}
</div>
)}
</div>
{/* Guest Stars (stored from TMDB; link to their TMDB person page) */}
{episode.guest_stars && episode.guest_stars.length > 0 && (
<>
<Separator />
<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;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
/>
</>
)}
{/* Prev / Next navigation */}
<Separator />
<div className="flex items-center justify-between gap-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>
) : (
<div />
)}
{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}`,
)
}
>
<span className="truncate">
E{nextEpisode.episode_number}: {nextEpisode.name}
</span>
<ChevronRight className="h-4 w-4 shrink-0" />
</Button>
) : (
<div />
)}
</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 */}
@@ -302,7 +422,7 @@ export function EpisodePage() {
mode="create"
episodeId={episode.id}
entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)}
seasonId={seasonIdNum}
/>
)}
@@ -316,7 +436,7 @@ export function EpisodePage() {
mode="edit"
record={editRecord}
entryId={entryIdNum}
seasonId={parseInt(seasonId!, 10)}
seasonId={seasonIdNum}
/>
)}
@@ -336,7 +456,7 @@ export function EpisodePage() {
id: deleteTarget,
entryId: entryIdNum,
episodeId: epId,
seasonId: parseInt(seasonId!, 10),
seasonId: seasonIdNum,
});
setDeleteTarget(null);
}
@@ -358,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>
);
}
+227 -250
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,245 +100,199 @@ 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}
</span>
</div>
<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"
/>
{/* 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>
<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>
<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"
>
<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="icon"
variant="outline"
className="shrink-0 self-end sm:self-start"
size="lg"
className="h-11 gap-2 px-6"
onClick={() => handleWatchEpisode(nextUp)}
disabled={!entry?.entryIds?.tmdb_id}
>
<Ellipsis className="h-4 w-4" />
<Play className="h-4 w-4 fill-current" />
{watchedCount > 0 ? "Continue" : "Start"}: E
{nextUp.episode_number}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem onClick={() => setShowMarkAllDialog(true)}>
<ListChecks className="mr-2 h-4 w-4" />
Mark Season Watched
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setShowRatingDialog(true)}>
<Star className="mr-2 h-4 w-4" />
Rate Season
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => refreshSeason.mutate(season.id)}
disabled={refreshSeason.isPending}
)}
<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"
/>
}
>
<RefreshCw
className={`mr-2 h-4 w-4 ${refreshSeason.isPending ? "animate-spin" : ""}`}
/>
Refresh Season
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>Season {season.season_number}</span>
{season.air_date && (
<>
<span>•</span>
<span>{getYear(season.air_date)}</span>
</>
)}
<span>•</span>
<span>{totalEpisodes} episodes</span>
<MoreHorizontal className="h-4 w-4" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
onClick={() => refreshSeason.mutate(season.id)}
disabled={refreshSeason.isPending}
>
<RefreshCw
className={`mr-2 h-4 w-4 ${refreshSeason.isPending ? "animate-spin" : ""}`}
/>
{refreshSeason.isPending
? "Refreshing..."
: "Refresh season"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</DetailHero>
{/* 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>
{season.overview && (
<p className="text-sm text-muted-foreground max-w-lg">
<div className="mx-auto mt-4 max-w-6xl space-y-10">
{season.overview && (
<DetailSection title="Overview">
<p className="select-text max-w-prose text-[15px] leading-relaxed text-foreground/85">
{season.overview}
</p>
)}
</div>
</div>
</DetailSection>
)}
{/* 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"
>
{/* 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"
/>
) : (
<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
title="Episodes"
action={<EpisodeViewToggle view={view} onChange={changeView} />}
>
<SeasonEpisodes
episodes={episodes}
view={view}
entryId={entryIdNum}
seasonId={seasonIdNum}
onPlay={handleWatchEpisode}
onMarkWatched={setDialogEpisode}
/>
</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}
/>
)}
<SeasonRatingDialog
open={showRatingDialog}
onOpenChange={setShowRatingDialog}
season={season}
/>
{/* Streaming dialog */}
{entry && streamingOpen && (
+11
View File
@@ -26,6 +26,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 })),
);
@@ -161,6 +164,14 @@ export const router = createRouter([
</SuspensePage>
),
},
{
path: "/history",
element: (
<SuspensePage fallback={<WatchlistSkeleton />}>
<HistoryPage />
</SuspensePage>
),
},
{
path: "/watchlist",
element: (