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
This commit is contained in:
Mohammed Abad committed 2026-04-27 04:03:02 +01:00
1 parent 6aa57cbe71
commit 25b645a16f
13 files changed
+199 -10

No files matched your search

+17 -1
View File
@@ -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() {
+33
View File
@@ -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();
@@ -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();
+2 -2
View File
@@ -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);
}
+3 -1
View File
@@ -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;
module.exports = Entry;
+3 -1
View File
@@ -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;
module.exports = People;
+1
View File
@@ -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);
+6
View File
@@ -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;
+38 -3
View File
@@ -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();
+21 -1
View File
@@ -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
+32
View File
@@ -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]]
+3
View File
@@ -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 |
---
+30 -1
View File
@@ -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 |