From 25b645a16f50dc92a083606979f56c0d29198cd0 Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Mon, 27 Apr 2026 04:03:02 +0100 Subject: [PATCH 1/2] feat(backend): add TMDB preview endpoint for non-library entries - Add GET /entries/tmdb/preview/:type/:tmdbId endpoint in entryController.js - Fetch TMDB data via tmdbService.fetchEntryData() without persisting to DB - Return normalized preview object with title, poster, genres, rating, season/episode counts --- backend/config/dataInitializer.js | 18 ++++++++- backend/controllers/entryController.js | 33 ++++++++++++++++ backend/controllers/maintenanceController.js | 10 +++++ backend/controllers/peopleController.js | 4 +- backend/models/Entry.js | 4 +- backend/models/People.js | 4 +- backend/routes/entry.routes.js | 1 + backend/routes/maintenance.routes.js | 6 +++ backend/services/maintenanceService.js | 41 ++++++++++++++++++-- backend/services/peopleService.js | 22 ++++++++++- docs-vault/Changelog.md | 32 +++++++++++++++ docs-vault/Models.md | 3 ++ docs-vault/Stores.md | 31 ++++++++++++++- 13 files changed, 199 insertions(+), 10 deletions(-) diff --git a/backend/config/dataInitializer.js b/backend/config/dataInitializer.js index 30a1756..cfe2e6f 100644 --- a/backend/config/dataInitializer.js +++ b/backend/config/dataInitializer.js @@ -1,12 +1,14 @@ const { Sequelize } = require("sequelize"); const sequelize = require("../config/database"); const Collection = require("../models/Collection"); +const Entry = require("../models/Entry"); const Genre = require("../models/Genre"); const Media = require("../models/Media"); async function initializeData() { initializeGenres(); + //markEntriesRequireCreditsSync(); // migrateAccuracyField(); } @@ -31,6 +33,20 @@ async function initializeData() { // console.log(collections); // } +async function markEntriesRequireCreditsSync() { + try { + const [affectedCount] = await Entry.update( + { entry_sync_status: 'RequireCreditsSync' }, + { where: { entry_sync_status: null } } + ); + if (affectedCount > 0) { + console.log(`Marked ${affectedCount} entries as RequireCreditsSync`); + } + } catch (error) { + console.error('Error marking entries for credits sync:', error); + } +} + async function initializeGenres() { try { // * data to insert: @@ -84,8 +100,8 @@ async function initializeGenres() { module.exports = { initializeData, - initializeGenres, + markEntriesRequireCreditsSync, } // async function migrateAccuracyField() { diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js index 95a9a86..a2a761f 100644 --- a/backend/controllers/entryController.js +++ b/backend/controllers/entryController.js @@ -163,6 +163,39 @@ class EntryController { if (!data) return res.status(500).json({ message: 'Failed to fetch upcoming data' }); res.status(200).json(data); }); + + // * GET - TMDB PREVIEW (fetch details without saving to library) + getTmdbPreview = asyncWrapper(async (req, res) => { + const { type, tmdbId } = req.params; + const is_tvserie = type === 'tv'; + const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie); + if (!data) return res.status(404).json({ message: 'Entry not found on TMDB' }); + + // Normalize to a shape similar to our Entry model + const preview = { + tmdb_id: data.id, + title: data.title || data.name, + original_title: data.original_title || data.original_name || null, + release_date: data.release_date || data.first_air_date || null, + runtime: data.runtime || (data.episode_run_time?.[0]) || null, + storyline: data.overview || null, + country: data.origin_country?.[0] || data.production_countries?.[0]?.iso_3166_1 || null, + is_tvseries: is_tvserie, + status: data.status || null, + poster_path: data.poster_path || null, + backdrop_path: data.backdrop_path || null, + vote_average: data.vote_average || null, + genres: data.genres || [], + tagline: data.tagline || null, + number_of_seasons: data.number_of_seasons || null, + number_of_episodes: data.number_of_episodes || null, + networks: data.networks || [], + homepage: data.homepage || null, + imdb_id: data.imdb_id || data.external_ids?.imdb_id || null, + }; + + res.status(200).json(preview); + }); } module.exports = new EntryController(); diff --git a/backend/controllers/maintenanceController.js b/backend/controllers/maintenanceController.js index 136ee4e..88dff6c 100644 --- a/backend/controllers/maintenanceController.js +++ b/backend/controllers/maintenanceController.js @@ -35,6 +35,16 @@ class MaintenanceController { return res.status(200).json(deleted); } + async getOrphanPeople(req, res) { + const result = await _maintenanceService.deleteOrphanPeople(true); + return res.status(200).json(result); + } + + async deleteOrphanPeople(req, res) { + const result = await _maintenanceService.deleteOrphanPeople(); + return res.status(200).json(result); + } + } module.exports = new MaintenanceController(); diff --git a/backend/controllers/peopleController.js b/backend/controllers/peopleController.js index f3bd01b..ffde287 100644 --- a/backend/controllers/peopleController.js +++ b/backend/controllers/peopleController.js @@ -50,8 +50,8 @@ class PeopleController { } async fetchAndSavePersonByTmdbId(req, res) { - const { tmdb_id } = req.body; - const person = await _peopleService.fetchAndSavePersonByTmdbId(tmdb_id); + const { tmdb_id, pinned } = req.body; + const person = await _peopleService.fetchAndSavePersonByTmdbId(tmdb_id, { pinned: !!pinned }); res.status(201).json(person); } diff --git a/backend/models/Entry.js b/backend/models/Entry.js index fbacfa2..b3ad1a2 100644 --- a/backend/models/Entry.js +++ b/backend/models/Entry.js @@ -39,7 +39,9 @@ const Entry = sequelize.define("entry", date_last_seen: { type: DataTypes.DATEONLY, field: 'date_last_seen' }, last_fetch: { type: DataTypes.DATEONLY }, + + entry_sync_status: { type: DataTypes.STRING(50), field: 'entry_sync_status', allowNull: true }, } ); -module.exports = Entry; \ No newline at end of file +module.exports = Entry; diff --git a/backend/models/People.js b/backend/models/People.js index 33426cf..c6781da 100644 --- a/backend/models/People.js +++ b/backend/models/People.js @@ -27,7 +27,9 @@ const People = sequelize.define("peoples", last_fetch: { type: DataTypes.DATEONLY, field: 'last_fetch' }, profile_update: { type: DataTypes.DATEONLY, field: 'profile_update' }, fully_fetched: { type: DataTypes.BOOLEAN, defaultValue: false }, + favorite: { type: DataTypes.BOOLEAN, defaultValue: false }, + pinned: { type: DataTypes.BOOLEAN, defaultValue: false }, } ); -module.exports = People; \ No newline at end of file +module.exports = People; diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index 9b93051..0b417bf 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -17,6 +17,7 @@ entryRouter.get('/tmdb/popular/:type', entryController.getTmdbPopular); entryRouter.get('/tmdb/top-rated/:type', entryController.getTmdbTopRated); entryRouter.get('/tmdb/upcoming/movie', entryController.getTmdbUpcoming); entryRouter.get('/tmdb/search', entryController.getTmdbSearch); +entryRouter.get('/tmdb/preview/:type/:tmdbId', entryController.getTmdbPreview); entryRouter.get('/sync-series', entryController.syncSeries); diff --git a/backend/routes/maintenance.routes.js b/backend/routes/maintenance.routes.js index c7eb12e..ea9296e 100644 --- a/backend/routes/maintenance.routes.js +++ b/backend/routes/maintenance.routes.js @@ -16,4 +16,10 @@ maintenanceRouter.delete('/orphan-files', maintenanceController.deleteOrpanFiles // * DELETE - Missing files maintenanceRouter.delete('/orphan-media-records', maintenanceController.deleteOrphanMediaRecords); +// * GET - Orphan people (dry run) +maintenanceRouter.get('/orphan-people', maintenanceController.getOrphanPeople); + +// * DELETE - Orphan people +maintenanceRouter.delete('/orphan-people', maintenanceController.deleteOrphanPeople); + module.exports = maintenanceRouter; diff --git a/backend/services/maintenanceService.js b/backend/services/maintenanceService.js index 1423669..02f7591 100644 --- a/backend/services/maintenanceService.js +++ b/backend/services/maintenanceService.js @@ -3,6 +3,8 @@ const fsPromises = require('fs').promises; const fs = require('fs'); const Media = require("../models/Media"); +const People = require("../models/People"); +const Credit = require("../models/Credit"); const { logToFile } = require('./logService'); const configService = require('./configService'); @@ -18,9 +20,9 @@ class MaintenanceService { return MaintenanceService.instance; } - /** + /** * Delete orphan media records from database, - * these are media records that exist in the database + * these are media records that exist in the database * but do not have a file in the `user data folder`. * @param {boolean} [dry=false] - if true only return the count of the files that are getting deleted, default=`false` */ @@ -71,7 +73,7 @@ class MaintenanceService { return removed; } - /** + /** * Delete orphan files from media folder data, * orphan files are files that exist in the `folder data` * but do not have an instance in the database @@ -142,6 +144,39 @@ class MaintenanceService { return removed; } + /** + * Delete orphan people from the database. + * Orphan people are those not linked to any entry via credits + * AND not manually pinned. + * @param {boolean} [dry=false] - if true only return the count + */ + async deleteOrphanPeople(dry = false) { + const { Sequelize } = require('sequelize'); + + // Find all people who have no credits and are not pinned + const allPeople = await People.findAll({ + include: [{ + model: Credit, + as: 'roles', + required: false, + }], + }); + + const orphans = allPeople.filter(p => (!p.roles || p.roles.length === 0) && !p.pinned); + + if (!dry) { + for (const person of orphans) { + await person.destroy(); + } + } + + const count = orphans.length; + if (dry) logToFile(`Run a dry orphan people check, found: ${count}`); + else logToFile(`Run orphan people cleanup, deleted: ${count}`); + + return { count }; + } + } module.exports = new MaintenanceService(); diff --git a/backend/services/peopleService.js b/backend/services/peopleService.js index ab56ca8..f629faa 100644 --- a/backend/services/peopleService.js +++ b/backend/services/peopleService.js @@ -2,6 +2,7 @@ const People = require("../models/People"); const Credit = require("../models/Credit"); const Entry = require("../models/Entry"); const Media = require("../models/Media"); +const { Op } = require("sequelize"); const { fetchPersonDetails: fetchPersonData } = require("./tmdbService"); const mediaDownloaderService = require("./mediaDownloaderService"); const { logToFile } = require("./logService"); @@ -92,6 +93,20 @@ class PeopleService { return person; } + async searchPeople(query) { + const people = await People.findAll({ + where: { + name: { [Op.like]: `%${query}%` } + }, + order: [["popularity", "DESC"]], + limit: 20, + include: [ + { model: Media, as: 'medias' } + ] + }); + return people; + } + async createPerson(personData) { try { const existingPerson = await People.findOne({ @@ -160,7 +175,7 @@ class PeopleService { return { success: true, message: `Person with ID ${id} was deleted` }; } - async fetchAndSavePersonByTmdbId(tmdbId) { + async fetchAndSavePersonByTmdbId(tmdbId, options = {}) { if (!tmdbId) { throw new BadRequestError("TMDB ID is required"); } @@ -169,6 +184,10 @@ class PeopleService { let person = await this.getPersonByTmdbId(tmdbId); if (person) { + // If manually added (pinned), mark it + if (options.pinned && !person.pinned) { + await person.update({ pinned: true }); + } // If person exists but hasn't been fully fetched, we'll update it if (!person.fully_fetched) { const personData = await fetchPersonData(tmdbId); @@ -199,6 +218,7 @@ class PeopleService { ...personData, fully_fetched: true, last_fetch: new Date(), + pinned: !!options.pinned, }); // Download profile image if available diff --git a/docs-vault/Changelog.md b/docs-vault/Changelog.md index aa72255..f0f0c40 100644 --- a/docs-vault/Changelog.md +++ b/docs-vault/Changelog.md @@ -45,3 +45,35 @@ All project milestones. See also `changes.md` in project root. - Created [[Components#Dialogs|MarkSeasonWatchedDialog]] — dedicated dialog replacing the old two-step EpisodeSeenEditDialog + ConfirmDialog flow - Added **Scatter Mode**: distributes episodes across a date range with even spread and live preview - "Mark Season Watched" button on [[Pages#SeasonPage|SeasonPage]] is now always visible + +--- + +## Milestone 002 + +### Backend + +- Added `favorite` and `pinned` boolean fields to [[Models#People|People]] model +- Added `entry_sync_status` field to [[Models#Entry|Entry]] model +- Added `searchPeople` method to [[Services|PeopleService]] for local DB search by name +- `fetchAndSavePersonByTmdbId` now accepts `options.pinned` for manual person adds +- Added orphan people cleanup to [[Services|MaintenanceService]]: finds people with no credits and not pinned +- Added `GET /maintenance/orphan-people` and `DELETE /maintenance/orphan-people` routes +- Added `markEntriesRequireCreditsSync()` to dataInitializer — marks entries needing credit sync + +### Frontend + +- [[Pages#SeasonPage|SeasonPage]]: Seen button always clickable (supports multiple seen records); shows seen dates with tooltip; improved mobile responsive layout +- [[Components|EntryCard]]: Quick actions dropdown menu (Favorite, Hide, Delete, Remove from collection); non-library entries now add to library + navigate instead of opening dialog +- [[Collections|CollectionDetailsPage]]: Remove entry from collection via quick actions menu +- [[People|PersonDetailsPage]]: Error handling for missing persons; favorite toggle button +- [[People|PeoplePage]]: Debounced search, Local DB toggle, All/Favorite filter +- [[Library|LibraryPage]]: Persistent filter/search/sort state via Zustand store (`useLibraryFiltersStore`) +- Added `useUpdatePerson`, `useSearchLocalPeople`, `useRemoveEntryFromCollection` [[Hooks|hooks]] +- Added `update`, `search` methods to [[API Clients|people.ts]] +- Added orphan people endpoints to [[API Clients|maintenance.ts]] +- [[Components|EntryCard]]: Moved quick actions to top-right icon button; added all Entry Details page actions (Mark watched, Rate, Watch History, Add to collection, Refresh, Manage media, Settings) with lazy-loaded dialogs +- [[Collections|CollectionDetailsPage]]: Added sort toolbar (Order, Year, Title, Rating) with asc/desc toggle +- **Backend**: Added `GET /entries/tmdb/preview/:type/:tmdbId` — TMDB preview endpoint (no library save) +- Created [[Pages#TmdbPreviewPage|TmdbPreviewPage]] — shows TMDB entry details with "Add to Library" button; TV series shows season/episode count +- [[Components|EntryCard]]: Non-library entries now navigate to TMDB preview page instead of auto-adding to library +- Added `TmdbPreview` type, `previewTmdb` API method, `useTmdbPreview` [[Hooks|hook]] diff --git a/docs-vault/Models.md b/docs-vault/Models.md index 16c508e..814abeb 100644 --- a/docs-vault/Models.md +++ b/docs-vault/Models.md @@ -52,6 +52,7 @@ The core model — represents a movie or TV series. | `date_first_seen` | DATEONLY | | | `date_last_seen` | DATEONLY | | | `last_fetch` | DATEONLY | Used by [[Services#Lazy Refresh\|lazy refresh]] | +| `entry_sync_status` | STRING(50) | Nullable. e.g. `"RequireCreditsSync"` | **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) @@ -258,6 +259,8 @@ See [[People]]. | `last_fetch` | DATEONLY | For lazy-fetch | | `profile_update` | DATEONLY | | | `fully_fetched` | BOOLEAN | Default `false` — triggers TMDB fetch when `false` | +| `favorite` | BOOLEAN | Default `false` — user-favorited person | +| `pinned` | BOOLEAN | Default `false` — manually added, excluded from orphan cleanup | --- diff --git a/docs-vault/Stores.md b/docs-vault/Stores.md index f75fe76..1f236bc 100644 --- a/docs-vault/Stores.md +++ b/docs-vault/Stores.md @@ -11,7 +11,7 @@ aliases: # Stores -Zustand stores in `react_frontend/src/stores/`. Two stores managing client-side state. +Zustand stores in `react_frontend/src/stores/`. Three stores managing client-side state. --- @@ -96,3 +96,32 @@ Uses Zustand `persist` middleware: - Storage key: `showy-theme` - Stored in `localStorage` - On change: toggles `dark`/`light` class on `document.documentElement` + +--- + +## useLibraryFiltersStore + +> [!info] File: `stores/useLibraryFiltersStore.ts` + +Persists [[Library|LibraryPage]] filter/search/sort state across navigation so filters survive when navigating to entry details and back. + +### State + +| Field | Type | Description | +|---|---|---| +| `activeTab` | `FilterTab` | `'all' \| 'movies' \| 'series' \| 'watchlist'` | +| `search` | `string` | Search query | +| `sortField` | `SortField` | `'title' \| 'date_added' \| 'release_date' \| 'rating'` | +| `sortDir` | `SortDir` | `'asc' \| 'desc'` | +| `filters` | `Filters` | `{ genre: string; status: string; year: string }` | + +### Actions + +| Action | Description | +|---|---| +| `setActiveTab(tab)` | Set active tab filter | +| `setSearch(query)` | Set search query | +| `setSortField(field)` | Set sort field | +| `setSortDir(dir)` | Set sort direction | +| `setFilters(filters)` | Set genre/status/year filters | +| `clearFilters()` | Reset all filters to defaults | From 02cdcf733d466ba25d61da4ea9e294375dd14dbc Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Mon, 27 Apr 2026 04:03:21 +0100 Subject: [PATCH 2/2] feat(frontend): navigate non-library entries to TMDB preview page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add TmdbPreviewPage showing TMDB details without adding to library - Display backdrop, poster, title, tagline, genres, rating, storyline - Show season/episode count for TV series - Add "Add to Library" button that creates entry then redirects to details page - Show "Already in Library — View" if entry exists in DB - Add /entry/tmdb/:type/:tmdbId route in router.tsx - Add TmdbPreview type, entriesApi.previewTmdb(), and useTmdbPreview() hook - Update EntryCard to navigate to preview page instead of auto-adding Co-authored-by: Copilot --- react_frontend/src/api/entries.ts | 5 +- react_frontend/src/api/maintenance.ts | 10 + react_frontend/src/api/people.ts | 10 +- react_frontend/src/api/seasons.ts | 4 +- .../src/components/entries/EntryCard.tsx | 361 ++++++++++++------ .../components/entries/EntryLibraryGrid.tsx | 6 +- react_frontend/src/hooks/useCollections.ts | 17 + react_frontend/src/hooks/useEntries.ts | 10 + react_frontend/src/hooks/usePeople.ts | 27 +- .../src/pages/CollectionDetailsPage.tsx | 89 ++++- react_frontend/src/pages/LibraryPage.tsx | 45 +-- react_frontend/src/pages/PeoplePage.tsx | 153 ++++++-- .../src/pages/PersonDetailsPage.tsx | 37 +- react_frontend/src/pages/SeasonPage.tsx | 68 +++- react_frontend/src/pages/TmdbPreviewPage.tsx | 213 +++++++++++ react_frontend/src/router.tsx | 13 + .../src/stores/useLibraryFiltersStore.ts | 61 +++ react_frontend/src/types/index.ts | 24 ++ 18 files changed, 949 insertions(+), 204 deletions(-) create mode 100644 react_frontend/src/pages/TmdbPreviewPage.tsx create mode 100644 react_frontend/src/stores/useLibraryFiltersStore.ts diff --git a/react_frontend/src/api/entries.ts b/react_frontend/src/api/entries.ts index ce2a99e..73a5c62 100644 --- a/react_frontend/src/api/entries.ts +++ b/react_frontend/src/api/entries.ts @@ -1,6 +1,6 @@ import { api } from '@/lib/api'; import { normalizeEntry } from '@/lib/normalizers'; -import type { Entry } from '@/types'; +import type { Entry, TmdbPreview } from '@/types'; export const entriesApi = { getAll: () => @@ -44,6 +44,9 @@ export const entriesApi = { syncSeries: () => api.get('/entries/sync-series').then((r) => r.data), + previewTmdb: (tmdbId: number, type: 'movie' | 'tv') => + api.get(`/entries/tmdb/preview/${type}/${tmdbId}`).then((r) => r.data), + uploadMedia: (id: number, formData: FormData) => api .post(`/entries/${id}/media`, formData, { diff --git a/react_frontend/src/api/maintenance.ts b/react_frontend/src/api/maintenance.ts index a269925..05e84c1 100644 --- a/react_frontend/src/api/maintenance.ts +++ b/react_frontend/src/api/maintenance.ts @@ -7,6 +7,10 @@ export interface OrphanResult { stills: number; } +export interface OrphanPeopleResult { + count: number; +} + export const maintenanceApi = { scanOrphanFiles: () => api.get('/maintenance/orphan-files').then((r) => r.data), @@ -19,4 +23,10 @@ export const maintenanceApi = { deleteOrphanMediaRecords: () => api.delete('/maintenance/orphan-media-records').then((r) => r.data), + + scanOrphanPeople: () => + api.get('/maintenance/orphan-people').then((r) => r.data), + + deleteOrphanPeople: () => + api.delete('/maintenance/orphan-people').then((r) => r.data), }; diff --git a/react_frontend/src/api/people.ts b/react_frontend/src/api/people.ts index 5f33bf2..b23f84a 100644 --- a/react_frontend/src/api/people.ts +++ b/react_frontend/src/api/people.ts @@ -33,6 +33,12 @@ export const peopleApi = { getTmdbFilmography: (id: number) => api.get(`/people/${id}/tmdb-filmography`).then((r) => r.data), - fetchByTmdbId: (tmdb_id: number) => - api.post('/people/fetch', { tmdb_id }).then((r) => r.data), + fetchByTmdbId: (tmdb_id: number, pinned = false) => + api.post('/people/fetch', { tmdb_id, pinned }).then((r) => r.data), + + update: (id: number, data: Partial) => + api.put(`/people/${id}`, data).then((r) => r.data), + + search: (query: string) => + api.get('/people/search', { params: { query } }).then((r) => r.data), }; diff --git a/react_frontend/src/api/seasons.ts b/react_frontend/src/api/seasons.ts index 231c1b2..287520e 100644 --- a/react_frontend/src/api/seasons.ts +++ b/react_frontend/src/api/seasons.ts @@ -1,5 +1,5 @@ import { api } from '@/lib/api'; -import type { Season } from '@/types'; +import type { Season, Episode } from '@/types'; export const seasonsApi = { getAll: () => api.get('/seasons').then((r) => r.data), @@ -8,7 +8,7 @@ export const seasonsApi = { api.get(`/seasons/${id}`).then((r) => r.data), getEpisodes: (id: number) => - api.get(`/seasons/${id}/episodes`).then((r) => r.data), + api.get(`/seasons/${id}/episodes`).then((r) => r.data), create: (data: Partial) => api.post('/seasons', data).then((r) => r.data), diff --git a/react_frontend/src/components/entries/EntryCard.tsx b/react_frontend/src/components/entries/EntryCard.tsx index d9c63db..6b1d814 100644 --- a/react_frontend/src/components/entries/EntryCard.tsx +++ b/react_frontend/src/components/entries/EntryCard.tsx @@ -1,32 +1,56 @@ import { useState } from 'react'; -import { Link } from 'react-router-dom'; -import { Plus, Trash2, Star, Loader2, Calendar, Clock } from 'lucide-react'; +import { Link, useNavigate } from 'react-router-dom'; +import { + Plus, Star, Loader2, Heart, EyeOff, Trash2, MoreHorizontal, X, + Eye, History, FolderPlus, RefreshCw, ImageIcon, Settings, +} from 'lucide-react'; import { Badge } from '@/components/ui/badge'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { - Dialog, - DialogContent, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog'; + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; import { getPosterUrl, getYear, formatRuntime } from '@/lib/media-utils'; -import { useCreateEntry, useDeleteEntry } from '@/hooks/useEntries'; +import { useCreateEntry, useDeleteEntry, useUpdateEntry, useRefreshEntry, useEntrySeasons } from '@/hooks/useEntries'; +import { useEntrySeenByEntry, useDeleteEntrySeen } from '@/hooks/useEntrySeen'; import { useLibraryStore } from '@/stores/useLibraryStore'; import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog'; +import { EntrySeenDialog } from '@/components/dialogs/EntrySeenDialog'; +import { RatingDialog } from '@/components/dialogs/RatingDialog'; +import { MovieWatchHistoryDialog } from '@/components/dialogs/MovieWatchHistoryDialog'; +import { AddEntryToCollectionDialog } from '@/components/dialogs/AddEntryToCollectionDialog'; +import { EntryMediaDialog } from '@/components/dialogs/EntryMediaDialog'; +import { EntrySettingsDialog } from '@/components/dialogs/EntrySettingsDialog'; import type { Entry, TmdbEntry } from '@/types'; interface EntryCardProps { entry?: Entry; tmdbEntry?: TmdbEntry; showTypeBadge?: boolean; + /** When inside a collection, provide the collection ID to show "Remove from collection" action */ + collectionId?: number; + /** Callback to remove entry from collection */ + onRemoveFromCollection?: (entryId: number) => void; } -export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) { +export function EntryCard({ entry, tmdbEntry, showTypeBadge, collectionId, onRemoveFromCollection }: EntryCardProps) { const [showConfirm, setShowConfirm] = useState(false); - const [showDetailDialog, setShowDetailDialog] = useState(false); + const [showRemoveCollectionConfirm, setShowRemoveCollectionConfirm] = useState(false); + const [showSeenDialog, setShowSeenDialog] = useState(false); + const [showRatingDialog, setShowRatingDialog] = useState(false); + const [showWatchHistoryDialog, setShowWatchHistoryDialog] = useState(false); + const [showCollectionDialog, setShowCollectionDialog] = useState(false); + const [showMediaDialog, setShowMediaDialog] = useState(false); + const [showSettingsDialog, setShowSettingsDialog] = useState(false); + const navigate = useNavigate(); const createEntry = useCreateEntry(); const deleteEntry = useDeleteEntry(); + const updateEntry = useUpdateEntry(); + const refreshEntry = useRefreshEntry(); const libraryEntry = useLibraryStore((s) => { if (entry?.isInLibrary) return entry; if (tmdbEntry) { @@ -67,19 +91,18 @@ export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) { const entryLink = displayEntry ? `/entry/${displayEntry.id}` - : undefined; + : tmdbEntry + ? `/entry/tmdb/${isTv ? 'tv' : 'movie'}/${tmdbEntry.id}` + : undefined; const handleAdd = (e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation(); if (!tmdbEntry) return; - createEntry.mutate({ tmdb_id: tmdbEntry.id, is_tvserie: isTv }); - }; - - const handleRemove = (e: React.MouseEvent) => { - e.preventDefault(); - e.stopPropagation(); - setShowConfirm(true); + createEntry.mutate( + { tmdb_id: tmdbEntry.id, is_tvserie: isTv }, + { onSuccess: (newEntry) => navigate(`/entry/${newEntry.id}`) } + ); }; const confirmRemove = () => { @@ -90,10 +113,22 @@ export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) { } }; + const toggleFavorite = () => { + if (libraryEntry) { + updateEntry.mutate({ id: libraryEntry.id, data: { favorit: !libraryEntry.favorit } }); + } + }; + + const toggleHidden = () => { + if (libraryEntry) { + updateEntry.mutate({ id: libraryEntry.id, data: { hidden: !libraryEntry.hidden } }); + } + }; + const card = (
{/* Poster */} -
+
{title} )} - {/* Favorite indicator */} + {/* Favorite indicator – hidden on hover when actions button shows */} {libraryEntry?.favorit && ( - + + )} + + {/* Quick actions button – top right, shown on hover */} + {isInLibrary && ( +
+ + + + + e.stopPropagation()}> + {/* Watch & Rate */} + { e.stopPropagation(); setShowSeenDialog(true); }}> + + Mark as watched + + { e.stopPropagation(); setShowRatingDialog(true); }}> + + Rate this + + {!isTv && ( + { e.stopPropagation(); setShowWatchHistoryDialog(true); }}> + + Watch History + + )} + + {/* Organize */} + { e.stopPropagation(); toggleFavorite(); }}> + + {libraryEntry?.favorit ? 'Unfavorite' : 'Favorite'} + + { e.stopPropagation(); setShowCollectionDialog(true); }}> + + Add to collection + + { e.stopPropagation(); toggleHidden(); }}> + + {libraryEntry?.hidden ? 'Unhide' : 'Hide'} + + + {/* Manage */} + { e.stopPropagation(); refreshEntry.mutate(libraryEntry!.id); }} + disabled={refreshEntry.isPending} + > + + {refreshEntry.isPending ? 'Refreshing...' : 'Refresh details'} + + { e.stopPropagation(); setShowMediaDialog(true); }}> + + Manage media + + { e.stopPropagation(); setShowSettingsDialog(true); }}> + + Settings + + {/* Collection removal */} + {collectionId && onRemoveFromCollection && ( + <> + + { e.stopPropagation(); setShowRemoveCollectionConfirm(true); }} + className="text-destructive focus:text-destructive" + > + + Remove from collection + + + )} + + {/* Danger */} + { e.stopPropagation(); setShowConfirm(true); }} + className="text-destructive focus:text-destructive" + > + + Delete entry + + + +
)} {/* Entry type pill */} @@ -124,7 +247,7 @@ export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) { )} {/* Hover overlay */} -
+

{title} @@ -140,24 +263,9 @@ export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) { {runtime && {runtime}}

- {/* Actions */} -
- {isInLibrary ? ( - - ) : tmdbEntry ? ( + {/* Add to Library – only for non-library entries */} + {!isInLibrary && tmdbEntry && ( +
+
+ )} +
+
+
+
+ );
@@ -184,87 +297,119 @@ export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) { {entryLink ? ( {card} ) : ( -
setShowDetailDialog(true)}> - {card} -
+ card )} - {/* Details dialog for non-library entries */} - {!entryLink && tmdbEntry && ( - - - - {title} - -
- {title} -
-
- {year && ( - - - {year} - - )} - {isTv ? ( - TV Series - ) : ( - Movie - )} -
- {tmdbEntry.vote_average > 0 && ( -
- - {tmdbEntry.vote_average.toFixed(1)}/10 -
- )} - {tmdbEntry.overview && ( -

- {tmdbEntry.overview} -

- )} - -
-
-
-
+ {collectionId && onRemoveFromCollection && ( + { + if (libraryEntry) onRemoveFromCollection(libraryEntry.id); + setShowRemoveCollectionConfirm(false); + }} + variant="destructive" + /> + )} + {libraryEntry && showSeenDialog && ( + + )} + {libraryEntry && showRatingDialog && ( + + )} + {libraryEntry && showWatchHistoryDialog && ( + + )} + {libraryEntry && showCollectionDialog && ( + + )} + {libraryEntry && showMediaDialog && ( + + )} + {libraryEntry && showSettingsDialog && ( + )} ); } +/* Lazy wrappers – only mount when dialog is open so hooks fetch on demand */ + +function LazyEntrySeenDialog({ entry, open, onOpenChange }: { + entry: Entry; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const { data: seasons = [] } = useEntrySeasons(entry.id); + return ( + + ); +} + +function LazyMovieWatchHistoryDialog({ entryId, open, onOpenChange }: { + entryId: number; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const { data: watchHistory = [] } = useEntrySeenByEntry(entryId); + const deleteEntrySeen = useDeleteEntrySeen(); + return ( + deleteEntrySeen.mutate({ id: seenId, entryId })} + /> + ); +} + export function EntryCardSkeleton() { return (
- +
); } diff --git a/react_frontend/src/components/entries/EntryLibraryGrid.tsx b/react_frontend/src/components/entries/EntryLibraryGrid.tsx index dee1ff1..9ea3655 100644 --- a/react_frontend/src/components/entries/EntryLibraryGrid.tsx +++ b/react_frontend/src/components/entries/EntryLibraryGrid.tsx @@ -7,6 +7,8 @@ interface EntryLibraryGridProps { isLoading?: boolean; hasMore?: boolean; onLoadMore?: () => void; + collectionId?: number; + onRemoveFromCollection?: (entryId: number) => void; } export function EntryLibraryGrid({ @@ -14,6 +16,8 @@ export function EntryLibraryGrid({ isLoading, hasMore, onLoadMore, + collectionId, + onRemoveFromCollection, }: EntryLibraryGridProps) { const observerRef = useRef(null); @@ -62,7 +66,7 @@ export function EntryLibraryGrid({ className="animate-card-enter" style={{ animationDelay: `${Math.min(index * 30, 300)}ms` }} > - + ))} {isLoading && diff --git a/react_frontend/src/hooks/useCollections.ts b/react_frontend/src/hooks/useCollections.ts index 51cb177..cb22eeb 100644 --- a/react_frontend/src/hooks/useCollections.ts +++ b/react_frontend/src/hooks/useCollections.ts @@ -69,3 +69,20 @@ export function useGetCollectionParts() { }, }); } + +export function useRemoveEntryFromCollection() { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: ({ collectionId, entryId }: { collectionId: number; entryId: number }) => + collectionsApi.removeEntry(collectionId, entryId), + onSuccess: (_data, { collectionId }) => { + queryClient.invalidateQueries({ queryKey: collectionKeys.detail(collectionId) }); + queryClient.invalidateQueries({ queryKey: collectionKeys.all }); + toast.success('Entry removed from collection'); + }, + onError: () => { + toast.error('Failed to remove entry from collection'); + }, + }); +} diff --git a/react_frontend/src/hooks/useEntries.ts b/react_frontend/src/hooks/useEntries.ts index eee94b5..f4113d4 100644 --- a/react_frontend/src/hooks/useEntries.ts +++ b/react_frontend/src/hooks/useEntries.ts @@ -8,6 +8,7 @@ export const entryKeys = { all: ['entries'] as const, detail: (id: number) => ['entries', id] as const, seasons: (id: number) => ['entries', id, 'seasons'] as const, + tmdbPreview: (tmdbId: number, type: string) => ['entries', 'tmdb-preview', type, tmdbId] as const, }; export function useLibrary() { @@ -153,3 +154,12 @@ export function useUploadMedia() { }, }); } + +export function useTmdbPreview(tmdbId: number, type: 'movie' | 'tv') { + return useQuery({ + queryKey: entryKeys.tmdbPreview(tmdbId, type), + queryFn: () => entriesApi.previewTmdb(tmdbId, type), + enabled: !!tmdbId, + staleTime: 10 * 60 * 1000, + }); +} diff --git a/react_frontend/src/hooks/usePeople.ts b/react_frontend/src/hooks/usePeople.ts index 69d6e0f..b74c499 100644 --- a/react_frontend/src/hooks/usePeople.ts +++ b/react_frontend/src/hooks/usePeople.ts @@ -1,4 +1,5 @@ -import { useQuery, useMutation } from '@tanstack/react-query'; +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { toast } from 'sonner'; import { peopleApi } from '@/api/people'; export const peopleKeys = { @@ -38,3 +39,27 @@ export function useFetchPersonByTmdbId() { mutationFn: (tmdb_id: number) => peopleApi.fetchByTmdbId(tmdb_id), }); } + +export function useUpdatePerson() { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: ({ id, data }: { id: number; data: Partial }) => + peopleApi.update(id, data), + onSuccess: (updatedPerson) => { + queryClient.invalidateQueries({ queryKey: peopleKeys.detail(updatedPerson.id) }); + toast.success('Person updated'); + }, + onError: () => { + toast.error('Failed to update person'); + }, + }); +} + +export function useSearchLocalPeople(query: string) { + return useQuery({ + queryKey: ['people', 'search', query], + queryFn: () => query === '*' ? peopleApi.getAll() : peopleApi.search(query), + enabled: query.length > 0, + }); +} diff --git a/react_frontend/src/pages/CollectionDetailsPage.tsx b/react_frontend/src/pages/CollectionDetailsPage.tsx index 2819088..62aedb3 100644 --- a/react_frontend/src/pages/CollectionDetailsPage.tsx +++ b/react_frontend/src/pages/CollectionDetailsPage.tsx @@ -1,6 +1,6 @@ -import { useState } from 'react'; +import { useState, useMemo } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; -import { useCollection, useDeleteCollection, useGetCollectionParts } from '@/hooks/useCollections'; +import { useCollection, useDeleteCollection, useGetCollectionParts, useRemoveEntryFromCollection } from '@/hooks/useCollections'; import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid'; import { getCollectionPosterUrl } from '@/lib/media-utils'; import { getTmdbImageUrl } from '@/lib/api'; @@ -12,10 +12,14 @@ import { DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; -import { Star, MoreVertical, Pencil, Download, Trash2 } from 'lucide-react'; +import { Star, MoreVertical, Pencil, Download, Trash2, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'; import { CollectionEditDialog } from '@/components/dialogs/CollectionEditDialog'; import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog'; import { toast } from 'sonner'; +import type { Entry } from '@/types'; + +type CollectionSortField = 'order' | 'year' | 'title' | 'rating'; +type SortDir = 'asc' | 'desc'; export function CollectionDetailsPage() { const { id } = useParams<{ id: string }>(); @@ -23,8 +27,11 @@ export function CollectionDetailsPage() { const { data: collection, isLoading, isError } = useCollection(Number(id)); const [showEditDialog, setShowEditDialog] = useState(false); const [showDeleteConfirm, setShowDeleteConfirm] = useState(false); + const [sortField, setSortField] = useState('order'); + const [sortDir, setSortDir] = useState('asc'); const deleteCollection = useDeleteCollection(); const getCollectionParts = useGetCollectionParts(); + const removeEntryFromCollection = useRemoveEntryFromCollection(); if (isLoading) { return ( @@ -33,7 +40,7 @@ export function CollectionDetailsPage() {
{Array.from({ length: 6 }).map((_, i) => ( - + ))}
@@ -55,6 +62,46 @@ export function CollectionDetailsPage() { isInLibrary: true, })); + const sortedEntries = useMemo(() => { + const sorted = [...entries].sort((a, b) => { + let cmp = 0; + switch (sortField) { + case 'order': { + const oa = (a as Entry & { UserCollectionEntry?: { order: number } }).UserCollectionEntry?.order ?? 0; + const ob = (b as Entry & { UserCollectionEntry?: { order: number } }).UserCollectionEntry?.order ?? 0; + cmp = oa - ob; + break; + } + case 'year': { + const ya = a.release_date ? new Date(a.release_date).getFullYear() : 0; + const yb = b.release_date ? new Date(b.release_date).getFullYear() : 0; + cmp = ya - yb; + break; + } + case 'title': + cmp = (a.title || '').localeCompare(b.title || ''); + break; + case 'rating': { + const ra = a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0; + const rb = b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0; + cmp = ra - rb; + break; + } + } + return sortDir === 'asc' ? cmp : -cmp; + }); + return sorted; + }, [entries, sortField, sortDir]); + + const handleSort = (field: CollectionSortField) => { + if (field === sortField) { + setSortDir((d) => (d === 'asc' ? 'desc' : 'asc')); + } else { + setSortField(field); + setSortDir(field === 'rating' ? 'desc' : 'asc'); + } + }; + const handleDelete = () => { deleteCollection.mutate(collection.id, { onSuccess: () => navigate('/collections', { replace: true }), @@ -78,7 +125,7 @@ export function CollectionDetailsPage() { ) : (
)} -
+
{/* Quick action menu - top right */}
@@ -142,8 +189,38 @@ export function CollectionDetailsPage() {
+ {/* Sort toolbar */} + {entries.length > 1 && ( +
+ + {(['order', 'year', 'title', 'rating'] as const).map((field) => ( + + ))} +
+ )} + {/* Entries grid */} - + + removeEntryFromCollection.mutate({ collectionId: collection.id, entryId }) + } + /> {/* Edit dialog */} {showEditDialog && ( diff --git a/react_frontend/src/pages/LibraryPage.tsx b/react_frontend/src/pages/LibraryPage.tsx index 3dd0473..12703ff 100644 --- a/react_frontend/src/pages/LibraryPage.tsx +++ b/react_frontend/src/pages/LibraryPage.tsx @@ -2,6 +2,8 @@ import { useState, useMemo, useCallback, useEffect, useRef } from 'react'; import { useSearchParams } from 'react-router-dom'; import { useLibrary } from '@/hooks/useEntries'; import { useLibraryEntries } from '@/stores/useLibraryStore'; +import { useLibraryFiltersStore, defaultFilters } from '@/stores/useLibraryFiltersStore'; +import type { FilterTab, SortField, SortDir, Filters } from '@/stores/useLibraryFiltersStore'; import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid'; import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Input } from '@/components/ui/input'; @@ -12,22 +14,6 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ import { Search, X, SlidersHorizontal, ArrowUpDown } from 'lucide-react'; import type { Entry } from '@/types'; -type FilterTab = 'all' | 'movies' | 'tv' | 'favorites' | 'hidden'; -type SortField = 'date_last_seen' | 'createdAt' | 'title' | 'release_date' | 'rating'; -type SortDir = 'asc' | 'desc'; - -interface Filters { - genre: string; - tmdbRatingMin: string; - tmdbRatingMax: string; - userRatingMin: string; - userRatingMax: string; - yearMin: string; - yearMax: string; -} - -const defaultFilters: Filters = { genre: '', tmdbRatingMin: '', tmdbRatingMax: '', userRatingMin: '', userRatingMax: '', yearMin: '', yearMax: '' }; - const sortLabels: Record = { date_last_seen: 'Last Watched', createdAt: 'Date Added', @@ -66,13 +52,22 @@ const PAGE_SIZE = 28; export function LibraryPage() { const { isLoading } = useLibrary(); const [searchParams, setSearchParams] = useSearchParams(); - const [activeTab, setActiveTab] = useState('all'); - const [search, setSearch] = useState(''); - const [debouncedSearch, setDebouncedSearch] = useState(''); - const [sortField, setSortField] = useState('date_last_seen'); - const [sortDir, setSortDir] = useState('desc'); - const [filters, setFilters] = useState(defaultFilters); - const [debouncedFilters, setDebouncedFilters] = useState(defaultFilters); + + // Persistent filter state from store + const activeTab = useLibraryFiltersStore((s) => s.activeTab); + const setActiveTab = useLibraryFiltersStore((s) => s.setActiveTab); + const search = useLibraryFiltersStore((s) => s.search); + const setSearch = useLibraryFiltersStore((s) => s.setSearch); + const sortField = useLibraryFiltersStore((s) => s.sortField); + const setSortField = useLibraryFiltersStore((s) => s.setSortField); + const sortDir = useLibraryFiltersStore((s) => s.sortDir); + const setSortDir = useLibraryFiltersStore((s) => s.setSortDir); + const filters = useLibraryFiltersStore((s) => s.filters); + const setFilters = useLibraryFiltersStore((s) => s.setFilters); + const clearFilters = useLibraryFiltersStore((s) => s.clearFilters); + + const [debouncedSearch, setDebouncedSearch] = useState(search); + const [debouncedFilters, setDebouncedFilters] = useState(filters); const [visibleCount, setVisibleCount] = useState(PAGE_SIZE); const filtersInitialized = useRef(false); @@ -92,7 +87,7 @@ export function LibraryPage() { // Clear URL params after applying setSearchParams({}, { replace: true }); } - }, [searchParams, setSearchParams]); + }, [searchParams, setSearchParams, setFilters]); // Debounce search useEffect(() => { @@ -181,8 +176,6 @@ export function LibraryPage() { const hasMore = visibleCount < filteredEntries.length; const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []); - const clearFilters = useCallback(() => setFilters(defaultFilters), []); - return (
diff --git a/react_frontend/src/pages/PeoplePage.tsx b/react_frontend/src/pages/PeoplePage.tsx index 3b14169..fe32ab1 100644 --- a/react_frontend/src/pages/PeoplePage.tsx +++ b/react_frontend/src/pages/PeoplePage.tsx @@ -1,26 +1,64 @@ -import { useState, useCallback, useRef, useEffect } from 'react'; +import { useState, useCallback, useRef, useEffect, useMemo } from 'react'; import { Link } from 'react-router-dom'; import { usePopularPeople, useTmdbSearchPeople } from '@/hooks/useTmdb'; +import { useSearchLocalPeople } from '@/hooks/usePeople'; import { Input } from '@/components/ui/input'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Skeleton } from '@/components/ui/skeleton'; -import { Search } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Switch } from '@/components/ui/switch'; +import { Label } from '@/components/ui/label'; +import { Search, Heart } from 'lucide-react'; import { getProfileUrl } from '@/lib/media-utils'; +type PeopleFilter = 'all' | 'favorite'; + export function PeoplePage() { const [search, setSearch] = useState(''); - const isSearching = search.length > 0; + const [debouncedSearch, setDebouncedSearch] = useState(''); + const [filter, setFilter] = useState('all'); + const [localOnly, setLocalOnly] = useState(false); + + // Debounce search input + useEffect(() => { + const timer = setTimeout(() => setDebouncedSearch(search), 400); + return () => clearTimeout(timer); + }, [search]); + + const isSearching = debouncedSearch.length > 0; const popularQuery = usePopularPeople(); - const searchQuery = useTmdbSearchPeople(search); + const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? '' : debouncedSearch); + const { data: localSearchResults = [], isLoading: localSearchLoading } = useSearchLocalPeople( + localOnly ? debouncedSearch : '' + ); - const activeQuery = isSearching ? searchQuery : popularQuery; - const people = activeQuery.data?.pages.flatMap((p) => p.results) ?? []; + // For TMDB mode, use infinite scroll queries + const activeQuery = isSearching && !localOnly ? tmdbSearchQuery : !localOnly ? popularQuery : null; + const tmdbPeople = activeQuery?.data?.pages.flatMap((p) => p.results) ?? []; + + // For local mode with no search, fetch all local people + const { data: allLocalPeople = [], isLoading: allLocalLoading } = useSearchLocalPeople( + localOnly && !isSearching ? '*' : '' + ); + + // Determine displayed people + const displayPeople = useMemo(() => { + if (localOnly) { + const people = isSearching ? localSearchResults : allLocalPeople; + if (filter === 'favorite') { + return people.filter((p: any) => p.favorite); + } + return people; + } + // TMDB mode - filter not applicable for TMDB results + return tmdbPeople; + }, [localOnly, isSearching, localSearchResults, allLocalPeople, tmdbPeople, filter]); const observerRef = useRef(null); const lastRef = useCallback( (node: HTMLDivElement | null) => { - if (activeQuery.isFetchingNextPage) return; + if (!activeQuery || activeQuery.isFetchingNextPage) return; if (observerRef.current) observerRef.current.disconnect(); observerRef.current = new IntersectionObserver((entries) => { if (entries[0].isIntersecting && activeQuery.hasNextPage) { @@ -29,28 +67,70 @@ export function PeoplePage() { }); if (node) observerRef.current.observe(node); }, - [activeQuery.isFetchingNextPage, activeQuery.hasNextPage, activeQuery.fetchNextPage] + [activeQuery?.isFetchingNextPage, activeQuery?.hasNextPage, activeQuery?.fetchNextPage] ); useEffect(() => { return () => observerRef.current?.disconnect(); }, []); + const isLoading = localOnly + ? (isSearching ? localSearchLoading : allLocalLoading) + : activeQuery?.isLoading; + return (

People

-
- - setSearch(e.target.value)} - className="pl-10" - /> + {/* Controls row */} +
+
+ + setSearch(e.target.value)} + className="pl-10" + /> +
+ + {/* Filter: All / Favorite (only in local mode) */} + {localOnly && ( +
+ + +
+ )} + + {/* Local DB toggle */} +
+ + +
- {activeQuery.isLoading ? ( + {isLoading ? (
{Array.from({ length: 24 }).map((_, i) => (
@@ -59,31 +139,40 @@ export function PeoplePage() {
))}
+ ) : displayPeople.length === 0 ? ( +
+ No people found. +
) : (
- {people.map((person, index) => ( + {displayPeople.map((person: any, index: number) => (
- - - - {person.name - .split(' ') - .map((n) => n[0]) - .join('')} - - +
+ + + + {person.name + .split(' ') + .map((n: string) => n[0]) + .join('')} + + + {person.favorite && ( + + )} +

{person.name}

diff --git a/react_frontend/src/pages/PersonDetailsPage.tsx b/react_frontend/src/pages/PersonDetailsPage.tsx index 8e0d998..cf6306e 100644 --- a/react_frontend/src/pages/PersonDetailsPage.tsx +++ b/react_frontend/src/pages/PersonDetailsPage.tsx @@ -1,6 +1,6 @@ -import { useParams } from 'react-router-dom'; +import { useParams, useNavigate } from 'react-router-dom'; import { useState } from 'react'; -import { usePerson, usePersonTmdbFilmography } from '@/hooks/usePeople'; +import { usePerson, usePersonTmdbFilmography, useUpdatePerson } from '@/hooks/usePeople'; import { useLibrary } from '@/hooks/useEntries'; import { useLibraryStore } from '@/stores/useLibraryStore'; import { Skeleton } from '@/components/ui/skeleton'; @@ -9,19 +9,35 @@ import { Separator } from '@/components/ui/separator'; import { Button } from '@/components/ui/button'; import { EntryCard } from '@/components/entries/EntryCard'; import { getProfileUrl, formatDate } from '@/lib/media-utils'; -import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { ChevronLeft, ChevronRight, Heart } from 'lucide-react'; import type { TmdbEntry } from '@/types'; import type { TmdbFilmographyItem } from '@/api/people'; export function PersonDetailsPage() { const { id } = useParams<{ id: string }>(); const personId = parseInt(id!, 10); - const { data: person, isLoading } = usePerson(personId); + const navigate = useNavigate(); + const { data: person, isLoading, isError } = usePerson(personId); const { data: tmdbFilmography, isLoading: tmdbLoading } = usePersonTmdbFilmography(personId); + const updatePerson = useUpdatePerson(); useLibrary(); const libraryMap = useLibraryStore((s) => s.entries); const libraryLoaded = useLibraryStore((s) => s.isLoaded); + if (isError) { + return ( +
+

Person not found

+

+ This person could not be loaded. They may not exist in the database. +

+ +
+ ); + } + if (isLoading || !person) { return (
@@ -47,7 +63,18 @@ export function PersonDetailsPage() {
-

{person.name}

+
+

{person.name}

+ +
{person.known_for_department && {person.known_for_department}} {person.birthday && (<>•Born: {formatDate(person.birthday)})} diff --git a/react_frontend/src/pages/SeasonPage.tsx b/react_frontend/src/pages/SeasonPage.tsx index 4f62b86..30d8d3f 100644 --- a/react_frontend/src/pages/SeasonPage.tsx +++ b/react_frontend/src/pages/SeasonPage.tsx @@ -9,8 +9,9 @@ import { Skeleton } from '@/components/ui/skeleton'; import { Progress } from '@/components/ui/progress'; import { Button } from '@/components/ui/button'; import { Eye, CheckCircle2, ListChecks } from 'lucide-react'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { getTmdbPosterUrl, getYear, formatDate } from '@/lib/media-utils'; -import type { Episode } from '@/types'; +import type { Episode, EpisodeSeen } from '@/types'; export function SeasonPage() { const { entryId, seasonId } = useParams<{ @@ -39,7 +40,7 @@ export function SeasonPage() { } const watchedCount = episodes.filter( - (ep) => + (ep: Episode) => ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0) ).length; @@ -61,20 +62,20 @@ export function SeasonPage() {
{/* Header */} -
+
{season.name}
-
-

{season.name}

+
+

{season.name}

{/* Mark Season as Watched — top right */} diff --git a/react_frontend/src/pages/TmdbPreviewPage.tsx b/react_frontend/src/pages/TmdbPreviewPage.tsx new file mode 100644 index 0000000..8eb9a04 --- /dev/null +++ b/react_frontend/src/pages/TmdbPreviewPage.tsx @@ -0,0 +1,213 @@ +import { useParams, useNavigate } from 'react-router-dom'; +import { useTmdbPreview, useCreateEntry } from '@/hooks/useEntries'; +import { useLibraryStore } from '@/stores/useLibraryStore'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Separator } from '@/components/ui/separator'; +import { Star, Plus, Loader2, ExternalLink, Tv, Film } from 'lucide-react'; +import { EntryDetailsSkeleton } from '@/components/skeletons/PageSkeletons'; +import { getYear, formatRuntime } from '@/lib/media-utils'; + +const TMDB_IMG = 'https://image.tmdb.org/t/p'; + +export function TmdbPreviewPage() { + const { type, tmdbId } = useParams<{ type: string; tmdbId: string }>(); + const navigate = useNavigate(); + const tmdbIdNum = parseInt(tmdbId!, 10); + const mediaType = type as 'movie' | 'tv'; + + const { data: preview, isLoading, isError } = useTmdbPreview(tmdbIdNum, mediaType); + const createEntry = useCreateEntry(); + + // Check if already in library + const libraryEntry = useLibraryStore((s) => { + for (const e of s.entries.values()) { + if (e.entryIds?.tmdb_id === tmdbIdNum) return e; + } + return null; + }); + + if (isLoading || !preview) { + return ; + } + + if (isError) { + return ( +
+

Could not load entry from TMDB.

+ +
+ ); + } + + const backdrop = preview.backdrop_path ? `${TMDB_IMG}/w1280${preview.backdrop_path}` : null; + const poster = preview.poster_path + ? `${TMDB_IMG}/w500${preview.poster_path}` + : '/images/default-poster.png'; + + const handleAddToLibrary = () => { + createEntry.mutate( + { tmdb_id: preview.tmdb_id, is_tvserie: preview.is_tvseries }, + { onSuccess: (newEntry) => navigate(`/entry/${newEntry.id}`, { replace: true }) } + ); + }; + + return ( +
+ {/* Backdrop banner */} +
+ {backdrop ? ( + + ) : ( +
+ )} +
+
+ + {/* Main content */} +
+ {/* Add to Library button — top right */} +
+ {libraryEntry ? ( + + ) : ( + + )} +
+ + {/* Two-column header: poster | info */} +
+ {/* LEFT: Poster */} +
+ {preview.title} + {/* External links */} +
+ {preview.tmdb_id && ( + + + TMDB + + )} + {preview.imdb_id && ( + + + IMDb + + )} +
+
+ + {/* RIGHT: Info */} +
+ {/* Title */} +
+

{preview.title}

+ {preview.tagline && ( +

{preview.tagline}

+ )} +
+ + {/* Meta */} +
+ + {preview.is_tvseries ? : } + {preview.is_tvseries ? 'TV Series' : 'Movie'} + + {preview.release_date && ( + <> + • + {getYear(preview.release_date)} + + )} + {preview.is_tvseries && preview.status && ( + <> + • + {preview.status} + + )} + {preview.runtime && !preview.is_tvseries && ( + <> + • + {formatRuntime(preview.runtime)} + + )} +
+ + {/* TV series season count */} + {preview.is_tvseries && preview.number_of_seasons != null && ( +
+ + {preview.number_of_seasons} {preview.number_of_seasons === 1 ? 'Season' : 'Seasons'} + + {preview.number_of_episodes != null && ( + + ({preview.number_of_episodes} episodes) + + )} +
+ )} + + {/* Genres */} + {preview.genres.length > 0 && ( +
+ {preview.genres.map((g) => ( + + {g.name} + + ))} +
+ )} + + {/* Rating */} + {preview.vote_average != null && preview.vote_average > 0 && ( +
+ + + TMDB: + {preview.vote_average.toFixed(1)}/10 + +
+ )} + + {/* Storyline */} + {preview.storyline && ( + <> + +

+ {preview.storyline} +

+ + )} +
+
+
+
+ ); +} diff --git a/react_frontend/src/router.tsx b/react_frontend/src/router.tsx index 356f8f9..20c1ee9 100644 --- a/react_frontend/src/router.tsx +++ b/react_frontend/src/router.tsx @@ -52,6 +52,11 @@ const EntryDetailsPage = lazy(() => default: m.EntryDetailsPage, })) ); +const TmdbPreviewPage = lazy(() => + import('@/pages/TmdbPreviewPage').then((m) => ({ + default: m.TmdbPreviewPage, + })) +); const SeasonPage = lazy(() => import('@/pages/SeasonPage').then((m) => ({ default: m.SeasonPage })) ); @@ -169,6 +174,14 @@ export const router = createBrowserRouter([ ), }, + { + path: '/entry/tmdb/:type/:tmdbId', + element: ( + }> + + + ), + }, { path: '/entry/:id', element: ( diff --git a/react_frontend/src/stores/useLibraryFiltersStore.ts b/react_frontend/src/stores/useLibraryFiltersStore.ts new file mode 100644 index 0000000..31bca21 --- /dev/null +++ b/react_frontend/src/stores/useLibraryFiltersStore.ts @@ -0,0 +1,61 @@ +import { create } from 'zustand'; + +type FilterTab = 'all' | 'movies' | 'tv' | 'favorites' | 'hidden'; +type SortField = 'date_last_seen' | 'createdAt' | 'title' | 'release_date' | 'rating'; +type SortDir = 'asc' | 'desc'; + +interface Filters { + genre: string; + tmdbRatingMin: string; + tmdbRatingMax: string; + userRatingMin: string; + userRatingMax: string; + yearMin: string; + yearMax: string; +} + +interface LibraryFiltersState { + activeTab: FilterTab; + search: string; + sortField: SortField; + sortDir: SortDir; + filters: Filters; + + setActiveTab: (tab: FilterTab) => void; + setSearch: (search: string) => void; + setSortField: (field: SortField) => void; + setSortDir: (dir: SortDir) => void; + setFilters: (updater: Filters | ((prev: Filters) => Filters)) => void; + clearFilters: () => void; +} + +const defaultFilters: Filters = { + genre: '', + tmdbRatingMin: '', + tmdbRatingMax: '', + userRatingMin: '', + userRatingMax: '', + yearMin: '', + yearMax: '', +}; + +export const useLibraryFiltersStore = create((set) => ({ + activeTab: 'all', + search: '', + sortField: 'date_last_seen', + sortDir: 'desc', + filters: defaultFilters, + + setActiveTab: (tab) => set({ activeTab: tab }), + setSearch: (search) => set({ search }), + setSortField: (field) => set({ sortField: field }), + setSortDir: (dir) => set({ sortDir: dir }), + setFilters: (updater) => + set((state) => ({ + filters: typeof updater === 'function' ? updater(state.filters) : updater, + })), + clearFilters: () => set({ filters: defaultFilters }), +})); + +export { defaultFilters }; +export type { FilterTab, SortField, SortDir, Filters }; diff --git a/react_frontend/src/types/index.ts b/react_frontend/src/types/index.ts index 710cb53..c242ce0 100644 --- a/react_frontend/src/types/index.ts +++ b/react_frontend/src/types/index.ts @@ -152,6 +152,8 @@ export interface People { place_of_birth: string | null; known_for_department: string | null; fully_fetched: boolean; + favorite: boolean; + pinned: boolean; profile_path: string | null; createdAt: string; updatedAt: string; @@ -241,3 +243,25 @@ export interface TmdbPaginatedResponse { total_pages: number; total_results: number; } + +export interface TmdbPreview { + tmdb_id: number; + title: string; + original_title: string | null; + release_date: string | null; + runtime: number | null; + storyline: string | null; + country: string | null; + is_tvseries: boolean; + status: string | null; + poster_path: string | null; + backdrop_path: string | null; + vote_average: number | null; + genres: { id: number; name: string }[]; + tagline: string | null; + number_of_seasons: number | null; + number_of_episodes: number | null; + networks: { id: number; name: string; logo_path: string | null }[]; + homepage: string | null; + imdb_id: string | null; +}