Author SHA1 Message Date
X4Lo 760afd8e84 Add history page with list, timeline and year in review
- Backend: /history/years and /history/:year return every movie and
  episode watch in a year, with entry posters, genres, networks and buddies
- History tab: watches by month and day, back-to-back episodes grouped
- Timeline tab: latest to oldest, month dividers, stacked binge sessions
- Year in Review tab: hours, top shows and genres, streaks, busiest day,
  biggest binge, monthly and weekday charts, buddies and new shows
- Year picker, movies/TV filter, state kept in the URL; unknown-date
  watches badged and excluded from the review by default
- History link in the sidebar and command palette
2026-11-05 16:09:24 +00:00
X4Lo c4aa0488d4 Merge pull request 'Feat/tmdb full data' (#5) from feat/tmdb-full-data into master
Reviewed-on: #5
2026-11-05 14:36:10 +00:00
X4Lo 28eee34548 Unify entry page for TMDB previews and add artwork section
- Entry details page now also renders entries not in the library, using
  the TMDB preview mapped to the same entry shape; remove TmdbPreviewPage
- Preview endpoint returns an entry-shaped object, TMDB seasons and
  directors
- Artwork section: TMDB posters, backdrops and logos merged with the media
  table, with in-library badges, language filter and add-to-library
- Record tmdb_path on downloaded media so TMDB images can be matched
- Recommendations by TMDB id for entries not in the library
2026-11-05 14:06:46 +00:00
X4Lo a9ff2d089a Store full TMDB data, add rate limiting and stale-entry refresh
Backend
- Route all TMDB requests through a rate limiter (20 req/s, 8 concurrent)
  with 429/5xx retries; stop logging the API key
- Fetch external ids, certification, keywords, videos, watch providers and
  alternative titles in the entry details request
- Shared entry mapper used by create, refresh, season refresh and importer
- New columns on entries, ids, ratings, seasons, episodes and people, with
  an idempotent startup migration (adds missing columns, widens types)
- Fix TV IMDb ids, network country/logo, episode tmdb_id on refresh, and
  genre/network removal on refresh
- Add stale-entries maintenance job (count, start, cancel) and live
  recommendations endpoint

Frontend
- Entry page: certification, tagline, creators, in-app trailer, vote count,
  TV/movie details, network logos, external links, keywords, where to
  watch, and recommendations
- Episode page: directors, writers and guest stars
- Settings: TMDB refresh card with live progress
2026-11-05 11:39:15 +00:00
X4Lo cee6f7f961 Merge branch 'feat/entry-details-redesign' 2026-11-05 10:30:53 +00:00
X4Lo 1c6023cc52 Redesign entry details page
- Full-bleed backdrop hero with larger poster, bold title, meta and genres
- Single action bar: watch, trailer, watched, rate, favorite, collection, more
- Two-column body with ratings tiles and details sidebar
- Update loading skeleton to match the new layout
2026-11-05 10:30:41 +00:00
X4Lo 67c828838d Updated electron & react frontend packages & Agents.md 2026-11-03 20:47:40 +00:00
X4Lo cd2c135c65 Merge pull request 'Unify person page for local and TMDB people' (#4) from feat/unified-person-page into master
Reviewed-on: #4
2026-11-03 19:01:47 +00:00
X4Lo f88dfdae44 Unify person page for local and TMDB people
- Merge local and TMDB person views into a single PersonDetailsPage
- Remove unused PersonTmdbRedirectPage
- Show age tooltip on birthdays (person page and people list)
2026-11-03 18:58:42 +00:00
X4Lo 6d4c3e185a Merge pull request 'Add poster popup, selectable title, collection media previews and library toggles' (#3) from feat/details-pages-and-library-filters into master
Reviewed-on: #3
2026-11-03 18:40:25 +00:00
X4Lo 834e02e76b Add poster popup, selectable title, collection media previews and library toggles
- Collection edit dialog shows the current poster and backdrop when available
- Entry details: title is selectable (action row no longer overlays it)
- Entry details: clicking the poster opens it full size in a dialog
- Library: Favorites and Hidden are toggles that combine with the type tabs
2026-11-03 18:39:03 +00:00
X4Lo c74e54bc2a Merge pull request 'Fix collection images and entry settings toggles' (#2) from fix/collections-and-entry-settings-bugs into master
Reviewed-on: #2
2026-11-03 17:30:40 +00:00
X4Lo 72600cbc5d Fix collection images and entry settings toggles
- Show the uploaded backdrop on the collection details page; it only
  looked at the TMDB backdrop and ignored the collection's media
- Fall back to the first entry's poster for collections without a poster
  on both the collections grid and the details page
- Read the live entry from the library store in EntrySettingsDialog so
  toggles reflect the new value instead of a stale prop snapshot
2026-11-03 16:25:12 +00:00
X4Lo a9e4eea856 Merge pull request 'Add Discovery Videos feature' (#1) from feat/discovery-videos into master
Reviewed-on: #1
2026-11-03 16:02:05 +00:00
X4Lo eb3a12f6cb Add Discovery Videos feature
Let users upload videos, tag them with one or more entries, and watch
them from a new Discovery Videos page.

Backend:
- Add Video and VideoEntry models and relations
- Add video controller and /video routes
- Add video thumbnail generation service (ffmpeg-static)
- Add video upload storage location and config

Frontend:
- Add DiscoveryVideosPage with sidebar link and route
- Add AddVideoDialog, VideoDropzone, EntryMultiSelect, VideoCard
  and VideoPlayerDialog components
- Add discoveryVideos API client and useDiscoveryVideos hook
- Add format helpers, video types and normalizers
- Add skeleton for the page

Docs:
- Document the feature in docs-vault
2026-11-03 15:57:53 +00:00
X4Lo 4d88747649 Add season refresh, rating display, and actions dropdown to SeasonPage
Backend: Added PUT /seasons/:id/refresh endpoint that fetches updated
TMDB data for a single season.

Frontend:
- New SeasonRatingDialog for rating seasons via StarRating
- useRefreshSeason and useUpdateSeason hooks with query invalidation
- SeasonPage now shows inline season rating (user + TMDB)
- Mark Watched, Rate, and Refresh actions moved under a dropdown menu
2026-07-05 20:58:40 +01:00
X4Lo 1aa0a84f4d Add computed entry stats to collection detail page
Show movies/series/seasons/episodes counts and estimated
total watch time inline — all from already-fetched data.
2026-07-01 00:00:13 +01:00
X4Lo e660b1ec87 Add Showy Homepage dashboard widget
Homepage widget with totals, library, and watchlist mappings. Displays
total entries, collections, favorites, library breakdown
(movies/series), and watchlist breakdown (movies/series).
2026-06-30 23:59:52 +01:00
X4Lo 63aca7e7b8 Add homepage-integration API endpoint
New GET /api/v1/homepage-integration endpoint exposes library stats
(totalEntries, library, libraryMovies, librarySeries, watchlist,
watchlistMovies, watchlistSeries, collections, favorits).
2026-06-30 23:58:26 +01:00
X4Lo ec9498cac0 Updated settings.json.example 2026-06-30 23:57:35 +01:00
X4Lo 0a79ee9768 Add named-token auth support to middleware and configService
authMiddleware now falls back to checking named tokens from settings
when JWT verification fails. configService.getNamedTokens() filters by
endDate, skipping expired tokens. Tokens without an endDate never expire.
2026-06-30 23:54:04 +01:00
X4Lo c6a838a91c Fix show_in_calendar and auto_sync toggles not persisting
Map snake_case field names from frontend to Sequelize camelCase
properties in controller. Normalize response back to snake_case
so dialog switches read correct boolean values.
2026-06-29 05:18:07 +01:00
X4Lo d12d7cb627 Rework SearchPage with tabs, infinite scroll, and anti-spam
- Add Movies & TV / People tabs next to search input
- Filter person results from movie/TV grid
- People tab with larger avatar cards, name always visible
- Infinite scroll with IntersectionObserver sentinel per tab
- Stop auto-scroll after 4 consecutive empty pages, show Load More button instead
2026-06-29 02:49:58 +01:00
X4Lo c09f70054c Add type-level duplicate credit cleanup to maintenance
Pass 1 handles exact role-level dupes. Pass 2 detects same
person/entry/type with different roles and keeps the credit
with a meaningful role, deleting the empty one.
2026-06-29 02:23:31 +01:00
X4Lo ea91c6011a Fix credits linking for TV aggregate format in create and refresh
Handle TV aggregate_credits (roles/jobs arrays) in entry creation,
matching the clean logic already in refresh. Also fix director
detection to search jobs[] array for TV series in both paths.
2026-06-29 02:10:24 +01:00
119 changed files with 10552 additions and 5047 deletions

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ environment.ts
circular-dependencies.png circular-dependencies.png
.agents/skills .agents/skills
auto_puller.py auto_puller.py
/brain
# Compiled output # Compiled output
.angular .angular
-27
View File
@@ -11,33 +11,6 @@ You can get project context from the following files:
## Mandatory Task Completion Rule ## Mandatory Task Completion Rule
#### Update the `changes.md` file after completing any task requested by the user.
After completing ANY task requested by the user, you MUST update the file `changes.md`.
Append a new section at the end of `changes.md` using this exact format:
```md
### Milestone XXX
#### Backend Changes
- <change 1>
- <change 2>
- <change 3>
#### Frontend Changes
```
#### Rules
- Always ask the user if this is a new milestone or if you should continue appending to the current milestone.
- Replace `XXX` with the task number provided by the user (example: `025`).
- The bullet list must include all important modifications made.
- Do NOT overwrite previous entries: always APPEND.
- If `changes.md` does not exist, create it.
- If no task number is provided, use the next available number based on the last entry in the file.
- Always ensure formatting matches exactly (heading + code block + bullets).
### Documentation (Skip the legacy docs, we're using obsidian docs-vault now) ### Documentation (Skip the legacy docs, we're using obsidian docs-vault now)
Update the `/backend/docs` and `/react_frontend/docs` folders with any relevant documentation changes related to the task you completed. This includes API documentation, architectural diagrams, or any other relevant docs. Update the `/backend/docs` and `/react_frontend/docs` folders with any relevant documentation changes related to the task you completed. This includes API documentation, architectural diagrams, or any other relevant docs.
+74
View File
@@ -0,0 +1,74 @@
const sequelize = require("./database");
/**
* Lightweight, idempotent schema migrations.
*
* `sequelize.sync()` runs without `alter`, so new model attributes never reach
* existing tables. This adds any column a model defines but the table lacks
* (additive only — nothing is dropped) and widens the few columns whose type
* changed. Safe to run on every start.
*/
// [model name, attribute name, expected DB type prefix (from describeTable)]
const TYPE_CHANGES = [
["entry", "certification", "VARCHAR(20)"],
["entry", "last_fetch", "DATETIME"],
["entry", "network_studio", "VARCHAR(100)"],
["network", "name", "VARCHAR(100)"],
];
async function addMissingColumns(queryInterface) {
for (const model of Object.values(sequelize.models)) {
const table = model.getTableName();
let columns;
try {
columns = await queryInterface.describeTable(table);
} catch {
continue; // table not created yet; sync handles it
}
for (const [name, attribute] of Object.entries(model.rawAttributes)) {
const column = attribute.field || name;
if (columns[column] || attribute.type?.key === "VIRTUAL") continue;
console.log(`[MIGRATION] Adding column ${table}.${column}`);
await queryInterface.addColumn(table, column, {
type: attribute.type,
allowNull: attribute.allowNull !== false,
defaultValue: attribute.defaultValue,
});
}
}
}
async function applyTypeChanges(queryInterface) {
for (const [modelName, attributeName, expectedType] of TYPE_CHANGES) {
const model = sequelize.models[modelName];
if (!model) continue;
const attribute = model.rawAttributes[attributeName];
const column = attribute.field || attributeName;
const table = model.getTableName();
const columns = await queryInterface.describeTable(table);
const current = columns[column]?.type?.toUpperCase();
if (!current || current.startsWith(expectedType)) continue;
console.log(
`[MIGRATION] Changing ${table}.${column} from ${current} to ${expectedType}`,
);
await queryInterface.changeColumn(table, column, {
type: attribute.type,
allowNull: attribute.allowNull !== false,
defaultValue: attribute.defaultValue,
});
}
}
async function runMigrations() {
const queryInterface = sequelize.getQueryInterface();
await addMissingColumns(queryInterface);
await applyTypeChanges(queryInterface);
}
module.exports = { runMigrations };
+19
View File
@@ -19,6 +19,8 @@ const Credit = require('../models/Credit');
const WatchBuddy = require('../models/WatchBuddy'); const WatchBuddy = require('../models/WatchBuddy');
const EntrySeenBuddy = require('../models/EntrySeenBuddy'); const EntrySeenBuddy = require('../models/EntrySeenBuddy');
const EpisodeSeenBuddy = require('../models/EpisodeSeenBuddy'); const EpisodeSeenBuddy = require('../models/EpisodeSeenBuddy');
const Video = require('../models/Video');
const VideoEntry = require('../models/VideoEntry');
// ? one to one // ? one to one
// A hasOne B = A > B // A hasOne B = A > B
@@ -289,3 +291,20 @@ WatchBuddy.belongsToMany(EpisodeSeen, {
otherKey: 'episode_seen_id', otherKey: 'episode_seen_id',
as: 'episodeSeens', as: 'episodeSeens',
}); });
// * VIDEO & ENTRY - MANY TO MANY (discovery videos)
Video.belongsToMany(Entry, {
through: VideoEntry,
foreignKey: 'video_id',
otherKey: 'entry_id',
onDelete: 'CASCADE',
as: 'entries',
});
Entry.belongsToMany(Video, {
through: VideoEntry,
foreignKey: 'entry_id',
otherKey: 'video_id',
onDelete: 'CASCADE',
as: 'videos',
});
+130 -16
View File
@@ -1,9 +1,15 @@
const EntryRating = require('../models/EntryRating'); const EntryRating = require("../models/EntryRating");
const collectionManager = require('../services/collectionManager'); const collectionManager = require("../services/collectionManager");
const entryManager = require('../services/entryManager'); const entryManager = require("../services/entryManager");
const entryService = require('../services/entryService'); const entryService = require("../services/entryService");
const tmdbService = require('../services/tmdbService'); const tmdbService = require("../services/tmdbService");
const asyncWrapper = require('../utils/asyncWrapper'); const artworkService = require("../services/artworkService");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
} = require("../mappers/entryMapper");
const asyncWrapper = require("../utils/asyncWrapper");
const _collectionManager = collectionManager; const _collectionManager = collectionManager;
const _entryManager = entryManager; const _entryManager = entryManager;
@@ -105,7 +111,7 @@ class EntryController {
const seasons = await _entryService.getEntrySeasons(id); const seasons = await _entryService.getEntrySeasons(id);
if (seasons.length == 0) { if (seasons.length == 0) {
return res.status(204).json({ message: 'Provided entry has no seasons' }); return res.status(204).json({ message: "Provided entry has no seasons" });
} }
res.status(200).json(seasons); res.status(200).json(seasons);
@@ -126,6 +132,59 @@ class EntryController {
res.status(201).json(entry); res.status(201).json(entry);
}); });
// * GET - TMDB RECOMMENDATIONS FOR A LIBRARY ENTRY (live, not stored)
getEntryRecommendations = asyncWrapper(async (req, res) => {
const entry = await _entryService.getEntryById(req.params.id, false);
const tmdbId = entry.entryId?.tmdb_id;
if (!tmdbId)
return res.status(400).json({ message: "Entry has no TMDB id" });
const data = await tmdbService.fetchEntryRecommendations(
tmdbId,
entry.is_tvseries,
req.query.page || 1,
);
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch recommendations" });
res.status(200).json(data);
});
// * GET - TMDB RECOMMENDATIONS BY TMDB ID (entries not in the library)
getTmdbRecommendations = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params;
const data = await tmdbService.fetchEntryRecommendations(
tmdbId,
type === "tv",
req.query.page || 1,
);
if (!data)
return res
.status(500)
.json({ message: "Failed to fetch recommendations" });
res.status(200).json(data);
});
// * GET - ARTWORK: TMDB images merged with the entry's media table
getEntryArtwork = asyncWrapper(async (req, res) => {
const artwork = await artworkService.getEntryArtwork(req.params.id);
res.status(200).json(artwork);
});
// * POST - ARTWORK: download a TMDB image into the entry's media table
addEntryArtwork = asyncWrapper(async (req, res) => {
const media = await artworkService.addEntryArtwork(req.params.id, req.body);
res.status(201).json(media);
});
// * GET - ARTWORK BY TMDB ID (entries not in the library)
getTmdbArtwork = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params;
const artwork = await artworkService.getTmdbArtwork(type, tmdbId);
res.status(200).json(artwork);
});
// * PUT - REQUEST COLLECTION REFRECH // * PUT - REQUEST COLLECTION REFRECH
fetchEntryCollection = asyncWrapper(async (req, res, next) => { fetchEntryCollection = asyncWrapper(async (req, res, next) => {
const { id } = req.params; const { id } = req.params;
@@ -145,7 +204,7 @@ class EntryController {
const { page } = req.query; const { page } = req.query;
const data = await tmdbService.fetchTrending(type, page || 1); const data = await tmdbService.fetchTrending(type, page || 1);
if (!data) if (!data)
return res.status(500).json({ message: 'Failed to fetch trending data' }); return res.status(500).json({ message: "Failed to fetch trending data" });
res.status(200).json(data); res.status(200).json(data);
}); });
@@ -155,7 +214,7 @@ class EntryController {
const { page } = req.query; const { page } = req.query;
const data = await tmdbService.fetchPopular(type, page || 1); const data = await tmdbService.fetchPopular(type, page || 1);
if (!data) if (!data)
return res.status(500).json({ message: 'Failed to fetch popular data' }); return res.status(500).json({ message: "Failed to fetch popular data" });
res.status(200).json(data); res.status(200).json(data);
}); });
@@ -163,10 +222,10 @@ class EntryController {
getTmdbSearch = asyncWrapper(async (req, res) => { getTmdbSearch = asyncWrapper(async (req, res) => {
const { query, page } = req.query; const { query, page } = req.query;
if (!query) if (!query)
return res.status(400).json({ message: 'Query parameter is required' }); return res.status(400).json({ message: "Query parameter is required" });
const data = await tmdbService.searchMulti(query, page || 1); const data = await tmdbService.searchMulti(query, page || 1);
if (!data) if (!data)
return res.status(500).json({ message: 'Failed to search TMDB' }); return res.status(500).json({ message: "Failed to search TMDB" });
res.status(200).json(data); res.status(200).json(data);
}); });
@@ -178,7 +237,7 @@ class EntryController {
if (!data) if (!data)
return res return res
.status(500) .status(500)
.json({ message: 'Failed to fetch top rated data' }); .json({ message: "Failed to fetch top rated data" });
res.status(200).json(data); res.status(200).json(data);
}); });
@@ -187,17 +246,17 @@ class EntryController {
const { page } = req.query; const { page } = req.query;
const data = await tmdbService.fetchUpcoming(page || 1); const data = await tmdbService.fetchUpcoming(page || 1);
if (!data) if (!data)
return res.status(500).json({ message: 'Failed to fetch upcoming data' }); return res.status(500).json({ message: "Failed to fetch upcoming data" });
res.status(200).json(data); res.status(200).json(data);
}); });
// * GET - TMDB PREVIEW (fetch details without saving to library) // * GET - TMDB PREVIEW (fetch details without saving to library)
getTmdbPreview = asyncWrapper(async (req, res) => { getTmdbPreview = asyncWrapper(async (req, res) => {
const { type, tmdbId } = req.params; const { type, tmdbId } = req.params;
const is_tvserie = type === 'tv'; const is_tvserie = type === "tv";
const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie); const data = await tmdbService.fetchEntryData(tmdbId, is_tvserie);
if (!data) if (!data)
return res.status(404).json({ message: 'Entry not found on TMDB' }); return res.status(404).json({ message: "Entry not found on TMDB" });
// Fetch credits in parallel // Fetch credits in parallel
const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie); const creditsData = await tmdbService.fetchEntryCredits(tmdbId, is_tvserie);
@@ -208,7 +267,7 @@ class EntryController {
for (const c of creditsData.cast) { for (const c of creditsData.cast) {
credits.push({ credits.push({
id: c.credit_id || c.id, id: c.credit_id || c.id,
cast_type: 'cast', cast_type: "cast",
character: is_tvserie character: is_tvserie
? c.roles?.[0]?.character || c.character || null ? c.roles?.[0]?.character || c.character || null
: c.character || null, : c.character || null,
@@ -223,6 +282,59 @@ class EntryController {
} }
} }
// Directors, so the preview page can show "Directed by"
for (const c of creditsData?.crew ?? []) {
const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job];
if (!jobs.includes("Director")) continue;
credits.push({
id: c.credit_id || c.jobs?.[0]?.credit_id || "crew-" + c.id,
cast_type: "crew",
job: "Director",
department: "Directing",
character: null,
people_id: c.id,
people: {
id: c.id,
name: c.name || c.original_name,
profile_path: c.profile_path,
tmdb_id: c.id,
},
});
}
// Same shape as a library entry, so the details page can render either
const entry = {
id: 0,
...mapEntryFields(data),
is_tvseries: is_tvserie,
isInLibrary: false,
entryIds: { tmdb_id: data.id, ...mapEntryIds(data) },
entryRatings: {
user_rating: null,
imdb_rating: null,
rotten_tomatoes_rating: null,
...mapEntryRatings(data),
},
genres: data.genres || [],
networks: (data.networks || []).map((n) => ({
id: n.id,
name: n.name,
origin_country: n.origin_country || null,
logo_path: n.logo_path || null,
homepage: null,
})),
};
const seasons = (data.seasons || []).map((s) => ({
id: s.id,
name: s.name,
season_number: s.season_number,
episode_count: s.episode_count,
air_date: s.air_date,
poster_path: s.poster_path,
overview: s.overview,
tmdb_rating: s.vote_average,
}));
// Normalize to a shape similar to our Entry model // Normalize to a shape similar to our Entry model
const preview = { const preview = {
tmdb_id: data.id, tmdb_id: data.id,
@@ -248,6 +360,8 @@ class EntryController {
homepage: data.homepage || null, homepage: data.homepage || null,
imdb_id: data.imdb_id || data.external_ids?.imdb_id || null, imdb_id: data.imdb_id || data.external_ids?.imdb_id || null,
credits, credits,
entry,
seasons,
}; };
res.status(200).json(preview); res.status(200).json(preview);
@@ -0,0 +1,62 @@
const Entry = require("../models/Entry");
const Collection = require("../models/Collection");
const { Op } = require("sequelize");
class HomepageIntegrationController {
constructor() {
if (!HomepageIntegrationController.instance) {
HomepageIntegrationController.instance = this;
}
return HomepageIntegrationController.instance;
}
async getStats(req, res) {
try {
const notSeries = { is_tvseries: { [Op.or]: [false, null] } };
const isSeries = { is_tvseries: true };
const [
totalEntries,
library,
libraryMovies,
librarySeries,
watchlist,
watchlistMovies,
watchlistSeries,
collections,
favorits,
] = await Promise.all([
Entry.count(),
Entry.count({ where: { watchlist: { [Op.or]: [false, null] } } }),
Entry.count({
where: { watchlist: { [Op.or]: [false, null] }, ...notSeries },
}),
Entry.count({
where: { watchlist: { [Op.or]: [false, null] }, ...isSeries },
}),
Entry.count({ where: { watchlist: true } }),
Entry.count({ where: { watchlist: true, ...notSeries } }),
Entry.count({ where: { watchlist: true, ...isSeries } }),
Collection.count(),
Entry.count({ where: { favorit: true } }),
]);
return res.status(200).json({
totalEntries,
library,
libraryMovies,
librarySeries,
watchlist,
watchlistMovies,
watchlistSeries,
collections,
favorits,
});
} catch (error) {
console.error("Homepage integration error:", error);
return res.status(500).json({ error: "Failed to fetch library stats" });
}
}
}
module.exports = new HomepageIntegrationController();
+28 -1
View File
@@ -78,6 +78,33 @@ class MaintenanceController {
const result = await _maintenanceService.fixImpossibleSeenDates(); const result = await _maintenanceService.fixImpossibleSeenDates();
return res.status(200).json(result); return res.status(200).json(result);
} }
parseHours(value) {
const hours = Number(value ?? 24);
return Number.isFinite(hours) && hours >= 0 ? hours : 24;
}
async getStaleEntries(req, res) {
const hours = maintenanceController.parseHours(req.query.hours);
const entries = await _maintenanceService.getStaleEntries(hours);
return res.status(200).json({
count: entries.length,
hours,
job: _maintenanceService.getStaleRefreshStatus(),
});
}
async startStaleRefresh(req, res) {
const hours = maintenanceController.parseHours(req.query.hours);
const result = await _maintenanceService.startStaleRefresh(hours);
return res.status(result.alreadyRunning ? 409 : 202).json(result);
}
async cancelStaleRefresh(req, res) {
return res.status(200).json(_maintenanceService.cancelStaleRefresh());
}
} }
module.exports = new MaintenanceController(); const maintenanceController = new MaintenanceController();
module.exports = maintenanceController;
+57
View File
@@ -1,6 +1,13 @@
const Episode = require("../models/Episode"); const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen"); const EpisodeSeen = require("../models/EpisodeSeen");
const Season = require("../models/Season"); const Season = require("../models/Season");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const { fetchSeasonData } = require("../services/tmdbService");
const {
mapSeasonFields,
mapEpisodeFields,
} = require("../mappers/entryMapper.js");
class SeasonController { class SeasonController {
constructor() { constructor() {
@@ -88,6 +95,56 @@ class SeasonController {
} }
} }
async refreshSeason(req, res) {
try {
const season = await Season.findByPk(req.params.id, {
include: [
{
model: Entry,
as: "entry",
include: [{ model: EntryId, as: "entryId" }],
},
],
});
if (!season) {
return res.status(404).send("Season not found");
}
const tmdbTvId = season.entry?.entryId?.tmdb_id;
if (!tmdbTvId) {
return res.status(400).send("Entry has no TMDB ID");
}
const seasonData = await fetchSeasonData(tmdbTvId, season.season_number);
if (!seasonData) {
return res.status(500).send("Couldn't fetch data from TMDB");
}
await season.update(mapSeasonFields(seasonData));
// Keep the season's episodes in sync too (guest stars, crew, votes…)
for (const episode of seasonData.episodes ?? []) {
const existingEpisode = await Episode.findOne({
where: { tmdb_id: episode.id },
});
if (existingEpisode) {
await existingEpisode.update(mapEpisodeFields(episode));
} else {
await Episode.create({
...mapEpisodeFields(episode),
season_id: season.id,
});
}
}
const refreshedSeason = await Season.findByPk(req.params.id);
res.send(refreshedSeason);
} catch (error) {
res.status(500).send(error.message);
}
}
async deleteSeason(req, res) { async deleteSeason(req, res) {
try { try {
const deleted = await Season.destroy({ const deleted = await Season.destroy({
+280
View File
@@ -0,0 +1,280 @@
const path = require("path");
const fs = require("fs");
const sequelize = require("../config/database");
const Video = require("../models/Video");
const VideoEntry = require("../models/VideoEntry");
const Entry = require("../models/Entry");
const configService = require("../services/configService.js");
const asyncWrapper = require("../utils/asyncWrapper");
const videoThumbnailService = require("../services/videoThumbnailService");
const ALLOWED_EXTENSIONS = ["mp4", "webm", "mov", "m4v", "mkv", "avi"];
function parseEntryIds(raw) {
if (raw === undefined || raw === null || raw === "") return [];
let parsed;
try {
parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
} catch (err) {
return null; // signal invalid input to the caller
}
if (!Array.isArray(parsed)) return null;
const ids = [...new Set(parsed.map(Number))].filter(
(n) => Number.isInteger(n) && n > 0,
);
return ids;
}
function getVideosDir() {
const dataPath = configService.getSettings().userDataPath;
return path.join(dataPath, "videos");
}
async function removeFileQuietly(filePath) {
try {
await fs.promises.unlink(filePath);
} catch (err) {
// file already gone — nothing to clean up
}
}
class VideoController {
constructor() {
if (!VideoController.instance) {
VideoController.instance = this;
}
return VideoController.instance;
}
// * GET /discovery-videos?page=1&limit=24
getVideos = asyncWrapper(async (req, res) => {
const page = Math.max(parseInt(req.query.page, 10) || 1, 1);
const limit = Math.min(
Math.max(parseInt(req.query.limit, 10) || 24, 1),
100,
);
const { count, rows } = await Video.findAndCountAll({
limit,
offset: (page - 1) * limit,
order: [["createdAt", "DESC"]],
distinct: true,
include: [
{
model: Entry,
as: "entries",
attributes: ["id", "title", "poster_path", "is_tvseries"],
through: { attributes: [] },
},
],
});
res.status(200).json({
videos: rows,
page,
limit,
total: count,
totalPages: Math.ceil(count / limit),
});
});
// * POST /discovery-videos (multipart: videos[], description, entryIds)
uploadVideos = asyncWrapper(async (req, res) => {
const files = req.files;
if (!files || files.length === 0) {
return res.status(400).json({ message: "No files uploaded" });
}
const entryIds = parseEntryIds(req.body.entryIds);
if (entryIds === null) {
await Promise.all(
files.map((file) =>
removeFileQuietly(path.join(getVideosDir(), file.filename)),
),
);
return res.status(400).json({ message: "entryIds must be a JSON array" });
}
const invalidFile = files.find((file) => {
const ext = file.originalname.split(".").pop().toLowerCase();
return !ALLOWED_EXTENSIONS.includes(ext);
});
if (invalidFile) {
await Promise.all(
files.map((file) =>
removeFileQuietly(path.join(getVideosDir(), file.filename)),
),
);
return res.status(400).json({
message: `Unsupported file type. Allowed: ${ALLOWED_EXTENSIONS.join(", ")}`,
});
}
const description =
typeof req.body.description === "string" ? req.body.description : "";
const createdVideos = [];
for (const file of files) {
const title =
file.originalname.replace(/\.[^.]+$/, "").trim() || "Untitled video";
const video = await Video.create({
title,
description,
filename: file.filename,
original_name: file.originalname,
mime_type: file.mimetype,
size: file.size,
});
if (entryIds.length > 0) {
await VideoEntry.bulkCreate(
entryIds.map((entryId) => ({
video_id: video.id,
entry_id: entryId,
})),
);
}
createdVideos.push(video);
}
return res.status(200).json(createdVideos);
});
// * PUT /discovery-videos/:id (title, description, entryIds)
updateVideo = asyncWrapper(async (req, res) => {
const video = await Video.findByPk(req.params.id);
if (!video) {
return res.status(404).json({ message: "Video not found" });
}
const { title, description, entryIds } = req.body;
if (title !== undefined && typeof title === "string") {
video.title = title.trim() || video.title;
}
if (description !== undefined && typeof description === "string") {
video.description = description;
}
let parsedEntryIds;
if (entryIds !== undefined) {
parsedEntryIds = parseEntryIds(entryIds);
if (parsedEntryIds === null) {
return res
.status(400)
.json({ message: "entryIds must be a JSON array" });
}
}
await sequelize.transaction(async (t) => {
await video.save({ transaction: t });
if (parsedEntryIds !== undefined) {
await VideoEntry.destroy({
where: { video_id: video.id },
transaction: t,
});
if (parsedEntryIds.length > 0) {
await VideoEntry.bulkCreate(
parsedEntryIds.map((entryId) => ({
video_id: video.id,
entry_id: entryId,
})),
{ transaction: t },
);
}
}
});
const updated = await Video.findByPk(video.id, {
include: [
{
model: Entry,
as: "entries",
attributes: ["id", "title", "poster_path", "is_tvseries"],
through: { attributes: [] },
},
],
});
return res.status(200).json(updated);
});
// * DELETE /discovery-videos/:id
deleteVideo = asyncWrapper(async (req, res) => {
const video = await Video.findByPk(req.params.id);
if (!video) {
return res.status(404).json({ message: "Video not found" });
}
await VideoEntry.destroy({ where: { video_id: video.id } });
await video.destroy();
// Remove the video file and its thumbnail. The thumbnail filename is
// derived from the video filename, so delete it even if the DB row
// never had thumbnail_path set (e.g. a failed update).
await removeFileQuietly(path.join(getVideosDir(), video.filename));
const thumbnailNames = new Set([
`${video.filename.split(".")[0]}.jpg`,
...(video.thumbnail_path ? [video.thumbnail_path] : []),
]);
for (const name of thumbnailNames) {
await removeFileQuietly(path.join(getVideosDir(), "thumbnails", name));
}
return res.status(200).json({ message: "Video deleted" });
});
// * GET /discovery-videos/:id/thumbnail
// Serves the thumbnail image. If none exists yet, generates it on
// demand (deduped + concurrency-limited inside the service) and
// serves it in the same response.
getThumbnail = asyncWrapper(async (req, res) => {
const video = await Video.findByPk(req.params.id);
if (!video) {
return res.status(404).json({ message: "Video not found" });
}
const thumbDir = path.join(getVideosDir(), "thumbnails");
const thumbName =
video.thumbnail_path || `${video.filename.split(".")[0]}.jpg`;
let filePath = path.join(thumbDir, thumbName);
if (!fs.existsSync(filePath)) {
const generated = await videoThumbnailService.ensureThumbnail(video);
if (generated) {
filePath = path.join(thumbDir, generated);
}
}
if (!fs.existsSync(filePath)) {
return res.status(404).json({ message: "Thumbnail not available" });
}
res.sendFile(filePath, (err) => {
if (err && !res.headersSent) {
res.status(404).json({ message: "Thumbnail not available" });
}
});
});
// * GET /discovery-videos/:id/stream (supports HTTP Range via res.sendFile)
streamVideo = asyncWrapper(async (req, res) => {
const video = await Video.findByPk(req.params.id);
if (!video) {
return res.status(404).json({ message: "Video not found" });
}
const filePath = path.join(getVideosDir(), video.filename);
res.sendFile(filePath, (err) => {
if (err && !res.headersSent) {
res.status(404).json({ message: "Video file not found" });
}
});
});
}
module.exports = new VideoController();
+263
View File
@@ -0,0 +1,263 @@
/**
* Maps TMDB responses (from tmdbService.fetchEntryData / fetchSeasonData) to
* the column values we store. Used by entry creation, the entry refresh and
* the legacy importer so every path saves the same fields.
*/
const CERTIFICATION_REGIONS = ["US", "GB"];
const MAX_VIDEOS = 12;
const MAX_KEYWORDS = 30;
const MAX_EPISODE_CREW = 15;
const MAX_GUEST_STARS = 25;
const pick = (obj, keys) =>
obj ? Object.fromEntries(keys.map((k) => [k, obj[k] ?? null])) : null;
function isTv(data) {
return data.first_air_date !== undefined || data.name !== undefined;
}
/** First non-empty certification, preferring US, then the origin country. */
function mapCertification(data) {
const regions = [...CERTIFICATION_REGIONS, ...(data.origin_country ?? [])];
if (data.content_ratings) {
const results = data.content_ratings.results ?? [];
for (const region of regions) {
const rating = results.find((r) => r.iso_3166_1 === region)?.rating;
if (rating) return rating;
}
return results.find((r) => r.rating)?.rating ?? null;
}
if (data.release_dates) {
const results = data.release_dates.results ?? [];
const certFor = (r) => {
const dates = (r?.release_dates ?? []).filter((d) => d.certification);
// Prefer theatrical (3), then limited (2), then anything
const byType =
dates.find((d) => d.type === 3) ??
dates.find((d) => d.type === 2) ??
dates[0];
return byType?.certification || null;
};
for (const region of regions) {
const cert = certFor(results.find((r) => r.iso_3166_1 === region));
if (cert) return cert;
}
}
return null;
}
function mapVideos(videos) {
const results = (videos?.results ?? []).filter(
(v) => v.site === "YouTube" && v.key,
);
const rank = (v) =>
(v.type === "Trailer" ? 0 : v.type === "Teaser" ? 1 : 2) +
(v.official ? 0 : 3);
return results
.sort(
(a, b) =>
rank(a) - rank(b) ||
new Date(b.published_at) - new Date(a.published_at),
)
.slice(0, MAX_VIDEOS)
.map((v) =>
pick(v, ["key", "name", "type", "official", "published_at", "iso_639_1"]),
);
}
/** Keeps per-country provider lists, trimmed to what the UI needs. */
function mapWatchProviders(providers) {
const results = providers?.results;
if (!results) return null;
const trimList = (list) =>
list?.map((p) =>
pick(p, [
"provider_id",
"provider_name",
"logo_path",
"display_priority",
]),
);
return Object.fromEntries(
Object.entries(results).map(([country, info]) => [
country,
{
link: info.link ?? null,
flatrate: trimList(info.flatrate),
free: trimList(info.free),
ads: trimList(info.ads),
rent: trimList(info.rent),
buy: trimList(info.buy),
},
]),
);
}
function mapEpisodeSummary(episode) {
return pick(episode, [
"id",
"name",
"season_number",
"episode_number",
"air_date",
"episode_type",
"runtime",
"still_path",
]);
}
/** Entry table columns. */
function mapEntryFields(data) {
const tv = isTv(data);
const keywords = (data.keywords?.keywords ?? data.keywords?.results ?? [])
.slice(0, MAX_KEYWORDS)
.map((k) => k.name);
const alternativeTitles = (
data.alternative_titles?.titles ??
data.alternative_titles?.results ??
[]
).map((t) => pick(t, ["iso_3166_1", "title", "type"]));
return {
title: data.title || data.name,
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date || null,
release_status: data.status,
runtime:
data.runtime ||
data.episode_run_time?.[0] ||
data.last_episode_to_air?.runtime ||
null,
tagline: data.tagline || null,
storyline: data.overview,
country: data.production_countries?.[0]?.name ?? null,
status: data.status,
certification: mapCertification(data),
network_studio:
data.networks?.[0]?.name ?? data.production_companies?.[0]?.name ?? null,
adult: !!data.adult,
tmdb_popularity: data.popularity ?? null,
original_language: data.original_language ?? null,
origin_country: data.origin_country ?? null,
spoken_languages:
data.spoken_languages?.map((l) =>
pick(l, ["iso_639_1", "english_name", "name"]),
) ?? null,
production_countries: data.production_countries ?? null,
production_companies:
data.production_companies?.map((c) =>
pick(c, ["id", "name", "logo_path", "origin_country"]),
) ?? null,
homepage: data.homepage || null,
budget: tv ? null : data.budget || null,
revenue: tv ? null : data.revenue || null,
keywords,
tmdb_videos: mapVideos(data.videos),
watch_providers: mapWatchProviders(data["watch/providers"]),
alternative_titles: alternativeTitles,
tv_type: tv ? (data.type ?? null) : null,
created_by: tv
? (data.created_by ?? []).map((p) =>
pick(p, ["id", "name", "profile_path"]),
)
: null,
number_of_seasons: tv ? (data.number_of_seasons ?? null) : null,
number_of_episodes: tv ? (data.number_of_episodes ?? null) : null,
last_air_date: tv ? (data.last_air_date ?? null) : null,
in_production: tv ? (data.in_production ?? null) : null,
next_episode_to_air: tv
? mapEpisodeSummary(data.next_episode_to_air)
: null,
last_episode_to_air: tv
? mapEpisodeSummary(data.last_episode_to_air)
: null,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date(),
};
}
/** EntryId table columns. TV details have no imdb_id; it's in external_ids. */
function mapEntryIds(data) {
const ext = data.external_ids ?? {};
return {
imdb_id: data.imdb_id || ext.imdb_id || null,
tvdb_id: ext.tvdb_id != null ? String(ext.tvdb_id) : null,
wikidata_id: ext.wikidata_id || null,
facebook_id: ext.facebook_id || null,
instagram_id: ext.instagram_id || null,
twitter_id: ext.twitter_id || null,
};
}
/** EntryRating TMDB columns (user/imdb/rt ratings are left untouched). */
function mapEntryRatings(data) {
return {
tmdb_rating: data.vote_average ?? null,
tmdb_vote_count: data.vote_count ?? null,
};
}
/** Season table columns from a season details response. */
function mapSeasonFields(seasonData) {
return {
tmdb_id: seasonData.id,
tvdb_id:
seasonData.external_ids?.tvdb_id != null
? String(seasonData.external_ids.tvdb_id)
: null,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes?.length ?? 0,
air_date: seasonData.air_date,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
};
}
/** Episode table columns from an entry of seasonData.episodes. */
function mapEpisodeFields(episode) {
return {
tmdb_id: episode.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
tmdb_vote_count: episode.vote_count ?? null,
production_code: episode.production_code || null,
crew: (episode.crew ?? [])
.filter((c) => ["Directing", "Writing"].includes(c.department))
.slice(0, MAX_EPISODE_CREW)
.map((c) => pick(c, ["id", "name", "job", "department", "profile_path"])),
guest_stars: (episode.guest_stars ?? [])
.slice(0, MAX_GUEST_STARS)
.map((g) =>
pick(g, ["id", "name", "character", "profile_path", "order"]),
),
still_path: episode.still_path,
};
}
module.exports = {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
};
+44 -9
View File
@@ -1,6 +1,45 @@
const jwt = require("jsonwebtoken"); const jwt = require("jsonwebtoken");
const configService = require("../services/configService"); const configService = require("../services/configService");
function validateToken(tokenValue) {
const settings = configService.getSettings();
const jwtSecret = settings.jwtSecret || "showy-default-secret";
// 1. Check dedicated dashboardToken
if (settings.dashboardToken && settings.dashboardToken === tokenValue) {
return true;
}
// 2. Check named tokens (supports expiration)
const namedTokens = configService.getNamedTokens();
if (namedTokens.some((t) => t.value === tokenValue)) {
return true;
}
// 3. Try JWT
try {
jwt.verify(tokenValue, jwtSecret);
return true;
} catch {
// not a valid JWT
}
return false;
}
function extractToken(req) {
// Authorization: Bearer <token>
const auth = req.headers.authorization;
if (auth && auth.startsWith("Bearer ")) {
return auth.slice(7);
}
// ?token= query parameter
if (req.query.token) {
return req.query.token;
}
return null;
}
function authMiddleware(req, res, next) { function authMiddleware(req, res, next) {
// Skip auth for login/verify/media endpoints // Skip auth for login/verify/media endpoints
if ( if (
@@ -11,20 +50,16 @@ function authMiddleware(req, res, next) {
return next(); return next();
} }
const auth = req.headers.authorization; const tokenValue = extractToken(req);
if (!auth || !auth.startsWith("Bearer ")) { if (!tokenValue) {
return res.status(401).json({ error: "Authentication required" }); return res.status(401).json({ error: "Authentication required" });
} }
const settings = configService.getSettings(); if (!validateToken(tokenValue)) {
const jwtSecret = settings.jwtSecret || "showy-default-secret";
try {
jwt.verify(auth.slice(7), jwtSecret);
next();
} catch {
return res.status(401).json({ error: "Invalid or expired token" }); return res.status(401).json({ error: "Invalid or expired token" });
} }
next();
} }
module.exports = authMiddleware; module.exports = authMiddleware;
+62 -21
View File
@@ -1,27 +1,54 @@
const { DataTypes } = require('sequelize'); const { DataTypes } = require("sequelize");
const sequelize = require('../config/database'); const sequelize = require("../config/database");
const Entry = sequelize.define('entry', { const Entry = sequelize.define("entry", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
title: { type: DataTypes.STRING(500) }, title: { type: DataTypes.STRING(500) },
original_title: { type: DataTypes.STRING(100), field: 'original_title' }, original_title: { type: DataTypes.STRING(100), field: "original_title" },
release_date: { type: DataTypes.DATE, field: 'release_date' }, release_date: { type: DataTypes.DATE, field: "release_date" },
release_status: { type: DataTypes.STRING(50), field: 'release_status' }, release_status: { type: DataTypes.STRING(50), field: "release_status" },
runtime: { type: DataTypes.INTEGER }, runtime: { type: DataTypes.INTEGER },
tagline: { type: DataTypes.STRING(200) }, tagline: { type: DataTypes.STRING(200) },
storyline: { type: DataTypes.STRING(3000) }, storyline: { type: DataTypes.STRING(3000) },
country: { type: DataTypes.STRING(30) }, country: { type: DataTypes.STRING(30) },
certification: { type: DataTypes.INTEGER }, certification: { type: DataTypes.STRING(20) },
network_studio: { type: DataTypes.STRING(40), field: 'network_studio' }, network_studio: { type: DataTypes.STRING(100), field: "network_studio" },
collection_id: { type: DataTypes.INTEGER, field: 'collection_id' },
max_cast: { type: DataTypes.INTEGER, field: 'max_cast', defaultValue: 10 }, // ? TMDB details
adult: { type: DataTypes.BOOLEAN, defaultValue: false },
tmdb_popularity: { type: DataTypes.FLOAT, field: "tmdb_popularity" },
original_language: { type: DataTypes.STRING(10), field: "original_language" },
origin_country: { type: DataTypes.JSON, field: "origin_country" },
spoken_languages: { type: DataTypes.JSON, field: "spoken_languages" },
production_countries: { type: DataTypes.JSON, field: "production_countries" },
production_companies: { type: DataTypes.JSON, field: "production_companies" },
homepage: { type: DataTypes.STRING(500) },
budget: { type: DataTypes.BIGINT },
revenue: { type: DataTypes.BIGINT },
keywords: { type: DataTypes.JSON },
tmdb_videos: { type: DataTypes.JSON, field: "tmdb_videos" },
watch_providers: { type: DataTypes.JSON, field: "watch_providers" },
alternative_titles: { type: DataTypes.JSON, field: "alternative_titles" },
// ? TV-only TMDB details
tv_type: { type: DataTypes.STRING(30), field: "tv_type" },
created_by: { type: DataTypes.JSON, field: "created_by" },
number_of_seasons: { type: DataTypes.INTEGER, field: "number_of_seasons" },
number_of_episodes: { type: DataTypes.INTEGER, field: "number_of_episodes" },
last_air_date: { type: DataTypes.DATEONLY, field: "last_air_date" },
in_production: { type: DataTypes.BOOLEAN, field: "in_production" },
next_episode_to_air: { type: DataTypes.JSON, field: "next_episode_to_air" },
last_episode_to_air: { type: DataTypes.JSON, field: "last_episode_to_air" },
collection_id: { type: DataTypes.INTEGER, field: "collection_id" },
max_cast: { type: DataTypes.INTEGER, field: "max_cast", defaultValue: 10 },
credit_fetched: { credit_fetched: {
type: DataTypes.BOOLEAN, type: DataTypes.BOOLEAN,
defaultValue: false, defaultValue: false,
field: 'credit_fetched', field: "credit_fetched",
}, },
watchlist: { type: DataTypes.BOOLEAN, defaultValue: false }, watchlist: { type: DataTypes.BOOLEAN, defaultValue: false },
@@ -30,35 +57,49 @@ const Entry = sequelize.define('entry', {
showInCalendar: { showInCalendar: {
type: DataTypes.BOOLEAN, type: DataTypes.BOOLEAN,
defaultValue: true, defaultValue: true,
field: 'show_in_calendar', field: "show_in_calendar",
}, },
autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: 'auto_sync' }, autoSync: { type: DataTypes.BOOLEAN, defaultValue: true, field: "auto_sync" },
note: { type: DataTypes.STRING(2000) }, note: { type: DataTypes.STRING(2000) },
is_tvseries: { type: DataTypes.BOOLEAN, field: 'is_tvseries' }, is_tvseries: { type: DataTypes.BOOLEAN, field: "is_tvseries" },
status: { type: DataTypes.STRING(20) }, status: { type: DataTypes.STRING(20) },
poster_path: { type: DataTypes.STRING(200), field: 'poster_path' }, poster_path: { type: DataTypes.STRING(200), field: "poster_path" },
banner_path: { type: DataTypes.STRING(200), field: 'banner_path' }, banner_path: { type: DataTypes.STRING(200), field: "banner_path" },
date_first_seen: { type: DataTypes.DATEONLY, field: 'date_first_seen' }, date_first_seen: { type: DataTypes.DATEONLY, field: "date_first_seen" },
date_last_seen: { type: DataTypes.DATEONLY, field: 'date_last_seen' }, date_last_seen: { type: DataTypes.DATEONLY, field: "date_last_seen" },
last_fetch: { type: DataTypes.DATEONLY }, last_fetch: { type: DataTypes.DATE },
entry_sync_status: { entry_sync_status: {
type: DataTypes.STRING(50), type: DataTypes.STRING(50),
field: 'entry_sync_status', field: "entry_sync_status",
allowNull: true, allowNull: true,
}, },
director: { type: DataTypes.STRING(200), allowNull: true }, director: { type: DataTypes.STRING(200), allowNull: true },
watch_status: { watch_status: {
type: DataTypes.STRING(20), type: DataTypes.STRING(20),
field: 'watch_status', field: "watch_status",
allowNull: true, allowNull: true,
defaultValue: null, defaultValue: null,
}, },
}); });
// Large JSON columns only needed on the details page; left out of list queries.
Entry.DETAIL_ONLY_ATTRIBUTES = [
"keywords",
"tmdb_videos",
"watch_providers",
"alternative_titles",
"production_companies",
"spoken_languages",
"production_countries",
"created_by",
"next_episode_to_air",
"last_episode_to_air",
];
module.exports = Entry; module.exports = Entry;
+4
View File
@@ -15,6 +15,10 @@ const EntryId = sequelize.define(
tmdb_id: { type: DataTypes.STRING(30) }, tmdb_id: { type: DataTypes.STRING(30) },
imdb_id: { type: DataTypes.STRING(30) }, imdb_id: { type: DataTypes.STRING(30) },
tvdb_id: { type: DataTypes.STRING(30) }, tvdb_id: { type: DataTypes.STRING(30) },
wikidata_id: { type: DataTypes.STRING(30) },
facebook_id: { type: DataTypes.STRING(100) },
instagram_id: { type: DataTypes.STRING(100) },
twitter_id: { type: DataTypes.STRING(100) },
}, },
{ {
timestamps: false, timestamps: false,
+1
View File
@@ -14,6 +14,7 @@ const EntryRating = sequelize.define(
}, },
user_rating: { type: DataTypes.FLOAT }, user_rating: { type: DataTypes.FLOAT },
tmdb_rating: { type: DataTypes.FLOAT }, tmdb_rating: { type: DataTypes.FLOAT },
tmdb_vote_count: { type: DataTypes.INTEGER },
imdb_rating: { type: DataTypes.FLOAT }, imdb_rating: { type: DataTypes.FLOAT },
rotten_tomatoes_rating: { type: DataTypes.FLOAT }, rotten_tomatoes_rating: { type: DataTypes.FLOAT },
}, },
+5
View File
@@ -25,6 +25,11 @@ const Episode = sequelize.define("episode", {
user_rating: { type: DataTypes.FLOAT }, user_rating: { type: DataTypes.FLOAT },
tmdb_rating: { type: DataTypes.FLOAT }, tmdb_rating: { type: DataTypes.FLOAT },
tmdb_vote_count: { type: DataTypes.INTEGER },
production_code: { type: DataTypes.STRING(50) },
crew: { type: DataTypes.JSON },
guest_stars: { type: DataTypes.JSON },
still_path: { type: DataTypes.STRING(200) }, still_path: { type: DataTypes.STRING(200) },
+2
View File
@@ -9,6 +9,8 @@ const Media = sequelize.define("media", {
type: { type: DataTypes.STRING(50) }, type: { type: DataTypes.STRING(50) },
path: { type: DataTypes.STRING(200) }, path: { type: DataTypes.STRING(200) },
// TMDB file_path this image was downloaded from (null for custom uploads)
tmdbPath: { type: DataTypes.STRING(200), field: "tmdb_path" },
isLocal: { type: DataTypes.BOOLEAN, field: "is_local" }, isLocal: { type: DataTypes.BOOLEAN, field: "is_local" },
isSelected: { isSelected: {
+1 -1
View File
@@ -4,7 +4,7 @@ const sequelize = require("../config/database");
const Network = sequelize.define("network", { const Network = sequelize.define("network", {
id: { type: DataTypes.INTEGER, primaryKey: true }, id: { type: DataTypes.INTEGER, primaryKey: true },
name: { type: DataTypes.STRING(30) }, name: { type: DataTypes.STRING(100) },
originCountry: { type: DataTypes.STRING(100), field: "origin_country" }, originCountry: { type: DataTypes.STRING(100), field: "origin_country" },
homepage: { type: DataTypes.STRING(100), field: "homepage" }, homepage: { type: DataTypes.STRING(100), field: "homepage" },
+1
View File
@@ -7,6 +7,7 @@ const People = sequelize.define("peoples", {
tmdb_id: { type: DataTypes.STRING(100) }, tmdb_id: { type: DataTypes.STRING(100) },
name: { type: DataTypes.STRING(100) }, name: { type: DataTypes.STRING(100) },
original_name: { type: DataTypes.STRING(200) },
birthday: { type: DataTypes.DATEONLY }, birthday: { type: DataTypes.DATEONLY },
deathday: { type: DataTypes.DATEONLY, allowNull: true }, deathday: { type: DataTypes.DATEONLY, allowNull: true },
gender: { type: DataTypes.INTEGER }, gender: { type: DataTypes.INTEGER },
+1
View File
@@ -6,6 +6,7 @@ const Season = sequelize.define("season", {
tmdb_id: { type: DataTypes.STRING(30) }, tmdb_id: { type: DataTypes.STRING(30) },
imdb_id: { type: DataTypes.STRING(30) }, imdb_id: { type: DataTypes.STRING(30) },
tvdb_id: { type: DataTypes.STRING(30) },
entry_id: { entry_id: {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
+23
View File
@@ -0,0 +1,23 @@
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
const Video = sequelize.define("video", {
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
title: { type: DataTypes.STRING(500) },
description: { type: DataTypes.TEXT, allowNull: true },
filename: { type: DataTypes.STRING(200) },
original_name: { type: DataTypes.STRING(500), field: "original_name" },
mime_type: { type: DataTypes.STRING(100), field: "mime_type" },
size: { type: DataTypes.BIGINT },
duration: { type: DataTypes.INTEGER, allowNull: true },
thumbnail_path: {
type: DataTypes.STRING(200),
field: "thumbnail_path",
allowNull: true,
},
});
module.exports = Video;
+17
View File
@@ -0,0 +1,17 @@
const { DataTypes } = require("sequelize");
const sequelize = require("../config/database");
// Junction table linking discovery videos to library entries (many-to-many)
const VideoEntry = sequelize.define(
"VideoEntry",
{
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
video_id: { type: DataTypes.INTEGER },
entry_id: { type: DataTypes.INTEGER },
},
{
tableName: "video_entries",
},
);
module.exports = VideoEntry;
+1
View File
@@ -30,6 +30,7 @@
"body-parser": "^1.20.3", "body-parser": "^1.20.3",
"dotenv": "^16.4.7", "dotenv": "^16.4.7",
"express": "^4.21.2", "express": "^4.21.2",
"ffmpeg-static": "^5.3.0",
"jsonwebtoken": "^9.0.3", "jsonwebtoken": "^9.0.3",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
"mysql2": "^3.12.0", "mysql2": "^3.12.0",
+204 -2
View File
@@ -20,6 +20,12 @@ importers:
express: express:
specifier: ^4.21.2 specifier: ^4.21.2
version: 4.21.2 version: 4.21.2
ffmpeg-static:
specifier: ^5.3.0
version: 5.3.0
jsonwebtoken:
specifier: ^9.0.3
version: 9.0.3
multer: multer:
specifier: ^1.4.5-lts.1 specifier: ^1.4.5-lts.1
version: 1.4.5-lts.1 version: 1.4.5-lts.1
@@ -34,7 +40,7 @@ importers:
version: 0.1.4 version: 0.1.4
sequelize: sequelize:
specifier: ^6.37.5 specifier: ^6.37.5
version: 6.37.5(mysql2@3.12.0) version: 6.37.5(mysql2@3.12.0)(supports-color@5.5.0)
sharp: sharp:
specifier: ^0.33.5 specifier: ^0.33.5
version: 0.33.5 version: 0.33.5
@@ -44,6 +50,10 @@ importers:
packages: packages:
'@derhuerst/http-basic@8.2.4':
resolution: {integrity: sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==}
engines: {node: '>=6.0.0'}
'@emnapi/runtime@1.3.1': '@emnapi/runtime@1.3.1':
resolution: {integrity: sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==} resolution: {integrity: sha512-kEBmG8KyqtxJZv+ygbEim+KCGtIq1fC22Ms3S4ziXmYKm8uyoLX0MHONVKwp+9opg390VaKRNt4a7A9NwmpNhw==}
@@ -73,67 +83,79 @@ packages:
resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==} resolution: {integrity: sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-libvips-linux-arm@1.0.5': '@img/sharp-libvips-linux-arm@1.0.5':
resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==} resolution: {integrity: sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-libvips-linux-s390x@1.0.4': '@img/sharp-libvips-linux-s390x@1.0.4':
resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==} resolution: {integrity: sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-libvips-linux-x64@1.0.4': '@img/sharp-libvips-linux-x64@1.0.4':
resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==} resolution: {integrity: sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-libvips-linuxmusl-arm64@1.0.4': '@img/sharp-libvips-linuxmusl-arm64@1.0.4':
resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==} resolution: {integrity: sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl]
'@img/sharp-libvips-linuxmusl-x64@1.0.4': '@img/sharp-libvips-linuxmusl-x64@1.0.4':
resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==} resolution: {integrity: sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl]
'@img/sharp-linux-arm64@0.33.5': '@img/sharp-linux-arm64@0.33.5':
resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==} resolution: {integrity: sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-linux-arm@0.33.5': '@img/sharp-linux-arm@0.33.5':
resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==} resolution: {integrity: sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm] cpu: [arm]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-linux-s390x@0.33.5': '@img/sharp-linux-s390x@0.33.5':
resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==} resolution: {integrity: sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [s390x] cpu: [s390x]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-linux-x64@0.33.5': '@img/sharp-linux-x64@0.33.5':
resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==} resolution: {integrity: sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [glibc]
'@img/sharp-linuxmusl-arm64@0.33.5': '@img/sharp-linuxmusl-arm64@0.33.5':
resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==} resolution: {integrity: sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [arm64] cpu: [arm64]
os: [linux] os: [linux]
libc: [musl]
'@img/sharp-linuxmusl-x64@0.33.5': '@img/sharp-linuxmusl-x64@0.33.5':
resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==} resolution: {integrity: sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
cpu: [x64] cpu: [x64]
os: [linux] os: [linux]
libc: [musl]
'@img/sharp-wasm32@0.33.5': '@img/sharp-wasm32@0.33.5':
resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==} resolution: {integrity: sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==}
@@ -158,6 +180,9 @@ packages:
'@types/ms@2.1.0': '@types/ms@2.1.0':
resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}
'@types/node@10.17.60':
resolution: {integrity: sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==}
'@types/node@22.10.10': '@types/node@22.10.10':
resolution: {integrity: sha512-X47y/mPNzxviAGY5TcYPtYL8JsY3kAq2n8fMmKoRCxq/c4v4pyGNCzM2R6+M5/umG4ZfHuT+sgqDYqWc9rJ6ww==} resolution: {integrity: sha512-X47y/mPNzxviAGY5TcYPtYL8JsY3kAq2n8fMmKoRCxq/c4v4pyGNCzM2R6+M5/umG4ZfHuT+sgqDYqWc9rJ6ww==}
@@ -168,6 +193,10 @@ packages:
resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==}
engines: {node: '>= 0.6'} engines: {node: '>= 0.6'}
agent-base@6.0.2:
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
anymatch@3.1.3: anymatch@3.1.3:
resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==}
engines: {node: '>= 8'} engines: {node: '>= 8'}
@@ -206,6 +235,9 @@ packages:
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'} engines: {node: '>=8'}
buffer-equal-constant-time@1.0.1:
resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}
buffer-from@1.1.2: buffer-from@1.1.2:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
@@ -225,6 +257,9 @@ packages:
resolution: {integrity: sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==} resolution: {integrity: sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
caseless@0.12.0:
resolution: {integrity: sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==}
chokidar@3.6.0: chokidar@3.6.0:
resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==} resolution: {integrity: sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==}
engines: {node: '>= 8.10.0'} engines: {node: '>= 8.10.0'}
@@ -254,6 +289,10 @@ packages:
resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==} resolution: {integrity: sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==}
engines: {'0': node >= 0.8} engines: {'0': node >= 0.8}
concat-stream@2.0.0:
resolution: {integrity: sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==}
engines: {'0': node >= 6.0}
content-disposition@0.5.4: content-disposition@0.5.4:
resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==} resolution: {integrity: sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==}
engines: {node: '>= 0.6'} engines: {node: '>= 0.6'}
@@ -315,11 +354,15 @@ packages:
dottie@2.0.6: dottie@2.0.6:
resolution: {integrity: sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==} resolution: {integrity: sha512-iGCHkfUc5kFekGiqhe8B/mdaurD+lakO9txNnTvKtA6PISrw86LgqHvRzWYPyoE2Ph5aMIrCw9/uko6XHTKCwA==}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
dunder-proto@1.0.1: dunder-proto@1.0.1:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
ecdsa-sig-formatter@1.0.11:
resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}
ee-first@1.1.1: ee-first@1.1.1:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
@@ -331,6 +374,10 @@ packages:
resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==}
engines: {node: '>= 0.8'} engines: {node: '>= 0.8'}
env-paths@2.2.1:
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
es-define-property@1.0.1: es-define-property@1.0.1:
resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}
engines: {node: '>= 0.4'} engines: {node: '>= 0.4'}
@@ -354,6 +401,10 @@ packages:
resolution: {integrity: sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==} resolution: {integrity: sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==}
engines: {node: '>= 0.10.0'} engines: {node: '>= 0.10.0'}
ffmpeg-static@5.3.0:
resolution: {integrity: sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==}
engines: {node: '>=16'}
fill-range@7.1.1: fill-range@7.1.1:
resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
engines: {node: '>=8'} engines: {node: '>=8'}
@@ -426,6 +477,13 @@ packages:
resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==} resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}
engines: {node: '>= 0.8'} engines: {node: '>= 0.8'}
http-response-object@3.0.2:
resolution: {integrity: sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==}
https-proxy-agent@5.0.1:
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
iconv-lite@0.4.24: iconv-lite@0.4.24:
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==} resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'} engines: {node: '>=0.10.0'}
@@ -473,6 +531,37 @@ packages:
isarray@1.0.0: isarray@1.0.0:
resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==}
jsonwebtoken@9.0.3:
resolution: {integrity: sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==}
engines: {node: '>=12', npm: '>=6'}
jwa@2.0.1:
resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==}
jws@4.0.1:
resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==}
lodash.includes@4.3.0:
resolution: {integrity: sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==}
lodash.isboolean@3.0.3:
resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==}
lodash.isinteger@4.0.4:
resolution: {integrity: sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==}
lodash.isnumber@3.0.3:
resolution: {integrity: sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==}
lodash.isplainobject@4.0.6:
resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==}
lodash.isstring@4.0.1:
resolution: {integrity: sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==}
lodash.once@4.1.1:
resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==}
lodash@4.17.21: lodash@4.17.21:
resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}
@@ -540,6 +629,7 @@ packages:
multer@1.4.5-lts.1: multer@1.4.5-lts.1:
resolution: {integrity: sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==} resolution: {integrity: sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==}
engines: {node: '>= 6.0.0'} engines: {node: '>= 6.0.0'}
deprecated: Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.
mysql2@3.12.0: mysql2@3.12.0:
resolution: {integrity: sha512-C8fWhVysZoH63tJbX8d10IAoYCyXy4fdRFz2Ihrt9jtPILYynFEKUUzpp1U7qxzDc3tMbotvaBH+sl6bFnGZiw==} resolution: {integrity: sha512-C8fWhVysZoH63tJbX8d10IAoYCyXy4fdRFz2Ihrt9jtPILYynFEKUUzpp1U7qxzDc3tMbotvaBH+sl6bFnGZiw==}
@@ -577,6 +667,9 @@ packages:
optional@0.1.4: optional@0.1.4:
resolution: {integrity: sha512-gtvrrCfkE08wKcgXaVwQVgwEQ8vel2dc5DDBn9RLQZ3YtmtkBss6A2HY6BnJH4N/4Ku97Ri/SF8sNWE2225WJw==} resolution: {integrity: sha512-gtvrrCfkE08wKcgXaVwQVgwEQ8vel2dc5DDBn9RLQZ3YtmtkBss6A2HY6BnJH4N/4Ku97Ri/SF8sNWE2225WJw==}
parse-cache-control@1.0.1:
resolution: {integrity: sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==}
parseurl@1.3.3: parseurl@1.3.3:
resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}
engines: {node: '>= 0.8'} engines: {node: '>= 0.8'}
@@ -594,6 +687,10 @@ packages:
process-nextick-args@2.0.1: process-nextick-args@2.0.1:
resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}
progress@2.0.3:
resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}
engines: {node: '>=0.4.0'}
proxy-addr@2.0.7: proxy-addr@2.0.7:
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
engines: {node: '>= 0.10'} engines: {node: '>= 0.10'}
@@ -619,6 +716,10 @@ packages:
readable-stream@2.3.8: readable-stream@2.3.8:
resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==} resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==}
readable-stream@3.6.2:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
readdirp@3.6.0: readdirp@3.6.0:
resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==}
engines: {node: '>=8.10.0'} engines: {node: '>=8.10.0'}
@@ -785,6 +886,7 @@ packages:
uuid@8.3.2: uuid@8.3.2:
resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==} resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
hasBin: true hasBin: true
validator@13.12.0: validator@13.12.0:
@@ -804,6 +906,13 @@ packages:
snapshots: snapshots:
'@derhuerst/http-basic@8.2.4':
dependencies:
caseless: 0.12.0
concat-stream: 2.0.0
http-response-object: 3.0.2
parse-cache-control: 1.0.1
'@emnapi/runtime@1.3.1': '@emnapi/runtime@1.3.1':
dependencies: dependencies:
tslib: 2.8.1 tslib: 2.8.1
@@ -890,6 +999,8 @@ snapshots:
'@types/ms@2.1.0': {} '@types/ms@2.1.0': {}
'@types/node@10.17.60': {}
'@types/node@22.10.10': '@types/node@22.10.10':
dependencies: dependencies:
undici-types: 6.20.0 undici-types: 6.20.0
@@ -901,6 +1012,12 @@ snapshots:
mime-types: 2.1.35 mime-types: 2.1.35
negotiator: 0.6.3 negotiator: 0.6.3
agent-base@6.0.2:
dependencies:
debug: 4.4.0(supports-color@5.5.0)
transitivePeerDependencies:
- supports-color
anymatch@3.1.3: anymatch@3.1.3:
dependencies: dependencies:
normalize-path: 3.0.0 normalize-path: 3.0.0
@@ -952,6 +1069,8 @@ snapshots:
dependencies: dependencies:
fill-range: 7.1.1 fill-range: 7.1.1
buffer-equal-constant-time@1.0.1: {}
buffer-from@1.1.2: {} buffer-from@1.1.2: {}
busboy@1.6.0: busboy@1.6.0:
@@ -970,6 +1089,8 @@ snapshots:
call-bind-apply-helpers: 1.0.1 call-bind-apply-helpers: 1.0.1
get-intrinsic: 1.2.7 get-intrinsic: 1.2.7
caseless@0.12.0: {}
chokidar@3.6.0: chokidar@3.6.0:
dependencies: dependencies:
anymatch: 3.1.3 anymatch: 3.1.3
@@ -1011,6 +1132,13 @@ snapshots:
readable-stream: 2.3.8 readable-stream: 2.3.8
typedarray: 0.0.6 typedarray: 0.0.6
concat-stream@2.0.0:
dependencies:
buffer-from: 1.1.2
inherits: 2.0.4
readable-stream: 3.6.2
typedarray: 0.0.6
content-disposition@0.5.4: content-disposition@0.5.4:
dependencies: dependencies:
safe-buffer: 5.2.1 safe-buffer: 5.2.1
@@ -1053,12 +1181,18 @@ snapshots:
es-errors: 1.3.0 es-errors: 1.3.0
gopd: 1.2.0 gopd: 1.2.0
ecdsa-sig-formatter@1.0.11:
dependencies:
safe-buffer: 5.2.1
ee-first@1.1.1: {} ee-first@1.1.1: {}
encodeurl@1.0.2: {} encodeurl@1.0.2: {}
encodeurl@2.0.0: {} encodeurl@2.0.0: {}
env-paths@2.2.1: {}
es-define-property@1.0.1: {} es-define-property@1.0.1: {}
es-errors@1.3.0: {} es-errors@1.3.0: {}
@@ -1107,6 +1241,15 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
ffmpeg-static@5.3.0:
dependencies:
'@derhuerst/http-basic': 8.2.4
env-paths: 2.2.1
https-proxy-agent: 5.0.1
progress: 2.0.3
transitivePeerDependencies:
- supports-color
fill-range@7.1.1: fill-range@7.1.1:
dependencies: dependencies:
to-regex-range: 5.0.1 to-regex-range: 5.0.1
@@ -1184,6 +1327,17 @@ snapshots:
statuses: 2.0.1 statuses: 2.0.1
toidentifier: 1.0.1 toidentifier: 1.0.1
http-response-object@3.0.2:
dependencies:
'@types/node': 10.17.60
https-proxy-agent@5.0.1:
dependencies:
agent-base: 6.0.2
debug: 4.4.0(supports-color@5.5.0)
transitivePeerDependencies:
- supports-color
iconv-lite@0.4.24: iconv-lite@0.4.24:
dependencies: dependencies:
safer-buffer: 2.1.2 safer-buffer: 2.1.2
@@ -1218,6 +1372,44 @@ snapshots:
isarray@1.0.0: {} isarray@1.0.0: {}
jsonwebtoken@9.0.3:
dependencies:
jws: 4.0.1
lodash.includes: 4.3.0
lodash.isboolean: 3.0.3
lodash.isinteger: 4.0.4
lodash.isnumber: 3.0.3
lodash.isplainobject: 4.0.6
lodash.isstring: 4.0.1
lodash.once: 4.1.1
ms: 2.1.3
semver: 7.6.3
jwa@2.0.1:
dependencies:
buffer-equal-constant-time: 1.0.1
ecdsa-sig-formatter: 1.0.11
safe-buffer: 5.2.1
jws@4.0.1:
dependencies:
jwa: 2.0.1
safe-buffer: 5.2.1
lodash.includes@4.3.0: {}
lodash.isboolean@3.0.3: {}
lodash.isinteger@4.0.4: {}
lodash.isnumber@3.0.3: {}
lodash.isplainobject@4.0.6: {}
lodash.isstring@4.0.1: {}
lodash.once@4.1.1: {}
lodash@4.17.21: {} lodash@4.17.21: {}
long@5.2.4: {} long@5.2.4: {}
@@ -1315,6 +1507,8 @@ snapshots:
optional@0.1.4: {} optional@0.1.4: {}
parse-cache-control@1.0.1: {}
parseurl@1.3.3: {} parseurl@1.3.3: {}
path-to-regexp@0.1.12: {} path-to-regexp@0.1.12: {}
@@ -1325,6 +1519,8 @@ snapshots:
process-nextick-args@2.0.1: {} process-nextick-args@2.0.1: {}
progress@2.0.3: {}
proxy-addr@2.0.7: proxy-addr@2.0.7:
dependencies: dependencies:
forwarded: 0.2.0 forwarded: 0.2.0
@@ -1357,6 +1553,12 @@ snapshots:
string_decoder: 1.1.1 string_decoder: 1.1.1
util-deprecate: 1.0.2 util-deprecate: 1.0.2
readable-stream@3.6.2:
dependencies:
inherits: 2.0.4
string_decoder: 1.1.1
util-deprecate: 1.0.2
readdirp@3.6.0: readdirp@3.6.0:
dependencies: dependencies:
picomatch: 2.3.1 picomatch: 2.3.1
@@ -1393,7 +1595,7 @@ snapshots:
sequelize-pool@7.1.0: {} sequelize-pool@7.1.0: {}
sequelize@6.37.5(mysql2@3.12.0): sequelize@6.37.5(mysql2@3.12.0)(supports-color@5.5.0):
dependencies: dependencies:
'@types/debug': 4.1.12 '@types/debug': 4.1.12
'@types/validator': 13.12.2 '@types/validator': 13.12.2
+3
View File
@@ -0,0 +1,3 @@
allowBuilds:
ffmpeg-static: true
sharp: false
+11
View File
@@ -18,6 +18,11 @@ entryRouter.get("/tmdb/top-rated/:type", entryController.getTmdbTopRated);
entryRouter.get("/tmdb/upcoming/movie", entryController.getTmdbUpcoming); entryRouter.get("/tmdb/upcoming/movie", entryController.getTmdbUpcoming);
entryRouter.get("/tmdb/search", entryController.getTmdbSearch); entryRouter.get("/tmdb/search", entryController.getTmdbSearch);
entryRouter.get("/tmdb/preview/:type/:tmdbId", entryController.getTmdbPreview); entryRouter.get("/tmdb/preview/:type/:tmdbId", entryController.getTmdbPreview);
entryRouter.get(
"/tmdb/recommendations/:type/:tmdbId",
entryController.getTmdbRecommendations,
);
entryRouter.get("/tmdb/artwork/:type/:tmdbId", entryController.getTmdbArtwork);
entryRouter.get("/sync-series", entryController.syncSeries); entryRouter.get("/sync-series", entryController.syncSeries);
@@ -31,6 +36,12 @@ entryRouter.delete("/:id", entryController.deleteEntry);
entryRouter.get("/:id/seasons", entryController.getEntrySeasons); entryRouter.get("/:id/seasons", entryController.getEntrySeasons);
entryRouter.get("/:id/credits", entryController.getEntryCredits); entryRouter.get("/:id/credits", entryController.getEntryCredits);
entryRouter.get(
"/:id/recommendations",
entryController.getEntryRecommendations,
);
entryRouter.get("/:id/artwork", entryController.getEntryArtwork);
entryRouter.post("/:id/artwork", entryController.addEntryArtwork);
entryRouter.put("/:id/refresh", entryController.refrechEntry); entryRouter.put("/:id/refresh", entryController.refrechEntry);
entryRouter.put("/:id/fetch-collection", entryController.fetchEntryCollection); entryRouter.put("/:id/fetch-collection", entryController.fetchEntryCollection);
+24
View File
@@ -0,0 +1,24 @@
const express = require("express");
const historyRouter = express.Router();
const historyService = require("../services/historyService");
const asyncWrapper = require("../utils/asyncWrapper");
// ! /history
// * GET - Years that have watches, with movie/episode counts
historyRouter.get(
"/years",
asyncWrapper(async (req, res) => {
res.status(200).json(await historyService.getYears());
}),
);
// * GET - Every movie/episode watch in a year (newest first)
historyRouter.get(
"/:year",
asyncWrapper(async (req, res) => {
res.status(200).json(await historyService.getYear(req.params.year));
}),
);
module.exports = historyRouter;
@@ -0,0 +1,8 @@
const express = require("express");
const homepageIntegrationRouter = express.Router();
const homepageIntegrationController = require("../controllers/homepageIntegrationController");
homepageIntegrationRouter.get("/", homepageIntegrationController.getStats);
module.exports = homepageIntegrationRouter;
+15
View File
@@ -76,4 +76,19 @@ maintenanceRouter.post(
maintenanceController.fixImpossibleSeenDates, maintenanceController.fixImpossibleSeenDates,
); );
// * GET - Count of entries not refreshed in the last ?hours=24 + job status
maintenanceRouter.get("/stale-entries", maintenanceController.getStaleEntries);
// * POST - Start refreshing stale entries in the background (?hours=24)
maintenanceRouter.post(
"/stale-entries/refresh",
maintenanceController.startStaleRefresh,
);
// * DELETE - Cancel the running stale refresh
maintenanceRouter.delete(
"/stale-entries/refresh",
maintenanceController.cancelStaleRefresh,
);
module.exports = maintenanceRouter; module.exports = maintenanceRouter;
+39 -33
View File
@@ -1,39 +1,45 @@
const express = require('express'); const express = require("express");
const collectionRouter = require('./collection.routes'); const collectionRouter = require("./collection.routes");
const entrySeenRouter = require('./entry-seen.routes'); const entrySeenRouter = require("./entry-seen.routes");
const entryRouter = require('./entry.routes'); const entryRouter = require("./entry.routes");
const seasonRouter = require('./season.routes'); const seasonRouter = require("./season.routes");
const episodeSeenRouter = require('./episode-seen.routes'); const episodeSeenRouter = require("./episode-seen.routes");
const settingsRouter = require('./settings.routes'); const settingsRouter = require("./settings.routes");
const maintenanceRouter = require('./maintenance.routes'); const maintenanceRouter = require("./maintenance.routes");
const statisticsRouter = require('./statistics.routes'); const statisticsRouter = require("./statistics.routes");
const mediaRouter = require('./media.routes'); const mediaRouter = require("./media.routes");
const episodeRouter = require('./episode.routes'); const episodeRouter = require("./episode.routes");
const pingRouter = require('./ping.routes'); const pingRouter = require("./ping.routes");
const importRouter = require('./import.routes'); const importRouter = require("./import.routes");
const peopleRouter = require('./people.routes'); const peopleRouter = require("./people.routes");
const aiQueryRouter = require('./ai-query.routes'); const aiQueryRouter = require("./ai-query.routes");
const authRouter = require('./auth.routes'); const authRouter = require("./auth.routes");
const watchBuddyRouter = require('./watch-buddy.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(); const router = express.Router();
router.use('/auth', authRouter); router.use("/auth", authRouter);
router.use('/watch-buddies', watchBuddyRouter); router.use("/watch-buddies", watchBuddyRouter);
router.use('/media', mediaRouter); router.use("/media", mediaRouter);
router.use('/entries', entryRouter); router.use("/entries", entryRouter);
router.use('/collections', collectionRouter); router.use("/collections", collectionRouter);
router.use('/entry-seen', entrySeenRouter); router.use("/entry-seen", entrySeenRouter);
router.use('/seasons', seasonRouter); router.use("/seasons", seasonRouter);
router.use('/episodes', episodeRouter); router.use("/episodes", episodeRouter);
router.use('/episode-seen', episodeSeenRouter); router.use("/episode-seen", episodeSeenRouter);
router.use('/import', importRouter); router.use("/import", importRouter);
router.use('/statistics', statisticsRouter); router.use("/statistics", statisticsRouter);
router.use('/settings', settingsRouter); router.use("/history", historyRouter);
router.use('/maintenance', maintenanceRouter); router.use("/settings", settingsRouter);
router.use('/ping', pingRouter); router.use("/maintenance", maintenanceRouter);
router.use('/people', peopleRouter); router.use("/ping", pingRouter);
router.use('/ai-query', aiQueryRouter); router.use("/people", peopleRouter);
router.use("/ai-query", aiQueryRouter);
router.use("/homepage-integration", homepageIntegrationRouter);
router.use("/discovery-videos", videoRouter);
module.exports = router; module.exports = router;
+3
View File
@@ -19,6 +19,9 @@ seasonRouter.get("/:id/episodes", seasonController.getSeasonEpisodes);
// * PUT - Update a season // * PUT - Update a season
seasonRouter.put("/:id", seasonController.updateSeason); seasonRouter.put("/:id", seasonController.updateSeason);
// * PUT - Refresh a season from TMDB
seasonRouter.put("/:id/refresh", seasonController.refreshSeason);
// * DELETE - Delete a season // * DELETE - Delete a season
seasonRouter.delete("/:id", seasonController.deleteSeason); seasonRouter.delete("/:id", seasonController.deleteSeason);
+17
View File
@@ -0,0 +1,17 @@
const express = require("express");
const videoRouter = express.Router();
const videoController = require("../controllers/videoController.js");
const { videosUpload } = require("../services/mutlerStorageLocations");
const upload = videosUpload.array("videos", 10);
// ! /discovery-videos
videoRouter.get("/", videoController.getVideos);
videoRouter.post("/", upload, videoController.uploadVideos);
videoRouter.put("/:id", videoController.updateVideo);
videoRouter.delete("/:id", videoController.deleteVideo);
videoRouter.get("/:id/thumbnail", videoController.getThumbnail);
videoRouter.get("/:id/stream", videoController.streamVideo);
module.exports = videoRouter;
+4 -2
View File
@@ -21,6 +21,7 @@ process.on("uncaughtException", (error) => {
const relations = require("./config/relations.js"); const relations = require("./config/relations.js");
const sequelizeHooks = require("./config/sequelizeHooks.js"); const sequelizeHooks = require("./config/sequelizeHooks.js");
const { initializeData } = require("./config/dataInitializer.js"); const { initializeData } = require("./config/dataInitializer.js");
const { runMigrations } = require("./config/migrations.js");
const killerRouter = require("./routes/killer.routes.js"); const killerRouter = require("./routes/killer.routes.js");
const errorHandler = require("./middleware/errorHandler"); const errorHandler = require("./middleware/errorHandler");
const authMiddleware = require("./middleware/authMiddleware"); const authMiddleware = require("./middleware/authMiddleware");
@@ -51,7 +52,7 @@ app.use((req, res, next) => {
next(); next();
}); });
// ? other api routes // ? API routes
app.use("/api/v1", authMiddleware, routes); app.use("/api/v1", authMiddleware, routes);
// ? Error handling middleware // ? Error handling middleware
@@ -68,8 +69,9 @@ console.log(`Syncing database schema...`);
sequelize sequelize
// .sync({force: true}) // will drop all tables and recreate them. // .sync({force: true}) // will drop all tables and recreate them.
.sync({ alter: doUpdate }) // will attempt to automatically alter tables to fit the model definitions. .sync({ alter: doUpdate }) // will attempt to automatically alter tables to fit the model definitions.
.then((result) => { .then(async (result) => {
console.log(`Database schema synced.`); console.log(`Database schema synced.`);
await runMigrations();
initializeData(); initializeData();
app.listen(PORT, () => { app.listen(PORT, () => {
+207
View File
@@ -0,0 +1,207 @@
const path = require("path");
const { v4: uuidv4 } = require("uuid");
const Entry = require("../models/Entry");
const EntryId = require("../models/EntryId");
const Media = require("../models/Media");
const BadRequestError = require("../errors/BadRequestError");
const NotFoundError = require("../errors/NotFoundError");
const InternalServerError = require("../errors/InternalServerError");
const configService = require("./configService");
const tmdbService = require("./tmdbService");
const mediaDownloaderService = require("./mediaDownloaderService");
const mediaOptimizerService = require("./mediaOptimizerService");
const { logToFile } = require("./logService");
// TMDB images response key → our Media.type
const ARTWORK_TYPES = {
posters: "poster",
backdrops: "backdrop",
logos: "logo",
};
const MEDIA_TYPES = Object.values(ARTWORK_TYPES);
function mapTmdbImage(image) {
return {
file_path: image.file_path,
width: image.width,
height: image.height,
aspect_ratio: image.aspect_ratio,
language: image.iso_639_1 || null,
vote_average: image.vote_average ?? 0,
vote_count: image.vote_count ?? 0,
};
}
function sortByVotes(a, b) {
return b.vote_count - a.vote_count || b.vote_average - a.vote_average;
}
/** TMDB artwork grouped by type, best-voted first. */
async function fetchTmdbArtwork(tmdbId, isTv) {
const data = await tmdbService.fetchEntryMedia(tmdbId, isTv);
if (!data) {
throw new InternalServerError("Couldn't fetch artwork from TMDB");
}
const result = {};
for (const [tmdbKey, type] of Object.entries(ARTWORK_TYPES)) {
result[`${type}s`] = (data[tmdbKey] ?? [])
.map(mapTmdbImage)
.sort(sortByVotes);
}
return result;
}
class ArtworkService {
constructor() {
if (!ArtworkService.instance) {
ArtworkService.instance = this;
}
return ArtworkService.instance;
}
/** Artwork for an entry that is not in the library (TMDB only). */
async getTmdbArtwork(type, tmdbId) {
const result = await fetchTmdbArtwork(tmdbId, type === "tv");
for (const key of Object.keys(result)) {
result[key] = result[key].map((img) => ({ ...img, in_library: false }));
}
return result;
}
/**
* TMDB artwork merged with the entry's media table. TMDB images we already
* have are flagged `in_library` with their media id; local images that
* don't match a TMDB image (custom uploads, older downloads) are appended.
*/
async getEntryArtwork(entryId) {
const entry = await Entry.findByPk(entryId, {
attributes: ["id", "is_tvseries"],
include: [{ model: EntryId, as: "entryId" }],
});
if (!entry) throw new NotFoundError("Entry not found");
const medias = await Media.findAll({
where: { mediaable: "entry", mediaableId: entryId, type: MEDIA_TYPES },
order: [["id", "ASC"]],
});
const tmdbId = entry.entryId?.tmdb_id;
const tmdb = tmdbId
? await fetchTmdbArtwork(tmdbId, entry.is_tvseries)
: { posters: [], backdrops: [], logos: [] };
const result = {};
for (const type of MEDIA_TYPES) {
const key = `${type}s`;
const ofType = medias.filter((m) => m.type === type);
const byTmdbPath = new Map(
ofType.filter((m) => m.tmdbPath).map((m) => [m.tmdbPath, m]),
);
const merged = tmdb[key].map((img) => {
const media = byTmdbPath.get(img.file_path);
return {
...img,
in_library: !!media,
media_id: media?.id ?? null,
media_path: media?.path ?? null,
is_selected: !!media?.isSelected,
};
});
const localOnly = ofType
.filter(
(m) =>
!m.tmdbPath || !tmdb[key].some((i) => i.file_path === m.tmdbPath),
)
.map((m) => ({
file_path: null,
width: null,
height: null,
aspect_ratio: null,
language: null,
vote_average: 0,
vote_count: 0,
in_library: true,
media_id: m.id,
media_path: m.path,
is_selected: !!m.isSelected,
is_custom: !!m.isCustom,
}));
// Library images first so what you already have is easy to find
result[key] = [
...localOnly,
...merged.filter((i) => i.in_library),
...merged.filter((i) => !i.in_library),
];
}
return result;
}
/**
* Downloads a TMDB image into the entry's media table. If the entry has no
* selected image of that type yet, the new one becomes selected.
* @param {number} entryId
* @param {{type: "poster"|"backdrop"|"logo", file_path: string}} data
*/
async addEntryArtwork(entryId, { type, file_path }) {
if (!MEDIA_TYPES.includes(type)) {
throw new BadRequestError(`Invalid artwork type: ${type}`);
}
if (!file_path || !/^\/[\w.-]+$/.test(file_path)) {
throw new BadRequestError("Invalid TMDB file path");
}
const entry = await Entry.findByPk(entryId, { attributes: ["id"] });
if (!entry) throw new NotFoundError("Entry not found");
const where = { mediaable: "entry", mediaableId: entryId, type };
const existing = await Media.findOne({
where: { ...where, tmdbPath: file_path },
});
if (existing) return existing;
configService.createMediaFolders();
const extension = file_path.split(".").pop();
const filename = `${uuidv4()}.${extension}`;
const dir = path.join(
configService.getSettings().userDataPath,
"images",
"entries",
`${type}s`,
);
await mediaDownloaderService.downloadImage(
`https://image.tmdb.org/t/p/original${file_path}`,
path.join(dir, filename),
);
const hasSelected = await Media.count({
where: { ...where, isSelected: true },
});
const media = await Media.create({
...where,
path: filename,
tmdbPath: file_path,
isLocal: true,
isSelected: hasSelected === 0,
isCustom: false,
});
mediaOptimizerService
.doGeneratePreview("entries", `${type}s`, filename)
.catch((err) =>
logToFile(`Artwork | Error generating preview for ${filename}: ${err}`),
);
logToFile(`Artwork | Added ${type} ${file_path} to entry ${entryId}`);
return media;
}
}
module.exports = new ArtworkService();
+1
View File
@@ -98,6 +98,7 @@ class CollectionManager {
mediaableId: collection.id, mediaableId: collection.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true, isLocal: true,
isSelected: true, isSelected: true,
}); });
+15
View File
@@ -120,6 +120,7 @@ class ConfigService {
"peoples", "peoples",
"profiles", "profiles",
); );
const videosDir = path.join(dataPath, "videos");
fs.mkdirSync(posterDir, { recursive: true }); fs.mkdirSync(posterDir, { recursive: true });
fs.mkdirSync(backdropDir, { recursive: true }); fs.mkdirSync(backdropDir, { recursive: true });
@@ -129,6 +130,7 @@ class ConfigService {
fs.mkdirSync(seasonsPostersDir, { recursive: true }); fs.mkdirSync(seasonsPostersDir, { recursive: true });
fs.mkdirSync(episodesStillsDir, { recursive: true }); fs.mkdirSync(episodesStillsDir, { recursive: true });
fs.mkdirSync(peopleProfilesDir, { recursive: true }); fs.mkdirSync(peopleProfilesDir, { recursive: true });
fs.mkdirSync(videosDir, { recursive: true });
} }
getTmdbApiUrl() { getTmdbApiUrl() {
@@ -138,6 +140,19 @@ class ConfigService {
getTmdbApiKey() { getTmdbApiKey() {
return this.settings.tmdbApiKey; return this.settings.tmdbApiKey;
} }
getNamedTokens() {
const tokens = this.settings.namedTokens || [];
const now = new Date();
return tokens.filter((token) => {
if (!token.value) return false;
if (token.endDate) {
const end = new Date(token.endDate);
if (end < now) return false;
}
return true;
});
}
} }
// const instance = new ConfigService(); // const instance = new ConfigService();
+45 -101
View File
@@ -28,6 +28,13 @@ const entryService = require("./entryService");
const mediaManager = require("./mediaManager.js"); const mediaManager = require("./mediaManager.js");
const networkService = require("./networkService.js"); const networkService = require("./networkService.js");
const InternalServerError = require("../errors/InternalServerError.js"); const InternalServerError = require("../errors/InternalServerError.js");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
} = require("../mappers/entryMapper.js");
const _collectionManager = collectionManager; const _collectionManager = collectionManager;
const _entryService = entryService; const _entryService = entryService;
@@ -107,79 +114,50 @@ class EntryManager {
} }
// ! the refrech logic // ! the refrech logic
let newData = { const savedEntry = await _entryService.updateEntryById(
title: entryData.title || entryData.name, id,
original_title: entryData.original_title || entryData.original_name, mapEntryFields(entryData),
release_date: entryData.release_date || entryData.first_air_date, false,
release_status: entryData.status, );
runtime: entryData.runtime || null,
tagline: entryData.tagline || null,
storyline: entryData.overview,
country:
entryData.production_countries.length > 0
? entryData.production_countries[0].name
: null,
status: entryData.status,
poster_path: entryData.poster_path,
banner_path: entryData.backdrop_path,
last_fetch: new Date(),
};
const savedEntry = await _entryService.updateEntryById(id, newData, false);
// * updating ids // * updating ids
// TODO: get more ids await oldEntry.entryId.update(mapEntryIds(entryData));
await oldEntry.entryId.update({
imdb_id: entryData.imdb_id,
});
// * updating ratings // * updating ratings
await oldEntry.entryRating.update({ await oldEntry.entryRating.update(mapEntryRatings(entryData));
tmdb_rating: entryData.vote_average,
});
// * updating genres // * syncing genres (add new ones, drop ones TMDB no longer lists)
const currentGenresIds = oldEntry.genres.map((genre) => genre.id); const currentGenresIds = oldEntry.genres.map((genre) => genre.id);
entryData.genres.forEach(async (genre) => { const newGenresIds = entryData.genres.map((genre) => genre.id);
// if the entry already has this genre then skip for (const genreId of newGenresIds) {
if (currentGenresIds.includes(genre.id)) return; if (currentGenresIds.includes(genreId)) continue;
await EntryGenre.create({ genre_id: genreId, entry_id: savedEntry.id });
// otherwise assign the genre to the entry }
await EntryGenre.create({ const removedGenresIds = currentGenresIds.filter(
genre_id: genre.id, (genreId) => !newGenresIds.includes(genreId),
entry_id: savedEntry.id, );
if (removedGenresIds.length) {
await EntryGenre.destroy({
where: { entry_id: savedEntry.id, genre_id: removedGenresIds },
}); });
}); }
// * networks // * syncing networks (also refreshes each network's name/logo/country)
if (entryData.networks) { if (entryData.networks) {
const oldNetworksIds = oldEntry.networks.map((network) => network.id); const networks = [];
for (const networkData of entryData.networks) { for (const networkData of entryData.networks) {
// If the entry already has this network, skip it const [network] =
if (oldNetworksIds.includes(networkData.id)) continue;
// Create or update the network
const [oldNetwork, newNetwork] =
await _networkService.createOrUpdateNetwork(networkData); await _networkService.createOrUpdateNetwork(networkData);
let network = oldNetwork || newNetwork;
if (!network) { if (!network) {
throw new NotFoundError("Network not found"); throw new NotFoundError("Network not found");
} }
networks.push(network);
// Associate the new network with the entry
await oldEntry.addNetwork(network);
} }
await oldEntry.setNetworks(networks);
} }
// * For TV-Series (Seasons & Episodes) // * For TV-Series (Seasons & Episodes)
if (oldEntry.is_tvseries) { if (oldEntry.is_tvseries) {
// ? Only refrech if the series's status is not 'Ended'
// ? and atleast 48 hours has passed
// * Update or insert seasons for the entry // * Update or insert seasons for the entry
for (const season of entryData.seasons) { for (const season of entryData.seasons) {
// fetch new season data from tmdb // fetch new season data from tmdb
@@ -187,6 +165,7 @@ class EntryManager {
entryData.id, entryData.id,
season.season_number, season.season_number,
); );
if (!seasonData) continue;
// Fetch existing season if it exists (using tmdb_id) // Fetch existing season if it exists (using tmdb_id)
let existingSeason = await Season.findOne({ let existingSeason = await Season.findOne({
@@ -198,31 +177,12 @@ class EntryManager {
// If the season exists, update it; otherwise, create a new season // If the season exists, update it; otherwise, create a new season
if (existingSeason) { if (existingSeason) {
// Update existing season data await existingSeason.update(mapSeasonFields(seasonData));
existingSeason.tmdb_id = seasonData.id;
existingSeason.name = seasonData.name;
existingSeason.overview = seasonData.overview;
existingSeason.episode_count = seasonData.episodes.length;
existingSeason.air_date = seasonData.air_date;
existingSeason.tmdb_rating = seasonData.vote_average;
existingSeason.poster_path = seasonData.poster_path;
existingSeason.banner_path = null;
// Save the updated season
await existingSeason.save();
} else { } else {
// Create a new season
existingSeason = await Season.create({ existingSeason = await Season.create({
tmdb_id: seasonData.id, ...mapSeasonFields(seasonData),
entry_id: oldEntry.id, entry_id: oldEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0, user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null, banner_path: null,
}); });
} }
@@ -242,31 +202,11 @@ class EntryManager {
// If the episode exists, update it; otherwise, create a new episode // If the episode exists, update it; otherwise, create a new episode
if (existingEpisode) { if (existingEpisode) {
// Update existing episode data await existingEpisode.update(mapEpisodeFields(episode));
existingEpisode.tmdb_id = episode.tmdb_id;
existingEpisode.name = episode.name;
existingEpisode.overview = episode.overview;
existingEpisode.episode_type = episode.episode_type;
existingEpisode.runtime = episode.runtime;
existingEpisode.air_date = episode.air_date;
existingEpisode.tmdb_rating = episode.vote_average;
existingEpisode.still_path = episode.still_path;
// Updated episode
await existingEpisode.save();
} else { } else {
// Create a new episode
existingEpisode = await Episode.create({ existingEpisode = await Episode.create({
tmdb_id: episode.id, ...mapEpisodeFields(episode),
season_id: existingSeason.id, season_id: existingSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
}); });
} }
@@ -315,6 +255,7 @@ class EntryManager {
return { return {
tmdb_id: credit.id, tmdb_id: credit.id,
name: credit.name, name: credit.name,
original_name: credit.original_name || null,
gender: credit.gender || null, gender: credit.gender || null,
popularity: credit.popularity, popularity: credit.popularity,
known_for_department: credit.known_for_department || null, known_for_department: credit.known_for_department || null,
@@ -513,10 +454,12 @@ class EntryManager {
console.log(`[CREDITS] No changes for entry ${oldEntry.id}`); console.log(`[CREDITS] No changes for entry ${oldEntry.id}`);
} }
// Set director from processed credits // Set director from processed credits (handles both movie & TV aggregate format)
const directorCredit = allCredits.find( const directorCredit = allCredits.find((c) => {
(c) => c.cast_type === "crew" && c.job === "Director", if (c.cast_type !== "crew") return false;
); const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job];
return jobs.includes("Director");
});
if (directorCredit) { if (directorCredit) {
oldEntry.director = directorCredit.name || null; oldEntry.director = directorCredit.name || null;
await oldEntry.save(); await oldEntry.save();
@@ -559,6 +502,7 @@ class EntryManager {
mediaableId: oldEntry.id, mediaableId: oldEntry.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true, isLocal: true,
isSelected: true, isSelected: true,
}); });
+78 -63
View File
@@ -20,6 +20,13 @@ const networkService = require("./networkService.js");
const Cast = require("../models/Credit.js"); const Cast = require("../models/Credit.js");
const People = require("../models/People.js"); const People = require("../models/People.js");
const Credit = require("../models/Credit.js"); const Credit = require("../models/Credit.js");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
} = require("../mappers/entryMapper.js");
const _mediaManager = mediaManager; const _mediaManager = mediaManager;
const _mediaOptimizerService = mediaOptimizerService; const _mediaOptimizerService = mediaOptimizerService;
@@ -35,6 +42,7 @@ class EntryService {
async getAllEntries() { async getAllEntries() {
const entries = await Entry.findAll({ const entries = await Entry.findAll({
attributes: { exclude: Entry.DETAIL_ONLY_ATTRIBUTES },
include: [ include: [
{ model: EntryId, as: "entryId" }, { model: EntryId, as: "entryId" },
{ model: EntryRating, as: "entryRating" }, { model: EntryRating, as: "entryRating" },
@@ -154,40 +162,20 @@ class EntryService {
console.log("entryService > createEntry > is_tvseries: ", is_tvseries); console.log("entryService > createEntry > is_tvseries: ", is_tvseries);
let movie = Entry.build({ let movie = Entry.build({
title: data.title || data.name, ...mapEntryFields(data),
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date,
release_status: data.status,
runtime: data.runtime || null,
tagline: data.tagline || null,
storyline: data.overview,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
is_tvseries: is_tvseries, is_tvseries: is_tvseries,
watchlist: true, watchlist: true,
status: data.status,
genres: data.genre_ids,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date(),
}); });
let savedEntry = await movie.save(); let savedEntry = await movie.save();
console.log("entryService > createEntry > savedEntry: ", savedEntry); console.log("entryService > createEntry > savedEntry: ", savedEntry.id);
// ? ids // ? ids
await EntryId.create({ await EntryId.create({
entry_id: savedEntry.id, entry_id: savedEntry.id,
tmdb_id: data.id, tmdb_id: data.id,
imdb_id: data.imdb_id, ...mapEntryIds(data),
}); });
// ? genres // ? genres
@@ -218,7 +206,7 @@ class EntryService {
await EntryRating.create({ await EntryRating.create({
entry_id: savedEntry.id, entry_id: savedEntry.id,
user_rating: 0, user_rating: 0,
tmdb_rating: data.vote_average, ...mapEntryRatings(data),
}); });
// ! seasons & episodes for tv series // ! seasons & episodes for tv series
@@ -227,21 +215,12 @@ class EntryService {
let seasons = []; let seasons = [];
for (const season of data.seasons) { for (const season of data.seasons) {
let seasonData = await fetchSeasonData(data.id, season.season_number); let seasonData = await fetchSeasonData(data.id, season.season_number);
if (!seasonData) continue;
const savedSeason = await Season.create({ const savedSeason = await Season.create({
tmdb_id: seasonData.id, ...mapSeasonFields(seasonData),
entry_id: savedEntry.id, entry_id: savedEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0, user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null, banner_path: null,
}); });
@@ -251,20 +230,8 @@ class EntryService {
let episodes = []; let episodes = [];
for (const episode of seasonData.episodes) { for (const episode of seasonData.episodes) {
const savedEpisode = await Episode.create({ const savedEpisode = await Episode.create({
tmdb_id: episode.id, ...mapEpisodeFields(episode),
season_id: savedSeason.id, season_id: savedSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
}); });
episodes.push(savedEpisode); episodes.push(savedEpisode);
@@ -293,6 +260,7 @@ class EntryService {
const tmdbIds = [...new Set(allCredits.map((c) => c.id))]; const tmdbIds = [...new Set(allCredits.map((c) => c.id))];
// — FETCH EXISTING PEOPLE —
const existingPeopleList = await People.findAll({ const existingPeopleList = await People.findAll({
where: { tmdb_id: tmdbIds }, where: { tmdb_id: tmdbIds },
}); });
@@ -300,6 +268,7 @@ class EntryService {
existingPeopleList.map((p) => [p.tmdb_id, p]), existingPeopleList.map((p) => [p.tmdb_id, p]),
); );
// — CREATE NEW PEOPLE —
const newPeopleData = tmdbIds const newPeopleData = tmdbIds
.filter((id) => !existingPeopleMap[id]) .filter((id) => !existingPeopleMap[id])
.map((id) => { .map((id) => {
@@ -307,6 +276,7 @@ class EntryService {
return { return {
tmdb_id: credit.id, tmdb_id: credit.id,
name: credit.name, name: credit.name,
original_name: credit.original_name || null,
gender: credit.gender || null, gender: credit.gender || null,
popularity: credit.popularity, popularity: credit.popularity,
known_for_department: credit.known_for_department || null, known_for_department: credit.known_for_department || null,
@@ -316,36 +286,80 @@ class EntryService {
}; };
}); });
if (newPeopleData.length) {
console.log(`[PEOPLE] Adding ${newPeopleData.length} new people...`);
}
const createdPeople = await People.bulkCreate(newPeopleData); const createdPeople = await People.bulkCreate(newPeopleData);
for (const person of createdPeople) { for (const person of createdPeople) {
console.log(`[PEOPLE] Added: ${person.name} (tmdb_id=${person.tmdb_id})`);
existingPeopleMap[person.tmdb_id] = person; existingPeopleMap[person.tmdb_id] = person;
} }
const newCredits = allCredits.map((c) => { // — BUILD NEW CREDITS —
const newCredits = [];
for (const c of allCredits) {
const person = existingPeopleMap[c.id]; const person = existingPeopleMap[c.id];
return { if (!person) continue;
// Detect TV aggregate format (roles/jobs arrays) vs movie flat format.
const character =
c.cast_type === "cast"
? Array.isArray(c.roles)
? c.roles
.map((r) => r.character)
.filter(Boolean)
.join("; ") || null
: c.character || null
: null;
const job =
c.cast_type === "crew"
? Array.isArray(c.jobs)
? c.jobs
.map((j) => j.job)
.filter(Boolean)
.join("; ") || null
: c.job || null
: null;
const tmdbCreditId = Array.isArray(c.roles)
? c.roles?.[0]?.credit_id
: Array.isArray(c.jobs)
? c.jobs?.[0]?.credit_id
: c.credit_id;
newCredits.push({
entry_id: savedEntry.id, entry_id: savedEntry.id,
people_id: person.id, people_id: person.id,
tmdb_credit_id: c.credit_id, tmdb_credit_id: tmdbCreditId,
character: c.cast_type === "cast" ? c.character : null, character,
order: c.cast_type === "cast" ? c.order : null, order: c.cast_type === "cast" ? c.order : null,
profile_path: person.profile_path || null, episode_count: c.total_episode_count ?? null,
adult: person.adult || false, profile_path: person.profile_path,
adult: person.adult,
cast_type: c.cast_type, cast_type: c.cast_type,
department: c.cast_type === "crew" ? c.department || null : null, department: c.cast_type === "crew" ? c.department || null : null,
job: c.cast_type === "crew" ? c.job || null : null, job,
}; });
}); }
await Credit.bulkCreate(newCredits); await Credit.bulkCreate(newCredits);
console.log(
`[CREDITS] Inserted ${newCredits.length} credits for entry ${savedEntry.id}`,
);
savedEntry.credit_fetched = true; savedEntry.credit_fetched = true;
// Extract director name from credits // Extract director name from processed credits (handles both movie & TV aggregate format)
const directorData = allCredits.find( const directorCredit = allCredits.find((c) => {
(c) => c.cast_type === "crew" && c.job === "Director", if (c.cast_type !== "crew") return false;
); const jobs = Array.isArray(c.jobs) ? c.jobs.map((j) => j.job) : [c.job];
savedEntry.director = directorData?.name || null; return jobs.includes("Director");
});
savedEntry.director = directorCredit?.name || null;
await savedEntry.save(); await savedEntry.save();
@@ -361,6 +375,7 @@ class EntryService {
mediaableId: savedEntry.id, mediaableId: savedEntry.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true, isLocal: true,
isSelected: true, isSelected: true,
}); });
+208
View File
@@ -0,0 +1,208 @@
const { Op } = require("sequelize");
const sequelize = require("../config/database");
const Entry = require("../models/Entry");
const EntryRating = require("../models/EntryRating");
const EntrySeen = require("../models/EntrySeen");
const Episode = require("../models/Episode");
const EpisodeSeen = require("../models/EpisodeSeen");
const Genre = require("../models/Genre");
const Media = require("../models/Media");
const Network = require("../models/Network");
const Season = require("../models/Season");
const WatchBuddy = require("../models/WatchBuddy");
const BadRequestError = require("../errors/BadRequestError");
const ENTRY_ATTRIBUTES = [
"id",
"title",
"is_tvseries",
"poster_path",
"banner_path",
"runtime",
"release_date",
"original_language",
];
const BUDDY_INCLUDE = {
model: WatchBuddy,
as: "buddies",
attributes: ["id", "name"],
through: { attributes: [] },
};
class HistoryService {
constructor() {
if (!HistoryService.instance) {
HistoryService.instance = this;
}
return HistoryService.instance;
}
/** Years that have watches, newest first, with movie/episode counts. */
async getYears() {
const [rows] = await sequelize.query(`
SELECT y AS year, SUM(movies) AS movies, SUM(episodes) AS episodes FROM (
SELECT YEAR(date_seen) AS y, COUNT(*) AS movies, 0 AS episodes
FROM entrySeens WHERE date_seen IS NOT NULL GROUP BY y
UNION ALL
SELECT YEAR(date_seen) AS y, 0 AS movies, COUNT(*) AS episodes
FROM episodeSeens WHERE date_seen IS NOT NULL GROUP BY y
) t GROUP BY y ORDER BY y DESC
`);
return rows.map((r) => ({
year: Number(r.year),
movies: Number(r.movies),
episodes: Number(r.episodes),
}));
}
/**
* Every watch in a year, newest first. Entries are returned once in
* `entries` (keyed by id) and referenced by `entry_id` from each event.
* @param {number} year
*/
async getYear(year) {
year = Number(year);
if (!Number.isInteger(year) || year < 1900 || year > 3000) {
throw new BadRequestError("Invalid year");
}
const range = {
[Op.gte]: new Date(year, 0, 1),
[Op.lt]: new Date(year + 1, 0, 1),
};
const [movieSeens, episodeSeens] = await Promise.all([
EntrySeen.findAll({
where: { date_seen: range },
attributes: ["id", "entry_id", "date_seen", "accuracy"],
include: [BUDDY_INCLUDE],
}),
EpisodeSeen.findAll({
where: { date_seen: range },
attributes: ["id", "entry_id", "episode_id", "date_seen", "accuracy"],
include: [
BUDDY_INCLUDE,
{
model: Episode,
attributes: [
"id",
"name",
"episode_number",
"runtime",
"still_path",
"season_id",
],
include: [
{ model: Season, as: "season", attributes: ["season_number"] },
],
},
],
}),
]);
const entryIds = [
...new Set([
...movieSeens.map((s) => s.entry_id),
...episodeSeens.map((s) => s.entry_id),
]),
].filter(Boolean);
const entries = entryIds.length
? await Entry.findAll({
where: { id: entryIds },
attributes: ENTRY_ATTRIBUTES,
include: [
{
model: Media,
as: "medias",
attributes: ["id", "type", "path", "isSelected"],
where: { type: "poster", isSelected: true },
required: false,
},
{
model: Genre,
as: "genres",
attributes: ["id", "name"],
through: { attributes: [] },
},
{
model: Network,
as: "networks",
attributes: ["id", "name", "logoPath"],
through: { attributes: [] },
},
{
model: EntryRating,
as: "entryRating",
attributes: ["user_rating", "tmdb_rating"],
},
],
})
: [];
const buddies = (seen) =>
(seen.buddies ?? []).map((b) => ({ id: b.id, name: b.name }));
const events = [
...movieSeens.map((s) => ({
id: `m-${s.id}`,
seen_id: s.id,
kind: "movie",
entry_id: s.entry_id,
date_seen: s.date_seen,
accuracy: s.accuracy,
buddies: buddies(s),
})),
...episodeSeens.map((s) => {
const ep = s.episode;
return {
id: `e-${s.id}`,
seen_id: s.id,
kind: "episode",
entry_id: s.entry_id,
date_seen: s.date_seen,
accuracy: s.accuracy,
buddies: buddies(s),
episode: ep
? {
id: ep.id,
name: ep.name,
season_id: ep.season_id,
season_number: ep.season?.season_number ?? null,
episode_number: ep.episode_number,
runtime: ep.runtime,
still_path: ep.still_path,
}
: null,
};
}),
].sort((a, b) => new Date(b.date_seen) - new Date(a.date_seen));
return {
year,
entries: Object.fromEntries(
entries.map((e) => {
const plain = e.get({ plain: true });
return [
plain.id,
{
...plain,
genres: plain.genres?.map((g) => g.name) ?? [],
networks:
plain.networks?.map((n) => ({
id: n.id,
name: n.name,
logo_path: n.logoPath,
})) ?? [],
},
];
}),
),
events,
};
}
}
module.exports = new HistoryService();
+198 -12
View File
@@ -6,6 +6,7 @@ const Media = require("../models/Media");
const People = require("../models/People"); const People = require("../models/People");
const Credit = require("../models/Credit"); const Credit = require("../models/Credit");
const Entry = require("../models/Entry"); const Entry = require("../models/Entry");
const { Op } = require("sequelize");
const { logToFile } = require("./logService"); const { logToFile } = require("./logService");
const configService = require("./configService"); const configService = require("./configService");
@@ -252,14 +253,18 @@ class MaintenanceService {
/** /**
* Find and optionally remove duplicate credits. * Find and optionally remove duplicate credits.
* A duplicate is the same person in the same entry with the same role. *
* For cast: same character. For crew: same job. * Pass 1: Role-level — same (entry, person, type, role).
* Pass 2: Type-level — same (entry, person, type) but different roles.
* Keeps the credit WITH a role; if both have roles, keeps newest ID.
*
* @param {boolean} [dry=false] - if true only count, if false also delete * @param {boolean} [dry=false] - if true only count, if false also delete
*/ */
async cleanDuplicateCredits(dry = false) { async cleanDuplicateCredits(dry = false) {
const { Sequelize } = require("sequelize"); const { Sequelize } = require("sequelize");
const duplicates = await Credit.findAll({ // ── Pass 1: Exact role-level duplicates ──
const duplicateGroups = await Credit.findAll({
attributes: [ attributes: [
"entry_id", "entry_id",
"people_id", "people_id",
@@ -274,11 +279,11 @@ class MaintenanceService {
raw: true, raw: true,
}); });
let duplicateGroups = duplicates.length; let pass1Groups = duplicateGroups.length;
let deletedCount = 0; let deletedCount = 0;
if (!dry) { if (!dry) {
for (const row of duplicates) { for (const row of duplicateGroups) {
const idList = row.ids const idList = row.ids
.split(",") .split(",")
.map(Number) .map(Number)
@@ -290,24 +295,112 @@ class MaintenanceService {
} }
} }
const totalDupes = duplicates.reduce( const pass1Dupes = duplicateGroups.reduce(
(sum, r) => sum + parseInt(r.cnt) - 1, (sum, r) => sum + parseInt(r.cnt) - 1,
0, 0,
); );
if (dry) // ── Pass 2: Type-level duplicates (same person/entry/type, different roles) ──
const typeDupes = await Credit.findAll({
attributes: [
"entry_id",
"people_id",
"cast_type",
[Sequelize.fn("COUNT", Sequelize.col("id")), "cnt"],
[Sequelize.fn("GROUP_CONCAT", Sequelize.col("id")), "ids"],
[
Sequelize.fn(
"GROUP_CONCAT",
Sequelize.fn(
"COALESCE",
Sequelize.col("character"),
Sequelize.col("job"),
),
),
"roles",
],
],
group: ["entry_id", "people_id", "cast_type"],
having: Sequelize.literal("COUNT(id) > 1"),
raw: true,
});
let pass2Groups = typeDupes.length;
let pass2Deleted = 0;
if (!dry) {
for (const row of typeDupes) {
const idList = row.ids.split(",").map(Number);
// Fetch these credits to inspect their roles
const credits = await Credit.findAll({
where: { id: idList },
order: [["id", "DESC"]],
});
// Separate: credits with roles vs without
const withRole = credits.filter((c) => {
if (c.cast_type === "cast") return c.character && c.character.trim();
return c.job && c.job.trim();
});
const withoutRole = credits.filter((c) => {
if (c.cast_type === "cast")
return !c.character || !c.character.trim();
return !c.job || !c.job.trim();
});
let keep;
const toDelete = [];
if (withRole.length > 0 && withoutRole.length > 0) {
// Prefer the one WITH a role; keep the newest among those with roles.
// Delete all without-role entries.
keep = withRole[0]; // already sorted by id DESC
toDelete.push(...withoutRole.map((c) => c.id));
// If there are multiple with-role, delete the older ones
if (withRole.length > 1) {
toDelete.push(...withRole.slice(1).map((c) => c.id));
}
} else if (withRole.length > 1) {
// All have roles — keep newest, delete older
keep = withRole[0];
toDelete.push(...withRole.slice(1).map((c) => c.id));
} else {
// None have roles — keep newest, delete older
keep = withoutRole[0];
toDelete.push(...withoutRole.slice(1).map((c) => c.id));
}
if (toDelete.length > 0) {
await Credit.destroy({ where: { id: toDelete } });
pass2Deleted += toDelete.length;
}
}
}
const pass2Dupes = typeDupes.reduce(
(sum, r) => sum + parseInt(r.cnt) - 1,
0,
);
const totalGroups = pass1Groups + pass2Groups;
const totalDupes = pass1Dupes + pass2Dupes;
const totalDeleted = deletedCount + pass2Deleted;
if (dry) {
logToFile( logToFile(
`Dry duplicate credits check: ${duplicateGroups} groups, ${totalDupes} duplicates`, `Dry duplicate credits: Pass1=${pass1Groups} groups (${pass1Dupes} dupes), Pass2=${pass2Groups} groups (${pass2Dupes} dupes) → ${totalGroups} groups, ${totalDupes} duplicates`,
); );
else } else {
logToFile( logToFile(
`Cleaned duplicate credits: ${deletedCount} removed from ${duplicateGroups} groups`, `Cleaned duplicate credits: Pass1=${pass1Groups} groups (${deletedCount} deleted), Pass2=${pass2Groups} groups (${pass2Deleted} deleted) → ${totalDeleted} total removed`,
); );
}
return { return {
groups: duplicateGroups, groups: totalGroups,
duplicates: totalDupes, duplicates: totalDupes,
deleted: deletedCount, deleted: totalDeleted,
}; };
} }
@@ -477,6 +570,99 @@ class MaintenanceService {
); );
return { count: impossibleEntries.length }; return { count: impossibleEntries.length };
} }
/**
* Entries due for a TMDB refresh: never fetched, or last fetched more than
* `hours` ago. Entries with auto sync turned off are skipped.
* @param {number} [hours=24]
*/
async getStaleEntries(hours = 24) {
const cutoff = new Date(Date.now() - hours * 60 * 60 * 1000);
return Entry.findAll({
attributes: ["id", "title", "last_fetch"],
where: {
autoSync: { [Op.not]: false },
[Op.or]: [{ last_fetch: null }, { last_fetch: { [Op.lt]: cutoff } }],
},
order: [["last_fetch", "ASC"]],
});
}
/** Current/last stale refresh job, for the status endpoint. */
getStaleRefreshStatus() {
const job = this.staleRefreshJob;
if (!job) return { running: false };
return { ...job, failed: job.failed.slice(-50) };
}
/**
* Starts refreshing every stale entry in the background, one at a time.
* TMDB requests go through tmdbService's rate limiter, so a large library
* is spread out instead of hammering the API.
* @param {number} [hours=24]
* @returns {Object} the job status, or `{ alreadyRunning: true, ... }`
*/
async startStaleRefresh(hours = 24) {
if (this.staleRefreshJob?.running) {
return { alreadyRunning: true, ...this.getStaleRefreshStatus() };
}
const entries = await this.getStaleEntries(hours);
const job = {
running: true,
cancelRequested: false,
hours,
total: entries.length,
done: 0,
succeeded: 0,
failed: [],
current: null,
startedAt: new Date(),
finishedAt: null,
};
this.staleRefreshJob = job;
logToFile(`Stale refresh started: ${entries.length} entries (> ${hours}h)`);
// Required lazily: entryManager pulls in most of the services layer.
const entryManager = require("./entryManager");
(async () => {
for (const entry of entries) {
if (job.cancelRequested) break;
job.current = { id: entry.id, title: entry.title };
try {
await entryManager.refrechEntryById(entry.id, false);
job.succeeded++;
} catch (error) {
job.failed.push({
id: entry.id,
title: entry.title,
error: error.message,
});
logToFile(
`Stale refresh failed for entry ${entry.id} (${entry.title}): ${error.message}`,
);
}
job.done++;
}
job.running = false;
job.current = null;
job.finishedAt = new Date();
logToFile(
`Stale refresh ${job.cancelRequested ? "cancelled" : "finished"}: ${job.succeeded} ok, ${job.failed.length} failed of ${job.total}`,
);
})();
return this.getStaleRefreshStatus();
}
cancelStaleRefresh() {
if (this.staleRefreshJob?.running) {
this.staleRefreshJob.cancelRequested = true;
}
return this.getStaleRefreshStatus();
}
} }
module.exports = new MaintenanceService(); module.exports = new MaintenanceService();
+5 -1
View File
@@ -151,7 +151,11 @@ class MediaDownloaderService {
logToFile( logToFile(
`Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`, `Media Service | downloaded: ${mediaType}, path:${downloadPath} url:${url}`,
); );
downloadedImages.push({ type: mediaType, path: filename }); downloadedImages.push({
type: mediaType,
path: filename,
tmdb_path: media.file_path,
});
}) })
.catch((err) => { .catch((err) => {
logToFile( logToFile(
@@ -18,6 +18,13 @@ const EntrySeen = require("../../models/EntrySeen.js");
const Episode = require("../../models/Episode.js"); const Episode = require("../../models/Episode.js");
const Media = require("../../models/Media.js"); const Media = require("../../models/Media.js");
const Genre = require("../../models/Genre.js"); const Genre = require("../../models/Genre.js");
const {
mapEntryFields,
mapEntryIds,
mapEntryRatings,
mapSeasonFields,
mapEpisodeFields,
} = require("../../mappers/entryMapper.js");
async function saveEntry(data) { async function saveEntry(data) {
try { try {
@@ -27,29 +34,9 @@ async function saveEntry(data) {
var is_tvseries = data.release_date == null ? true : false; var is_tvseries = data.release_date == null ? true : false;
let movie = Entry.build({ let movie = Entry.build({
title: data.title || data.name, ...mapEntryFields(data),
original_title: data.original_title || data.original_name,
release_date: data.release_date || data.first_air_date,
release_status: data.status,
runtime: data.runtime || null,
tagline: data.tagline || null,
storyline: data.overview,
country:
data.production_countries.length > 0
? data.production_countries[0].name
: null,
is_tvseries: is_tvseries, is_tvseries: is_tvseries,
watchlist: true, watchlist: true,
status: data.status,
genres: data.genre_ids,
poster_path: data.poster_path,
banner_path: data.backdrop_path,
last_fetch: new Date(),
}); });
const savedEntry = await movie.save(); const savedEntry = await movie.save();
@@ -58,7 +45,7 @@ async function saveEntry(data) {
const ids = await EntryId.create({ const ids = await EntryId.create({
entry_id: savedEntry.id, entry_id: savedEntry.id,
tmdb_id: data.id, tmdb_id: data.id,
imdb_id: data.imdb_id, ...mapEntryIds(data),
}); });
// ? genres // ? genres
@@ -73,7 +60,7 @@ async function saveEntry(data) {
const ratings = await EntryRating.create({ const ratings = await EntryRating.create({
entry_id: savedEntry.id, entry_id: savedEntry.id,
user_rating: 0, user_rating: 0,
tmdb_rating: data.vote_average, ...mapEntryRatings(data),
}); });
// ! seasons & episodes for tv series // ! seasons & episodes for tv series
@@ -82,21 +69,11 @@ async function saveEntry(data) {
let seasons = []; let seasons = [];
for (const season of data.seasons) { for (const season of data.seasons) {
let seasonData = await fetchSeasonData(data.id, season.season_number); let seasonData = await fetchSeasonData(data.id, season.season_number);
if (!seasonData) continue;
const savedSeason = await Season.create({ const savedSeason = await Season.create({
tmdb_id: seasonData.id, ...mapSeasonFields(seasonData),
entry_id: savedEntry.id, entry_id: savedEntry.id,
name: seasonData.name,
overview: seasonData.overview,
season_number: seasonData.season_number,
episode_count: seasonData.episodes.length,
air_date: seasonData.air_date,
user_rating: 0, user_rating: 0,
tmdb_rating: seasonData.vote_average,
poster_path: seasonData.poster_path,
banner_path: null, banner_path: null,
}); });
@@ -104,20 +81,8 @@ async function saveEntry(data) {
let episodes = []; let episodes = [];
for (const episode of seasonData.episodes) { for (const episode of seasonData.episodes) {
const savedEpisode = await Episode.create({ const savedEpisode = await Episode.create({
tmdb_id: episode.id, ...mapEpisodeFields(episode),
season_id: savedSeason.id, season_id: savedSeason.id,
name: episode.name,
overview: episode.overview,
episode_number: episode.episode_number,
episode_type: episode.episode_type,
runtime: episode.runtime,
air_date: episode.air_date,
tmdb_rating: episode.vote_average,
still_path: episode.still_path,
}); });
episodes.push(savedEpisode); episodes.push(savedEpisode);
@@ -143,6 +108,7 @@ async function saveEntry(data) {
mediaableId: savedEntry.id, mediaableId: savedEntry.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true, isLocal: true,
isSelected: true, isSelected: true,
}); });
@@ -554,6 +520,7 @@ async function refrechEntry(entryId) {
mediaableId: oldEntry.id, mediaableId: oldEntry.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true, isLocal: true,
isSelected: true, isSelected: true,
}); });
@@ -1,4 +1,5 @@
const multer = require("multer"); const multer = require("multer");
const fs = require("fs");
const { v4: uuidv4 } = require("uuid"); const { v4: uuidv4 } = require("uuid");
const path = require("path"); const path = require("path");
const configService = require("./configService"); const configService = require("./configService");
@@ -57,8 +58,27 @@ const peoplePicturesUpload = multer({
}), }),
}); });
// ? discovery videos
const videosUpload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
const dataPath = configService.getSettings().userDataPath;
const videosDir = path.join(dataPath, "videos");
// ensure the folder exists even if createMediaFolders() was never called
fs.mkdirSync(videosDir, { recursive: true });
cb(null, videosDir);
},
filename: function (req, file, cb) {
const uniqueFilename = uuidv4();
const extension = file.originalname.split(".").pop();
cb(null, `${uniqueFilename}.${extension}`);
},
}),
});
module.exports = { module.exports = {
entryPicturesUpload, entryPicturesUpload,
collectionPicturesUpload, collectionPicturesUpload,
peoplePicturesUpload, peoplePicturesUpload,
videosUpload,
}; };
+24 -12
View File
@@ -50,21 +50,33 @@ class NetworkService {
return network; return network;
} }
/**
* Creates the network or refreshes its TMDB fields. TMDB sends snake_case
* (`origin_country`, `logo_path`); the model attributes are camelCase.
* @returns {Promise<[Network, boolean]>} same shape as findOrCreate
*/
async createOrUpdateNetwork(networkData) { async createOrUpdateNetwork(networkData) {
return await Network.findOrCreate({ const fields = {
name: networkData.name,
originCountry: networkData.origin_country || null,
logoPath: networkData.logo_path || null,
};
const [network, created] = await Network.findOrCreate({
where: { id: networkData.id }, where: { id: networkData.id },
defaults: { defaults: { id: networkData.id, ...fields },
id: networkData.id,
name: networkData.name,
originCountry: networkData.originCountry,
homepage: networkData.homepage,
logoPath: networkData.logoPath,
posterPath: networkData.posterPath,
backdropPath: networkData.backdropPath,
},
}); });
if (
!created &&
(network.name !== fields.name ||
network.originCountry !== fields.originCountry ||
network.logoPath !== fields.logoPath)
) {
await network.update(fields);
}
return [network, created];
} }
} }
+1
View File
@@ -72,6 +72,7 @@ class PeopleManager {
mediaableId: person.id, mediaableId: person.id,
type: image.type, type: image.type,
path: image.path, path: image.path,
tmdbPath: image.tmdb_path || null,
isLocal: true, isLocal: true,
isSelected: true, isSelected: true,
}); });
+186 -206
View File
@@ -5,91 +5,161 @@ const configService = require("./configService");
const TMDB_APIURL = configService.getTmdbApiUrl(); const TMDB_APIURL = configService.getTmdbApiUrl();
const TMDB_APIKEY = configService.getTmdbApiKey(); const TMDB_APIKEY = configService.getTmdbApiKey();
async function fetchEntryData(tmdb_id, is_tvserie) { // ─── Rate limiting ───────────────────────────────────────────────────────────
try { // TMDB allows roughly 50 requests/second per IP. We stay well below that so
let type = is_tvserie ? "tv" : "movie"; // bulk jobs (e.g. the stale-entries refresh) never get the IP blocked.
let url = `${TMDB_APIURL}${type}/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US`; const MAX_REQUESTS_PER_WINDOW = 20;
logToFile(`Fetching Entry Data From: ${url}`); const WINDOW_MS = 1000;
let data; const MAX_CONCURRENT = 8;
await axios.get(url).then((response) => { const MAX_RETRIES = 4;
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
return data; const queue = [];
const recentStarts = [];
let activeRequests = 0;
let wakeTimer = null;
function scheduleNext() {
while (queue.length > 0 && activeRequests < MAX_CONCURRENT) {
const now = Date.now();
while (recentStarts.length && now - recentStarts[0] >= WINDOW_MS) {
recentStarts.shift();
}
if (recentStarts.length >= MAX_REQUESTS_PER_WINDOW) {
if (!wakeTimer) {
const waitMs = WINDOW_MS - (now - recentStarts[0]) + 5;
wakeTimer = setTimeout(() => {
wakeTimer = null;
scheduleNext();
}, waitMs);
}
return;
}
recentStarts.push(now);
activeRequests++;
const job = queue.shift();
job().finally(() => {
activeRequests--;
scheduleNext();
});
}
}
function enqueue(fn) {
return new Promise((resolve, reject) => {
queue.push(() => fn().then(resolve, reject));
scheduleNext();
});
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function isRetryable(error) {
const status = error.response?.status;
if (status === 429) return true;
if (status >= 500) return true;
return !error.response; // network error / timeout
}
/**
* Rate-limited GET against the TMDB API. Retries 429s (honouring Retry-After)
* and transient failures with backoff. The API key is never logged.
* @param {string} path - e.g. "movie/550"
* @param {Object} [params] - extra query params
* @returns {Promise<Object>} response data
*/
async function tmdbGet(path, params = {}) {
const query = { language: "en-US", ...params };
const logQuery = new URLSearchParams(
Object.entries(query).filter(([, v]) => v !== undefined),
).toString();
for (let attempt = 1; ; attempt++) {
try {
logToFile(`TMDB GET ${path}?${logQuery}`);
const response = await enqueue(() =>
axios.get(`${TMDB_APIURL}${path}`, {
params: { api_key: TMDB_APIKEY, ...query },
timeout: 20000,
}),
);
return response.data;
} catch (error) {
if (attempt >= MAX_RETRIES || !isRetryable(error)) throw error;
const retryAfter = Number(error.response?.headers?.["retry-after"]);
const waitMs =
Number.isFinite(retryAfter) && retryAfter > 0
? retryAfter * 1000
: 1000 * 2 ** (attempt - 1);
logToFile(
`TMDB GET ${path} failed (${error.response?.status ?? error.code}), retry ${attempt}/${MAX_RETRIES - 1} in ${waitMs}ms`,
);
await sleep(waitMs);
}
}
}
/** Runs a TMDB request, logging and returning null on failure. */
async function safeGet(label, path, params) {
try {
return await tmdbGet(path, params);
} catch (error) { } catch (error) {
console.log("Error fetching the entry data.", error); logToFile(
`Error fetching ${label} (${path}): ${error.response?.status ?? ""} ${error.message}`,
);
console.log(`Error fetching ${label}.`, error.message);
return null; return null;
} }
} }
// ─── Entries ─────────────────────────────────────────────────────────────────
/**
* Fetches movie/TV details plus everything we store from the same request:
* external ids, certification, keywords, videos, watch providers and
* alternative titles.
*/
async function fetchEntryData(tmdb_id, is_tvserie) {
const type = is_tvserie ? "tv" : "movie";
const appends = [
"external_ids",
is_tvserie ? "content_ratings" : "release_dates",
"keywords",
"videos",
"watch/providers",
"alternative_titles",
];
return safeGet("entry data", `${type}/${tmdb_id}`, {
append_to_response: appends.join(","),
include_video_language: "en,null",
});
}
async function fetchSeasonData(tmdbTvId, seasonNumber) { async function fetchSeasonData(tmdbTvId, seasonNumber) {
// fetching the informations return safeGet("season data", `tv/${tmdbTvId}/season/${seasonNumber}`, {
try { append_to_response: "external_ids",
let url = `${TMDB_APIURL}tv/${tmdbTvId}/season/${seasonNumber}?api_key=${TMDB_APIKEY}&language=en-US`; });
logToFile(`Fetching Season Data From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log("Error fetching the data.");
return null;
}
} }
async function fetchEntryMedia(tmdb_id, is_tvserie) { async function fetchEntryMedia(tmdb_id, is_tvserie) {
try { const type = is_tvserie ? "tv" : "movie";
let type = is_tvserie ? "tv" : "movie"; // Images are language-agnostic, so don't send language=en-US
let url = `${TMDB_APIURL}${type}/${tmdb_id}/images?api_key=${TMDB_APIKEY}`; return safeGet("entry media", `${type}/${tmdb_id}/images`, {
logToFile(`Fetching Entry Media Data From: ${url}`); language: undefined,
let data; });
await axios.get(url).then((response) => { }
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
data = response.data;
});
return data; async function fetchEntryRecommendations(tmdb_id, is_tvserie, page = 1) {
} catch (error) { const type = is_tvserie ? "tv" : "movie";
console.log("Error fetching the entry media.", error); return safeGet("recommendations", `${type}/${tmdb_id}/recommendations`, {
return null; page,
} });
} }
async function fetchCollectionData(collectionId) { async function fetchCollectionData(collectionId) {
try { return safeGet("collection data", `collection/${collectionId}`);
let url = `${TMDB_APIURL}collection/${collectionId}?api_key=${TMDB_APIKEY}&language=en-US`;
logToFile(`Fetching Collection Data From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200)
return console.log(
"Error fetching collection data from tmdb:",
response,
);
data = response.data;
});
return data;
} catch (error) {
if (response.status != 200) {
logToFile(`Error Fetching Data From: ${url}`);
return console.log("Error fetching the data.");
}
return null;
}
} }
/** /**
@@ -99,158 +169,68 @@ async function fetchCollectionData(collectionId) {
* @returns {Promise<Object|null>} - The credits data or null if there's an error * @returns {Promise<Object|null>} - The credits data or null if there's an error
*/ */
async function fetchEntryCredits(tmdb_id, is_tvserie) { async function fetchEntryCredits(tmdb_id, is_tvserie) {
try { const path = is_tvserie
let type = is_tvserie ? "tv" : "movie"; ? `tv/${tmdb_id}/aggregate_credits`
let url = `${TMDB_APIURL}${type}/${tmdb_id}/credits?api_key=${TMDB_APIKEY}&language=en-US`; : `movie/${tmdb_id}/credits`;
return safeGet("entry credits", path);
if (is_tvserie) {
url = `${TMDB_APIURL}${type}/${tmdb_id}/aggregate_credits?api_key=${TMDB_APIKEY}&language=en-US`;
}
logToFile(`Fetching Entry Credits From: ${url}`);
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Credits From: ${url}`);
return console.log("Error fetching the credits data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log("Error fetching the entry credits.", error);
return null;
}
} }
// ─── People ──────────────────────────────────────────────────────────────────
/** /**
* Fetches detailed information about a person * Fetches detailed information about a person
* @param {number} tmdb_id - The TMDB ID of the person * @param {number} tmdb_id - The TMDB ID of the person
* @returns {Promise<Object|null>} - The person data or null if there's an error * @returns {Promise<Object|null>} - The person data or null if there's an error
*/ */
async function fetchPersonDetails(tmdb_id) { async function fetchPersonDetails(tmdb_id) {
try { return safeGet("person details", `person/${tmdb_id}`, {
let url = `${TMDB_APIURL}person/${tmdb_id}?api_key=${TMDB_APIKEY}&language=en-US&append_to_response=external_ids`; append_to_response: "external_ids",
logToFile(`Fetching Person Details From: ${url}`); });
let data;
await axios.get(url).then((response) => {
if (response.status != 200) {
logToFile(`Error Fetching Person Details From: ${url}`);
return console.log("Error fetching the person data.");
}
data = response.data;
});
return data;
} catch (error) {
console.log("Error fetching the person details.", error);
return null;
}
}
async function fetchTrending(type, page = 1) {
try {
let url = `${TMDB_APIURL}trending/${type}/week?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Trending ${type} From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(`Error fetching trending ${type}.`, error);
return null;
}
}
async function fetchPopular(type, page = 1) {
try {
let url = `${TMDB_APIURL}${type}/popular?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Popular ${type} From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(`Error fetching popular ${type}.`, error);
return null;
}
}
async function fetchTopRated(type, page = 1) {
try {
let url = `${TMDB_APIURL}${type}/top_rated?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Top Rated ${type} From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log(`Error fetching top rated ${type}.`, error);
return null;
}
}
async function fetchUpcoming(page = 1) {
try {
let url = `${TMDB_APIURL}movie/upcoming?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Upcoming Movies From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error fetching upcoming movies.", error);
return null;
}
}
async function searchMulti(query, page = 1) {
try {
let url = `${TMDB_APIURL}search/multi?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`;
logToFile(`Searching TMDB for: ${query}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error searching TMDB.", error);
return null;
}
}
async function searchPeople(query, page = 1) {
try {
let url = `${TMDB_APIURL}search/person?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`;
logToFile(`Searching TMDB People for: ${query}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error searching TMDB people.", error);
return null;
}
}
async function fetchPopularPeople(page = 1) {
try {
let url = `${TMDB_APIURL}person/popular?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`;
logToFile(`Fetching Popular People From: ${url}`);
const response = await axios.get(url);
return response.data;
} catch (error) {
console.log("Error fetching popular people.", error);
return null;
}
} }
async function fetchPersonCombinedCredits(tmdb_id) { async function fetchPersonCombinedCredits(tmdb_id) {
try { return safeGet(
const url = `${TMDB_APIURL}person/${tmdb_id}/combined_credits?api_key=${TMDB_APIKEY}&language=en-US`; "person combined credits",
logToFile(`Fetching Person Combined Credits From: ${url}`); `person/${tmdb_id}/combined_credits`,
const response = await axios.get(url); );
return response.data; }
} catch (error) {
console.log("Error fetching person combined credits.", error); // ─── Lists & search ──────────────────────────────────────────────────────────
return null;
} async function fetchTrending(type, page = 1) {
return safeGet(`trending ${type}`, `trending/${type}/week`, { page });
}
async function fetchPopular(type, page = 1) {
return safeGet(`popular ${type}`, `${type}/popular`, { page });
}
async function fetchTopRated(type, page = 1) {
return safeGet(`top rated ${type}`, `${type}/top_rated`, { page });
}
async function fetchUpcoming(page = 1) {
return safeGet("upcoming movies", "movie/upcoming", { page });
}
async function searchMulti(query, page = 1) {
return safeGet("search", "search/multi", { query, page });
}
async function searchPeople(query, page = 1) {
return safeGet("people search", "search/person", { query, page });
}
async function fetchPopularPeople(page = 1) {
return safeGet("popular people", "person/popular", { page });
} }
module.exports = { module.exports = {
tmdbGet,
fetchEntryData, fetchEntryData,
fetchSeasonData, fetchSeasonData,
fetchEntryMedia, fetchEntryMedia,
fetchEntryRecommendations,
fetchCollectionData, fetchCollectionData,
fetchEntryCredits, fetchEntryCredits,
fetchPersonDetails, fetchPersonDetails,
+151
View File
@@ -0,0 +1,151 @@
const path = require("path");
const fs = require("fs");
const { execFile } = require("child_process");
const configService = require("./configService");
const Video = require("../models/Video");
const { logToFile } = require("./logService");
// Limit concurrent ffmpeg jobs so a page full of missing thumbnails
// doesn't start one heavy process per image request at once.
const MAX_CONCURRENT_JOBS = 2;
let activeJobs = 0;
const jobQueue = [];
function resolveFfmpeg() {
try {
const bin = require("ffmpeg-static");
if (bin && fs.existsSync(bin)) return bin;
} catch {
// ffmpeg-static not installed
}
return "ffmpeg"; // fall back to a system-wide ffmpeg on PATH
}
function extractFrame(ffmpeg, inputPath, outputPath, seek) {
return new Promise((resolve, reject) => {
execFile(
ffmpeg,
[
"-y",
"-ss",
seek,
"-i",
inputPath,
"-frames:v",
"1",
"-vf",
"scale=640:-2",
"-q:v",
"3",
outputPath,
],
{ timeout: 60000, windowsHide: true },
(err) => (err ? reject(err) : resolve()),
);
});
}
function runLimited(job) {
return new Promise((resolve, reject) => {
const run = async () => {
try {
resolve(await job());
} catch (err) {
reject(err);
} finally {
activeJobs -= 1;
const next = jobQueue.shift();
if (next) {
activeJobs += 1;
next();
}
}
};
if (activeJobs < MAX_CONCURRENT_JOBS) {
activeJobs += 1;
run();
} else {
jobQueue.push(run);
}
});
}
/**
* Generates a thumbnail for a video: extracts a frame at 1s (falls back
* to frame 0 for very short videos) and stores `{uuid}.jpg` in
* data/videos/thumbnails/.
*
* Returns the thumbnail filename on success, or null on failure.
* Never throws — a missing thumbnail must not break requests.
*/
async function generateThumbnail(video) {
try {
// Re-check against the DB — the thumbnail may have been generated
// since this video instance was loaded.
const fresh = await Video.findByPk(video.id);
if (!fresh) return null;
const dataPath = configService.getSettings().userDataPath;
const videosDir = path.join(dataPath, "videos");
const thumbDir = path.join(videosDir, "thumbnails");
const inputPath = path.join(videosDir, fresh.filename);
if (!fs.existsSync(inputPath)) return null;
const thumbName = `${fresh.filename.split(".")[0]}.jpg`;
const outputPath = path.join(thumbDir, thumbName);
// Already generated → just make sure the DB knows about it
if (fs.existsSync(outputPath)) {
if (!fresh.thumbnail_path) {
await fresh.update({ thumbnail_path: thumbName });
}
return thumbName;
}
fs.mkdirSync(thumbDir, { recursive: true });
const ffmpeg = resolveFfmpeg();
try {
await extractFrame(ffmpeg, inputPath, outputPath, "1");
} catch {
// very short videos — grab the first frame instead
await extractFrame(ffmpeg, inputPath, outputPath, "0");
}
if (!fs.existsSync(outputPath)) return null;
await fresh.update({ thumbnail_path: thumbName });
logToFile(`Video Thumbnail | Generated for video ${fresh.id}`);
return thumbName;
} catch (err) {
logToFile(`Video Thumbnail | Error for video ${video.id}`);
logToFile(err);
return null;
}
}
const inFlight = new Map(); // videoId -> Promise<string | null>
/**
* On-demand thumbnail generation.
* - Per-video dedup: concurrent requests for the same video share one job.
* - Global concurrency limit (MAX_CONCURRENT_JOBS ffmpeg processes).
* Called only from the thumbnail endpoint, i.e. when a client actually
* requests a thumbnail that doesn't exist yet.
*/
function ensureThumbnail(video) {
if (inFlight.has(video.id)) return inFlight.get(video.id);
const tracked = runLimited(() => generateThumbnail(video));
const shared = tracked.finally(() => {
inFlight.delete(video.id);
});
inFlight.set(video.id, shared);
return shared;
}
module.exports = { ensureThumbnail, generateThumbnail };
+9 -1
View File
@@ -13,5 +13,13 @@
"episodesViewMode": "grid-2", "episodesViewMode": "grid-2",
"favoritsViewMode": "", "favoritsViewMode": "",
"authPassword": "", "authPassword": "",
"jwtSecret": "change-me-to-a-random-string" "jwtSecret": "change-me-to-a-random-string",
"dashboardToken": "your-dashboard-token-here",
"namedTokens": [
{
"name": "homepage-widget",
"value": "generate-a-secure-random-string",
"endDate": "2027-12-31"
}
]
} }
+17
View File
@@ -170,6 +170,23 @@ See [[Media System]] for details.
--- ---
## Discovery Videos
> [!info] File: `routes/video.routes.js` → `controllers/videoController.js`
See [[Discovery Videos]] for details.
| Method | Path | Description |
|---|---|---|
| `GET` | `/discovery-videos?page=&limit=` | Paginated list (includes linked entries) |
| `POST` | `/discovery-videos` | Multipart upload: `videos[]` (≤ 10), `description`, `entryIds` (JSON array) |
| `PUT` | `/discovery-videos/:id` | Update title / description / entry links |
| `DELETE` | `/discovery-videos/:id` | Delete record + files from disk |
| `GET` | `/discovery-videos/:id/thumbnail` | Thumbnail image — generated on demand when missing |
| `GET` | `/discovery-videos/:id/stream` | Video stream with HTTP Range support (`?token=` auth) |
---
## People ## People
> [!info] File: `routes/people.routes.js` → `controllers/peopleController.js` > [!info] File: `routes/people.routes.js` → `controllers/peopleController.js`
+4 -3
View File
@@ -37,10 +37,10 @@ backend/
│ ├── relations.js All model associations → [[Database#Relationships]] │ ├── relations.js All model associations → [[Database#Relationships]]
│ ├── dataInitializer.js Genre seeding (27 TMDB genres) │ ├── dataInitializer.js Genre seeding (27 TMDB genres)
│ └── sequelizeHooks.js UserCollectionEntry hooks (order management) │ └── sequelizeHooks.js UserCollectionEntry hooks (order management)
├── controllers/ Route handlers (14 controllers) ├── controllers/ Route handlers (15 controllers)
├── services/ Business logic (16 services) → [[Services]] ├── services/ Business logic (16 services) → [[Services]]
├── models/ Sequelize models (17 models) → [[Models]] ├── models/ Sequelize models (19 models) → [[Models]]
├── routes/ Express routers (14 route files) → [[API Reference]] ├── routes/ Express routers (15 route files) → [[API Reference]]
├── errors/ Custom error classes → [[Error Handling]] ├── errors/ Custom error classes → [[Error Handling]]
├── middleware/ ├── middleware/
│ └── errorHandler.js Central error catching │ └── errorHandler.js Central error catching
@@ -96,3 +96,4 @@ See [[Media System]] for the complete download → optimize → serve flow.
- [[Error Handling]] — Error classes and middleware - [[Error Handling]] — Error classes and middleware
- [[TMDB Integration]] — External API - [[TMDB Integration]] — External API
- [[Media System]] — Image handling - [[Media System]] — Image handling
- [[Discovery Videos]] — Video upload/stream API
+16 -2
View File
@@ -68,13 +68,27 @@ See [[Statistics]] for data details.
| `CollectionEditDialog` | `dialogs/CollectionEditDialog.tsx` | Create/edit collection | | `CollectionEditDialog` | `dialogs/CollectionEditDialog.tsx` | Create/edit collection |
| `MarkSeasonWatchedDialog` | `dialogs/MarkSeasonWatchedDialog.tsx` | Mark season as watched — single date or scatter mode | | `MarkSeasonWatchedDialog` | `dialogs/MarkSeasonWatchedDialog.tsx` | Mark season as watched — single date or scatter mode |
## Discovery Video Components
> [!info] Folder: `components/discovery-videos/`
See [[Discovery Videos]].
| Component | File | Description |
|---|---|---|
| `VideoCard` | `discovery-videos/VideoCard.tsx` | Card with lazy thumbnail (`loading="lazy"`, on-demand generation) + play overlay, linked-entry chips, edit/delete actions |
| `VideoPlayerDialog` | `discovery-videos/VideoPlayerDialog.tsx` | Playback dialog — autoplay, ↑/↓ (and ←/→) prev/next navigation, linked-entry chips, inline edit |
| `AddVideoDialog` | `discovery-videos/AddVideoDialog.tsx` | Upload (create) and edit modes — dropzone + description + entry multi-select |
| `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]] |
## Skeletons ## Skeletons
> [!info] File: `components/skeletons/PageSkeletons.tsx` > [!info] File: `components/skeletons/PageSkeletons.tsx`
14 named skeleton exports used as `<Suspense>` fallbacks for lazy-loaded pages: 15 named skeleton exports used as `<Suspense>` fallbacks for lazy-loaded pages:
`HomeSkeleton`, `LibrarySkeleton`, `WatchlistSkeleton`, `DashboardSkeleton`, `CollectionsSkeleton`, `CollectionDetailsSkeleton`, `MediaSkeleton`, `CalendarSkeleton`, `EntryDetailsSkeleton`, `SeasonSkeleton`, `EpisodeSkeleton`, `PeopleSkeleton`, `PersonDetailsSkeleton`, `SettingsSkeleton` `HomeSkeleton`, `LibrarySkeleton`, `WatchlistSkeleton`, `DashboardSkeleton`, `CollectionsSkeleton`, `CollectionDetailsSkeleton`, `MediaSkeleton`, `CalendarSkeleton`, `EntryDetailsSkeleton`, `SeasonSkeleton`, `EpisodeSkeleton`, `PeopleSkeleton`, `PersonDetailsSkeleton`, `SettingsSkeleton`, `DiscoveryVideosSkeleton`
## Command Palette ## Command Palette
+4
View File
@@ -30,6 +30,7 @@ erDiagram
Entry }o--o{ Genre : tagged Entry }o--o{ Genre : tagged
Entry }o--o{ Network : airs-on Entry }o--o{ Network : airs-on
Entry }o--o{ Collection : belongs-to Entry }o--o{ Collection : belongs-to
Entry }o--o{ Video : links-to
Season ||--o{ Episode : contains Season ||--o{ Episode : contains
Episode ||--o{ EpisodeSeen : has Episode ||--o{ EpisodeSeen : has
@@ -63,6 +64,7 @@ Defined in `backend/config/relations.js`:
| Credit | Entry | `belongsTo` | — | — | | Credit | Entry | `belongsTo` | — | — |
| People | Credit | `hasMany` (as 'roles') | — | — | | People | Credit | `hasMany` (as 'roles') | — | — |
| Media | * | Polymorphic scopes | `mediaable` + `mediaableId` | — | | Media | * | Polymorphic scopes | `mediaable` + `mediaableId` | — |
| Video | Entry | `belongsToMany` | VideoEntry | CASCADE |
### Polymorphic Media Scopes ### Polymorphic Media Scopes
@@ -101,6 +103,8 @@ See [[Models]] for detailed field definitions of every model.
| [[Models#Genre\|Genre]] | Genres (seeded from TMDB) | No | | [[Models#Genre\|Genre]] | Genres (seeded from TMDB) | No |
| [[Models#Network\|Network]] | TV networks | No | | [[Models#Network\|Network]] | TV networks | No |
| [[Models#Franchise\|Franchise]] | Franchise grouping (unused) | No | | [[Models#Franchise\|Franchise]] | Franchise grouping (unused) | No |
| [[Models#Video\|Video]] | Discovery videos | Yes |
| [[Models#VideoEntry\|VideoEntry]] | Video ↔ Entry join | Yes |
## Important Files ## Important Files
+122
View File
@@ -0,0 +1,122 @@
---
title: Discovery Videos
tags:
- feature
- frontend
- backend
- videos
aliases:
- Videos
- Saved Videos
- Video Vault
---
# Discovery Videos
Personal video vault page — upload local videos (recommendations, anything worth watching later), add a description, and link them to one or more [[Library]] entries.
**Route:** `/discovery-videos` (sidebar label: "Discover")
> [!note] Naming
> This page is distinct from [[Pages#DiscoverPage|DiscoverPage]], which is the TMDB browse page at `/discover/:category`.
---
## Overview
**Responsibilities:**
- Upload video files via drag & drop (up to 10 at once)
- Store a description per upload
- Link videos to one or many library entries (M:N)
- Display all saved videos in a lazy-loaded grid with inline playback
- Edit / delete videos (deletion also removes the file from disk)
**Key Flows:**
1. **Upload:** `AddVideoDialog` → drop files → description + entry multi-select → `POST /discovery-videos` (multipart) → files stored to `data/videos/` with UUID names
2. **Browse:** `DiscoveryVideosPage` → `GET /discovery-videos?page=&limit=` (24/page) → infinite scroll via IntersectionObserver
3. **Play:** clicking a card opens `VideoPlayerDialog` — the video plays in the dialog; ↑/↓ (and ←/→ when the player isn't focused) navigate to the previous/next video. Streamed via `GET /discovery-videos/:id/stream` with HTTP Range support
4. **Thumbnails (on demand):** cards always request `GET /discovery-videos/:id/thumbnail`; when no thumbnail exists yet, the endpoint generates it (ffmpeg frame at 1s) and serves it in the same response — nothing is generated eagerly or at startup
**Entry linking UX:** the picker in `AddVideoDialog` lists entries only once the user starts typing (debounced 250 ms) — the full library is never rendered at once.
---
## Lazy Loading & Performance
| Layer | Mechanism |
|---|---|
| Route | `React.lazy()` + `<Suspense>` with `DiscoveryVideosSkeleton` |
| Data | Paginated API + `useInfiniteQuery` + IntersectionObserver sentinel (`rootMargin: "400px"`) — only metadata travels, never video bytes |
| Thumbnails | `<img loading="lazy">` requesting the thumbnail endpoint — generated **on demand** on first request (no eager/startup generation), deduped + limited to 2 concurrent ffmpeg jobs |
| Media | Video plays only inside the player dialog — nothing is fetched until the user opens it; `res.sendFile` → native `Accept-Ranges`/`206` support → browser pulls only the segments it needs on seek/play |
---
## Data Model
See [[Models#Video]] and [[Models#VideoEntry]] for field details, [[Database#Relationships]] for the relations.
```
videos (id, title, description, filename, original_name, mime_type, size, ...)
└── video_entries (video_id, entry_id) ── entries
```
---
## API
| Method | Path | Description |
|---|---|---|
| `GET` | `/discovery-videos?page=&limit=` | Paginated list (includes linked entries) |
| `POST` | `/discovery-videos` | Multipart upload: `videos[]` (≤ 10), `description`, `entryIds` (JSON array) |
| `PUT` | `/discovery-videos/:id` | Update title / description / entry links |
| `DELETE` | `/discovery-videos/:id` | Delete record + files from disk |
| `GET` | `/discovery-videos/:id/stream` | Video stream with HTTP Range support |
| `GET` | `/discovery-videos/:id/thumbnail` | Thumbnail image — generated on demand when missing (served in the same response) |
**Auth:** stream URLs append `?token=<authToken>` (the `<video>` tag cannot send `Authorization` headers). See [[API Reference]].
**Allowed extensions:** `mp4, webm, mov, m4v, mkv, avi`. Note: `mkv`/`avi` may not play in browsers — mp4 (H.264) is recommended.
---
## Important Files
**Backend**
- `backend/models/Video.js` — video record model
- `backend/models/VideoEntry.js` — junction model (video ↔ entry)
- `backend/controllers/videoController.js` — list/upload/update/delete/stream/thumbnail
- `backend/routes/video.routes.js` — mounted at `/api/v1/discovery-videos`
- `backend/services/mutlerStorageLocations.js` — `videosUpload` multer config
- `backend/services/videoThumbnailService.js` — on-demand ffmpeg thumbnail generation (deduped, concurrency-limited)
**Frontend**
- `react_frontend/src/pages/DiscoveryVideosPage.tsx` — page (grid + infinite scroll + player state)
- `react_frontend/src/components/discovery-videos/VideoCard.tsx` — thumbnail card with play overlay
- `react_frontend/src/components/discovery-videos/VideoPlayerDialog.tsx` — playback dialog with ↑/↓ navigation
- `react_frontend/src/components/discovery-videos/AddVideoDialog.tsx` — create/edit dialog
- `react_frontend/src/components/discovery-videos/VideoDropzone.tsx` — native drag & drop
- `react_frontend/src/components/discovery-videos/EntryMultiSelect.tsx` — library entry picker (reads from [[Stores|library store]])
- `react_frontend/src/api/discoveryVideos.ts` — API module
- `react_frontend/src/hooks/useDiscoveryVideos.ts` — query/mutations
---
## Known Limitations
- Thumbnails are generated on demand (first request, ffmpeg frame at 1s) — the first load of a thumbnail takes a moment; `ffmpeg-static` must ship in the packaged build (see `backend/pnpm-workspace.yaml` build approval)
- No transcoding — unsupported codecs will fail in the browser player
- No per-video watch state ("already watched") yet
- Multi-file uploads share one description + entry set (editable per video afterwards)
## See Also
- [[Routing]] — route table
- [[Pages]] — page reference
- [[Models]] — Sequelize models
- [[Database]] — relationships
- [[API Reference]] — endpoint reference
+3 -2
View File
@@ -103,7 +103,7 @@ The entire entry library is loaded into a Zustand `Map<number, Entry>` on startu
### Lazy Page Loading ### Lazy Page Loading
All 17 pages use `React.lazy()` with custom skeleton fallbacks via `<Suspense>`. See [[Routing]]. All 18 pages use `React.lazy()` with custom skeleton fallbacks via `<Suspense>`. See [[Routing]].
### Form Pattern ### Form Pattern
@@ -119,7 +119,7 @@ All mutation success/error feedback via Sonner toasts.
## See Also ## See Also
- [[Routing]] — All 17 routes - [[Routing]] — All 18 routes
- [[Pages]] — Every page component - [[Pages]] — Every page component
- [[Components]] — UI components by category - [[Components]] — UI components by category
- [[Hooks]] — Custom hooks - [[Hooks]] — Custom hooks
@@ -127,3 +127,4 @@ All mutation success/error feedback via Sonner toasts.
- [[API Clients]] — Backend communication - [[API Clients]] — Backend communication
- [[Types]] — TypeScript types - [[Types]] — TypeScript types
- [[Navigation]] — Breadcrumbs - [[Navigation]] — Breadcrumbs
- [[Discovery Videos]] — Personal video vault feature
+13
View File
@@ -127,6 +127,19 @@ See [[Statistics]].
|---|---|---| |---|---|---|
| `useEpisodesByMonth(start, end)` | Query | Episodes airing in date range (for [[Calendar]]) | | `useEpisodesByMonth(start, end)` | Query | Episodes airing in date range (for [[Calendar]]) |
## useDiscoveryVideos
> [!info] File: `hooks/useDiscoveryVideos.ts`
See [[Discovery Videos]].
| Hook | Type | Description |
|---|---|---|
| `useDiscoveryVideos()` | Infinite Query | Paginated video list (24/page) |
| `useUploadVideos()` | Mutation | `POST /discovery-videos` (multipart, upload progress) |
| `useUpdateVideo()` | Mutation | `PUT /discovery-videos/:id` |
| `useDeleteVideo()` | Mutation | `DELETE /discovery-videos/:id` |
## useDebounce ## useDebounce
> [!info] File: `hooks/useDebounce.ts` > [!info] File: `hooks/useDebounce.ts`
+1
View File
@@ -57,6 +57,7 @@ aliases:
- [[Watch Tracking]] — EntrySeen, EpisodeSeen, accuracy system - [[Watch Tracking]] — EntrySeen, EpisodeSeen, accuracy system
- [[Streaming]] — In-app streaming system with 4 providers (8 servers) - [[Streaming]] — In-app streaming system with 4 providers (8 servers)
- [[Calendar]] — Upcoming episodes view - [[Calendar]] — Upcoming episodes view
- [[Discovery Videos]] — Personal video vault (upload + link to library entries)
- [[Statistics]] — Dashboard charts and data - [[Statistics]] — Dashboard charts and data
- [[People]] — Cast, crew, filmography - [[People]] — Cast, crew, filmography
- [[Settings Page]] — App settings and maintenance cleanup - [[Settings Page]] — App settings and maintenance cleanup
+36
View File
@@ -360,3 +360,39 @@ Join table: Entry ↔ Network. Composite PK: `(network_id, entry_id)`. Has `orde
| `user_rating` | FLOAT | | `user_rating` | FLOAT |
**No timestamps. Currently unused — reserved for future franchise grouping.** **No timestamps. Currently unused — reserved for future franchise grouping.**
---
## Video
> [!info] File: `backend/models/Video.js`
Personal video record for the [[Discovery Videos]] page.
| Field | Type | Notes |
|---|---|---|
| `id` | INTEGER PK AUTO | |
| `title` | STRING(500) | Derived from filename on upload, editable |
| `description` | TEXT | User description |
| `filename` | STRING(200) | UUID filename in `data/videos/` |
| `original_name` | STRING(500) | Original upload name |
| `mime_type` | STRING(100) | |
| `size` | BIGINT | Bytes |
| `duration` | INTEGER | Nullable — reserved for ffmpeg probing |
| `thumbnail_path` | STRING(200) | Nullable — reserved for thumbnails |
**Has:** Entries (M:N via [[#VideoEntry]])
---
## VideoEntry
> [!info] File: `backend/models/VideoEntry.js`
Join table: Video ↔ Entry (M:N). Table name `video_entries`. FK `ON DELETE CASCADE` on both sides.
| Field | Type | Notes |
|---|---|---|
| `id` | INTEGER PK AUTO | |
| `video_id` | INTEGER FK | → Video |
| `entry_id` | INTEGER FK | → Entry |
+11
View File
@@ -36,6 +36,17 @@ TMDB browse by category: popular, trending, top-rated, upcoming. Uses `useTmdb`
Route: `/discover/:category` where category = `popular-movies`, `trending-movies`, `popular-tv`, etc. Route: `/discover/:category` where category = `popular-movies`, `trending-movies`, `popular-tv`, etc.
## DiscoveryVideosPage
Personal video vault — upload, link, and watch saved videos. See [[Discovery Videos]].
Route: `/discovery-videos`.
- Infinite-scroll grid of video cards (24/page)
- "Add media" button → `AddVideoDialog` (drag & drop upload)
- Cards render `<video preload="none">` — lazy playback, zero bytes until Play
- Linked entry chips navigate to `/entry/:id`
## WatchlistPage ## WatchlistPage
Grid of entries where `watchlist = true`. Similar to LibraryPage. Grid of entries where `watchlist = true`. Similar to LibraryPage.
+1
View File
@@ -27,6 +27,7 @@ Every page uses `React.lazy()` with a custom `<Suspense>` skeleton fallback.
| `/collections` | `CollectionsPage` | `CollectionsSkeleton` | [[Collections]] overview | | `/collections` | `CollectionsPage` | `CollectionsSkeleton` | [[Collections]] overview |
| `/collections/:id` | `CollectionDetailsPage` | `CollectionDetailsSkeleton` | Collection with entries | | `/collections/:id` | `CollectionDetailsPage` | `CollectionDetailsSkeleton` | Collection with entries |
| `/media` | `MediaPage` | `MediaSkeleton` | Media management | | `/media` | `MediaPage` | `MediaSkeleton` | Media management |
| `/discovery-videos` | `DiscoveryVideosPage` | `DiscoveryVideosSkeleton` | Personal video vault — see [[Discovery Videos]] |
| `/calendar` | `CalendarPage` | `CalendarSkeleton` | [[Calendar]] upcoming episodes | | `/calendar` | `CalendarPage` | `CalendarSkeleton` | [[Calendar]] upcoming episodes |
| `/entry/:id` | `EntryDetailsPage` | `EntryDetailsSkeleton` | Entry details, seasons, cast | | `/entry/:id` | `EntryDetailsPage` | `EntryDetailsSkeleton` | Entry details, seasons, cast |
| `/entry/:entryId/season/:seasonId` | `SeasonPage` | `SeasonSkeleton` | Season episodes | | `/entry/:entryId/season/:seasonId` | `SeasonPage` | `SeasonSkeleton` | Season episodes |
+916 -2576
View File
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -49,9 +49,8 @@
}, },
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": {},
"devDependencies": { "devDependencies": {
"electron": "^34.0.1", "electron": "^45.1.0",
"electron-builder": "^25.1.8" "electron-builder": "^26.18.0"
} }
} }
@@ -0,0 +1,66 @@
# Showy Dashboard — Homepage Widget
Displays Showy library stats on your Homepage dashboard.
## Setup
### 1. Showy Access Token
In your Showy settings pages you can generate a token. Copy it and use it in the widget configuration below.
The endpoint will be available at `GET /homepage-integration?token=your-secret-token-here`
### 2. Copy widget into your Homepage install
Copy this folder (`showydashboard/`) into your Homepage's `src/widgets/` directory.
### 3. Register the widget
**`src/widgets/widgets.js`** — add:
```js
import showydashboard from "./showydashboard/widget";
const widgets = {
// ...
showydashboard: showydashboard,
};
```
**`src/widgets/components.js`** — add:
```js
const components = {
// ...
showydashboard: dynamic(() => import("./showydashboard/component")),
};
```
### 4. Add to your Homepage services.yaml
```yaml
- Showy Library:
icon: /icons/showy.png
description: Movies & TV-Series Tracking library
widget:
type: showydashboard
url: http://YOUR-SHOWY-HOST:4000
dashboardToken: your-secret-token-here
fields: ["library", "libraryMovies", "librarySeries", "watchlist", "watchlistMovies", "watchlistSeries"]
```
### Available fields
| Field | Description |
|---|---|
| `totalEntries` | All entries in the library |
| `library` | Entries not in watchlist |
| `libraryMovies` | Movies not in watchlist |
| `librarySeries` | TV series not in watchlist |
| `watchlist` | Entries in watchlist |
| `watchlistMovies` | Movies in watchlist |
| `watchlistSeries` | TV series in watchlist |
| `collections` | Total collections |
| `favorits` | Favorite entries |
Omit `fields` to show all 9. `url` is just the host base — the widget appends `/api/v1/homepage-integration?token=...` automatically.
@@ -0,0 +1,47 @@
import Block from "components/services/widget/block";
import Container from "components/services/widget/container";
import useWidgetAPI from "utils/proxy/use-widget-api";
export default function Component({ service }) {
const { widget } = service;
const { data: showyStats, error: showyStatsError } = useWidgetAPI(
widget,
"stats",
);
if (showyStatsError) {
return <Container service={service} error={showyStatsError} />;
}
if (!showyStats) {
return (
<Container service={service}>
{/* <Block label="Total Entries" />*/}
<Block label="Library" />
{/* <Block label="Library Movies" />
<Block label="Library Series" />*/}
<Block label="Watchlist" />
{/* <Block label="Watchlist Movies" />
<Block label="Watchlist Series" />
<Block label="Collections" />
<Block label="Favorites" />*/}
</Container>
);
}
return (
<Container service={service}>
{/* <Block label="Total Entries" value={showyStats.totalEntries} />*/}
<Block label="Library" value={showyStats.library} />
{/* <Block label="Library Movies" value={showyStats.libraryMovies} />*/}
{/* <Block label="Library Series" value={showyStats.librarySeries} />*/}
<Block label="Watchlist" value={showyStats.watchlist} />
{/* <Block label="Watchlist Movies" value={showyStats.watchlistMovies} />*/}
{/* <Block label="Watchlist Series" value={showyStats.watchlistSeries} />*/}
{/* <Block label="Collections" value={showyStats.collections} />*/}
{/* <Block label="Favorites" value={showyStats.favorits} />*/}
</Container>
);
}
@@ -0,0 +1,36 @@
import { asJson } from "utils/proxy/api-helpers";
import genericProxyHandler from "utils/proxy/handlers/generic";
const widget = {
api: "{url}/api/v1/{endpoint}?token={dashboardToken}",
proxyHandler: genericProxyHandler,
mappings: {
totals: {
endpoint: "homepage-integration",
map: (data) => ({
totalEntries: asJson(data).totalEntries,
collections: asJson(data).collections,
favorits: asJson(data).favorits,
}),
},
library: {
endpoint: "homepage-integration",
map: (data) => ({
library: asJson(data).library,
libraryMovies: asJson(data).libraryMovies,
librarySeries: asJson(data).librarySeries,
}),
},
watchlist: {
endpoint: "homepage-integration",
map: (data) => ({
watchlist: asJson(data).watchlist,
watchlistMovies: asJson(data).watchlistMovies,
watchlistSeries: asJson(data).watchlistSeries,
}),
},
},
};
export default widget;
+748 -445
View File
File diff suppressed because it is too large. Load diff
+32
View File
@@ -0,0 +1,32 @@
allowBuilds:
msw: false
overrides:
'@babel/core@<=7.29.0': ^7.29.6
'@hono/node-server@<1.19.15': ^1.19.15
'@hono/node-server@>=1.19.10 <2.1.3': ^2.1.3
'@modelcontextprotocol/sdk@<1.32.0': ^1.32.0
axios@>=1.0.0 <1.20.0: ^1.20.0
baseline-browser-mapping@>=2.0.0 <2.11.0: ^2.11.0
body-parser@>=2.0.0 <2.4.0: ^2.4.0
brace-expansion@<1.1.21: ^1.1.21
brace-expansion@>=3.0.0 <5.0.7: ^5.0.7
brace-expansion@>=4.0.0 <5.0.12: ^5.0.12
browserslist@<=4.28.6: ^4.28.7
fast-uri@>=3.0.0 <3.1.9: ^3.1.9
follow-redirects@>=1.16.0 <1.16.1: ^1.16.1
form-data@>=4.0.0 <4.0.6: ^4.0.6
hono@<4.13.7: ^4.13.7
hono@>=4.12.4 <4.13.11: ^4.13.11
ip-address@<=10.7.3: ^10.7.4
js-yaml@>=4.0.0 <4.3.2: ^4.3.2
nanoid@<3.3.18: ^3.3.18
postcss-selector-parser@>=7.0.0 <7.1.6: ^7.1.6
postcss@<=8.5.22: ^8.5.23
proxy-addr@>=1.1.0 <2.0.8: ^2.0.8
qs@>=2.2.5 <6.16.0: ^6.16.0
qs@>=6.7.0 <=6.16.0: ^6.16.1
react-router@>=6.0.0 <7.18.0: ^7.18.0
react-router@>=7.12.0 <7.18.2: ^7.18.2
source-map-js@>=1.0.0 <1.2.2: ^1.2.2
vite@>=8.0.0 <=8.1.5: ^8.1.6
zod@<4.6.6: ^4.6.6
+43
View File
@@ -0,0 +1,43 @@
import { api } from "@/lib/api";
import { normalizeDiscoveryVideo } from "@/lib/normalizers";
import type {
DiscoveryVideo,
DiscoveryVideoPaginatedResponse,
} from "@/types";
export interface UpdateVideoData {
title?: string;
description?: string;
entryIds: number[];
}
export const discoveryVideosApi = {
getAll: (page = 1, limit = 24) =>
api
.get<DiscoveryVideoPaginatedResponse>("/discovery-videos", {
params: { page, limit },
})
.then((r) => ({
...r.data,
videos: r.data.videos.map(normalizeDiscoveryVideo),
})),
create: (formData: FormData, onProgress?: (percent: number) => void) =>
api
.post<DiscoveryVideo[]>("/discovery-videos", formData, {
headers: { "Content-Type": "multipart/form-data" },
onUploadProgress: (e) => {
if (onProgress && e.total) {
onProgress(Math.round((e.loaded / e.total) * 100));
}
},
})
.then((r) => r.data.map(normalizeDiscoveryVideo)),
update: (id: number, data: UpdateVideoData) =>
api
.put<DiscoveryVideo>(`/discovery-videos/${id}`, data)
.then((r) => normalizeDiscoveryVideo(r.data)),
remove: (id: number) => api.delete(`/discovery-videos/${id}`).then((r) => r.data),
};
+33 -1
View File
@@ -1,6 +1,15 @@
import { api } from "@/lib/api"; import { api } from "@/lib/api";
import { normalizeEntry, normalizeCredit } from "@/lib/normalizers"; import { normalizeEntry, normalizeCredit } from "@/lib/normalizers";
import type { Entry, Credit, TmdbPreview } from "@/types"; import type {
Entry,
Credit,
TmdbPreview,
TmdbEntry,
TmdbPaginatedResponse,
ArtworkResponse,
ArtworkType,
Media,
} from "@/types";
export const entriesApi = { export const entriesApi = {
getAll: () => getAll: () =>
@@ -58,6 +67,29 @@ export const entriesApi = {
.get<Credit[]>(`/entries/${id}/credits`) .get<Credit[]>(`/entries/${id}/credits`)
.then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])), .then((r) => (Array.isArray(r.data) ? r.data.map(normalizeCredit) : [])),
getRecommendations: (id: number) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>(`/entries/${id}/recommendations`)
.then((r) => r.data),
getTmdbRecommendations: (type: "movie" | "tv", tmdbId: number) =>
api
.get<TmdbPaginatedResponse<TmdbEntry>>(
`/entries/tmdb/recommendations/${type}/${tmdbId}`,
)
.then((r) => r.data),
getArtwork: (id: number) =>
api.get<ArtworkResponse>(`/entries/${id}/artwork`).then((r) => r.data),
getTmdbArtwork: (type: "movie" | "tv", tmdbId: number) =>
api
.get<ArtworkResponse>(`/entries/tmdb/artwork/${type}/${tmdbId}`)
.then((r) => r.data),
addArtwork: (id: number, data: { type: ArtworkType; file_path: string }) =>
api.post<Media>(`/entries/${id}/artwork`, data).then((r) => r.data),
syncSeries: () => api.get("/entries/sync-series").then((r) => r.data), syncSeries: () => api.get("/entries/sync-series").then((r) => r.data),
previewTmdb: (tmdbId: number, type: "movie" | "tv") => previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
+61
View File
@@ -0,0 +1,61 @@
import { api } from "@/lib/api";
export type WatchAccuracy = "EXACT" | "ESTIMATED" | "UNKNOWN";
export interface HistoryYear {
year: number;
movies: number;
episodes: number;
}
export interface HistoryEntry {
id: number;
title: string;
is_tvseries: boolean;
poster_path: string | null;
banner_path: string | null;
runtime: number | null;
release_date: string | null;
original_language: string | null;
medias: { id: number; type: string; path: string; isSelected: boolean }[];
genres: string[];
networks: { id: number; name: string; logo_path: string | null }[];
entryRating: {
user_rating: number | null;
tmdb_rating: number | null;
} | null;
}
export interface HistoryEpisode {
id: number;
name: string;
season_id: number;
season_number: number | null;
episode_number: number;
runtime: number | null;
still_path: string | null;
}
export interface HistoryEvent {
id: string;
seen_id: number;
kind: "movie" | "episode";
entry_id: number;
date_seen: string;
accuracy: WatchAccuracy;
buddies: { id: number; name: string }[];
episode?: HistoryEpisode | null;
}
export interface HistoryYearData {
year: number;
entries: Record<number, HistoryEntry>;
events: HistoryEvent[];
}
export const historyApi = {
getYears: () => api.get<HistoryYear[]>("/history/years").then((r) => r.data),
getYear: (year: number) =>
api.get<HistoryYearData>(`/history/${year}`).then((r) => r.data),
};
+40
View File
@@ -11,7 +11,47 @@ export interface OrphanPeopleResult {
count: number; count: number;
} }
export interface StaleRefreshJob {
running: boolean;
hours?: number;
total?: number;
done?: number;
succeeded?: number;
failed?: { id: number; title: string; error: string }[];
current?: { id: number; title: string } | null;
cancelRequested?: boolean;
startedAt?: string;
finishedAt?: string | null;
}
export interface StaleEntriesResult {
count: number;
hours: number;
job: StaleRefreshJob;
}
export const maintenanceApi = { export const maintenanceApi = {
getStaleEntries: (hours = 24) =>
api
.get<StaleEntriesResult>("/maintenance/stale-entries", {
params: { hours },
})
.then((r) => r.data),
// 409 means a job is already running; its status is returned either way
startStaleRefresh: (hours = 24) =>
api
.post<StaleRefreshJob>("/maintenance/stale-entries/refresh", null, {
params: { hours },
validateStatus: (s) => s === 202 || s === 409,
})
.then((r) => r.data),
cancelStaleRefresh: () =>
api
.delete<StaleRefreshJob>("/maintenance/stale-entries/refresh")
.then((r) => r.data),
scanOrphanFiles: () => scanOrphanFiles: () =>
api.get<OrphanResult>("/maintenance/orphan-files").then((r) => r.data), api.get<OrphanResult>("/maintenance/orphan-files").then((r) => r.data),
+3
View File
@@ -17,4 +17,7 @@ export const seasonsApi = {
api.put<Season>(`/seasons/${id}`, data).then((r) => r.data), api.put<Season>(`/seasons/${id}`, data).then((r) => r.data),
delete: (id: number) => api.delete(`/seasons/${id}`).then((r) => r.data), delete: (id: number) => api.delete(`/seasons/${id}`).then((r) => r.data),
refresh: (id: number) =>
api.put<Season>(`/seasons/${id}/refresh`).then((r) => r.data),
}; };
@@ -16,6 +16,7 @@ import {
ArrowDown, ArrowDown,
CornerDownLeft, CornerDownLeft,
ArrowRight, ArrowRight,
History,
} from "lucide-react"; } from "lucide-react";
import { tmdbApi } from "@/api/tmdb"; import { tmdbApi } from "@/api/tmdb";
import { useLibraryStore } from "@/stores/useLibraryStore"; import { useLibraryStore } from "@/stores/useLibraryStore";
@@ -53,6 +54,12 @@ const NAVIGATION_COMMANDS: CommandItem[] = [
title: "Go to Watchlist", title: "Go to Watchlist",
icon: <BookOpen className="h-4 w-4" />, 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", id: "cmd-stats",
type: "command", type: "command",
@@ -88,6 +95,7 @@ const NAVIGATION_COMMANDS: CommandItem[] = [
const COMMAND_ROUTES: Record<string, string> = { const COMMAND_ROUTES: Record<string, string> = {
"cmd-library": "/library", "cmd-library": "/library",
"cmd-watchlist": "/watchlist", "cmd-watchlist": "/watchlist",
"cmd-history": "/history",
"cmd-stats": "/dashboard", "cmd-stats": "/dashboard",
"cmd-calendar": "/calendar", "cmd-calendar": "/calendar",
"cmd-people": "/people", "cmd-people": "/people",
@@ -1,6 +1,6 @@
import { useCallback, useRef, useEffect } from "react"; import { useCallback, useRef, useEffect } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { getCollectionPosterUrl } from "@/lib/media-utils"; import { getCollectionDisplayPosterUrl } from "@/lib/collection-media";
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton";
import type { Collection } from "@/types"; import type { Collection } from "@/types";
@@ -16,7 +16,7 @@ export function CollectionCard({ collection }: CollectionCardProps) {
> >
<div className="relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-muted"> <div className="relative aspect-[2/3] w-full overflow-hidden rounded-lg bg-muted">
<img <img
src={getCollectionPosterUrl(collection)} src={getCollectionDisplayPosterUrl(collection)}
alt={collection.name} alt={collection.name}
className="h-full w-full object-cover transition-transform group-hover:scale-105" className="h-full w-full object-cover transition-transform group-hover:scale-105"
loading="lazy" loading="lazy"
@@ -13,6 +13,11 @@ import { Textarea } from "@/components/ui/textarea";
import { ImageIcon } from "lucide-react"; import { ImageIcon } from "lucide-react";
import { StarRating } from "@/components/ui/star-rating"; import { StarRating } from "@/components/ui/star-rating";
import { useUpdateCollection } from "@/hooks/useCollections"; import { useUpdateCollection } from "@/hooks/useCollections";
import {
DEFAULT_POSTER,
getCollectionDisplayBackdropUrl,
getCollectionDisplayPosterUrl,
} from "@/lib/collection-media";
import type { Collection } from "@/types"; import type { Collection } from "@/types";
interface CollectionEditDialogProps { interface CollectionEditDialogProps {
@@ -34,6 +39,14 @@ export function CollectionEditDialog({
const [posterPreview, setPosterPreview] = useState<string | null>(null); const [posterPreview, setPosterPreview] = useState<string | null>(null);
const [backdropPreview, setBackdropPreview] = useState<string | null>(null); const [backdropPreview, setBackdropPreview] = useState<string | null>(null);
// What the collection page currently shows, so the user can see what an
// upload would replace. The default placeholder doesn't count as a poster.
const displayPoster = getCollectionDisplayPosterUrl(collection);
const currentPoster = displayPoster === DEFAULT_POSTER ? null : displayPoster;
const currentBackdrop = getCollectionDisplayBackdropUrl(collection);
const shownPoster = posterPreview ?? currentPoster;
const shownBackdrop = backdropPreview ?? currentBackdrop;
const posterInputRef = useRef<HTMLInputElement>(null); const posterInputRef = useRef<HTMLInputElement>(null);
const backdropInputRef = useRef<HTMLInputElement>(null); const backdropInputRef = useRef<HTMLInputElement>(null);
@@ -131,15 +144,20 @@ export function CollectionEditDialog({
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
className="w-full h-20 flex flex-col gap-1" className="group relative w-full h-32 p-0 overflow-hidden flex flex-col gap-1"
onClick={() => posterInputRef.current?.click()} onClick={() => posterInputRef.current?.click()}
> >
{posterPreview ? ( {shownPoster ? (
<img <>
src={posterPreview} <img
alt="Poster preview" src={shownPoster}
className="h-14 w-auto rounded object-cover" alt="Poster preview"
/> className="h-full w-full object-contain bg-muted"
/>
<span className="absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100">
Change Poster
</span>
</>
) : ( ) : (
<> <>
<ImageIcon className="h-5 w-5 text-muted-foreground" /> <ImageIcon className="h-5 w-5 text-muted-foreground" />
@@ -163,15 +181,20 @@ export function CollectionEditDialog({
<Button <Button
type="button" type="button"
variant="outline" variant="outline"
className="w-full h-20 flex flex-col gap-1" className="group relative w-full h-32 p-0 overflow-hidden flex flex-col gap-1"
onClick={() => backdropInputRef.current?.click()} onClick={() => backdropInputRef.current?.click()}
> >
{backdropPreview ? ( {shownBackdrop ? (
<img <>
src={backdropPreview} <img
alt="Backdrop preview" src={shownBackdrop}
className="h-14 w-auto rounded object-cover" alt="Backdrop preview"
/> className="h-full w-full object-cover"
/>
<span className="absolute inset-0 flex items-center justify-center bg-black/50 text-xs font-medium text-white opacity-0 transition-opacity group-hover:opacity-100">
Change Backdrop
</span>
</>
) : ( ) : (
<> <>
<ImageIcon className="h-5 w-5 text-muted-foreground" /> <ImageIcon className="h-5 w-5 text-muted-foreground" />
@@ -34,10 +34,12 @@ export function ConfirmDialog({
}: ConfirmDialogProps) { }: ConfirmDialogProps) {
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent> <DialogContent className="overflow-hidden">
<DialogHeader> <DialogHeader>
<DialogTitle>{title}</DialogTitle> <DialogTitle className="break-all">{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription> <DialogDescription className="break-all">
{description}
</DialogDescription>
</DialogHeader> </DialogHeader>
<DialogFooter> <DialogFooter>
<Button <Button
@@ -9,6 +9,7 @@ import { Switch } from "@/components/ui/switch";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
import { useUpdateEntry, useUpdateEntryRatings } from "@/hooks/useEntries"; import { useUpdateEntry, useUpdateEntryRatings } from "@/hooks/useEntries";
import { StarRating } from "@/components/ui/star-rating"; import { StarRating } from "@/components/ui/star-rating";
import { useLibraryStore } from "@/stores/useLibraryStore";
import type { Entry } from "@/types"; import type { Entry } from "@/types";
interface EntrySettingsDialogProps { interface EntrySettingsDialogProps {
@@ -20,8 +21,12 @@ interface EntrySettingsDialogProps {
export function EntrySettingsDialog({ export function EntrySettingsDialog({
open, open,
onOpenChange, onOpenChange,
entry, entry: entryProp,
}: EntrySettingsDialogProps) { }: EntrySettingsDialogProps) {
// The entry prop can be a stale snapshot (e.g. from a collection query), so
// read the live copy from the library store, which updates on every mutation.
const storeEntry = useLibraryStore((s) => s.entries.get(entryProp.id));
const entry = storeEntry ? { ...entryProp, ...storeEntry } : entryProp;
const updateEntry = useUpdateEntry(); const updateEntry = useUpdateEntry();
const updateRatings = useUpdateEntryRatings(); const updateRatings = useUpdateEntryRatings();
@@ -0,0 +1,76 @@
import { useState, useEffect } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { StarRating } from "@/components/ui/star-rating";
import { useUpdateSeason } from "@/hooks/useSeasons";
import type { Season } from "@/types";
interface SeasonRatingDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
season: Season;
}
export function SeasonRatingDialog({
open,
onOpenChange,
season,
}: SeasonRatingDialogProps) {
const currentRating = season.user_rating ?? 0;
const [selected, setSelected] = useState<number>(currentRating);
const updateSeason = useUpdateSeason();
useEffect(() => {
if (open) setSelected(season.user_rating ?? 0);
}, [open, season.user_rating]);
const handleRate = (rating: number) => {
setSelected(rating);
updateSeason.mutate({
id: season.id,
data: { user_rating: rating || null },
});
onOpenChange(false);
};
const handleClear = () => {
setSelected(0);
updateSeason.mutate({
id: season.id,
data: { user_rating: null },
});
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-auto sm:max-w-none">
<DialogHeader>
<DialogTitle>Rate Season</DialogTitle>
<p className="text-sm text-muted-foreground line-clamp-1">
{season.name}
</p>
</DialogHeader>
<div className="flex flex-col items-center gap-4 py-2">
<StarRating value={selected} onChange={handleRate} size="lg" />
<p className="text-xl font-semibold tabular-nums">
{selected > 0 ? `${selected} / 10` : "—"}
</p>
{(selected > 0 || currentRating > 0) && (
<Button variant="ghost" size="sm" onClick={handleClear}>
Clear rating
</Button>
)}
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,168 @@
import { useState } from "react";
import { Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Progress } from "@/components/ui/progress";
import { VideoDropzone } from "./VideoDropzone";
import { EntryMultiSelect } from "./EntryMultiSelect";
import { useLibrary } from "@/hooks/useEntries";
import { useUploadVideos, useUpdateVideo } from "@/hooks/useDiscoveryVideos";
import type { DiscoveryVideo } from "@/types";
interface AddVideoDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
/** When set, the dialog runs in edit mode (no file dropzone). */
video?: DiscoveryVideo | null;
}
export function AddVideoDialog({
open,
onOpenChange,
video,
}: AddVideoDialogProps) {
const isEdit = !!video;
const [files, setFiles] = useState<File[]>([]);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [entryIds, setEntryIds] = useState<number[]>([]);
const [progress, setProgress] = useState<number | null>(null);
const uploadVideos = useUploadVideos();
const updateVideo = useUpdateVideo();
// Warm the library store so the entry picker has data.
useLibrary();
// Reset form state whenever the dialog opens (or switches between
// create/edit mode) — the render-phase pattern from the React docs,
// which avoids cascading renders from setState-in-effect.
const [prevOpen, setPrevOpen] = useState(open);
const [prevVideo, setPrevVideo] = useState(video);
if (open !== prevOpen || video !== prevVideo) {
setPrevOpen(open);
setPrevVideo(video);
if (open) {
setFiles([]);
setTitle(video?.title ?? "");
setDescription(video?.description ?? "");
setEntryIds(video?.entries?.map((e) => e.id) ?? []);
setProgress(null);
}
}
const isBusy = uploadVideos.isPending || updateVideo.isPending;
const handleSubmit = () => {
if (isEdit && video) {
updateVideo.mutate(
{ id: video.id, data: { title, description, entryIds } },
{ onSuccess: () => onOpenChange(false) },
);
return;
}
if (files.length === 0) return;
const formData = new FormData();
files.forEach((file) => formData.append("videos", file));
formData.append("description", description);
formData.append("entryIds", JSON.stringify(entryIds));
uploadVideos.mutate(
{ formData, onProgress: setProgress },
{ onSuccess: () => onOpenChange(false) },
);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="overflow-hidden sm:max-w-xl">
<DialogHeader>
<DialogTitle>{isEdit ? "Edit video" : "Add media"}</DialogTitle>
<DialogDescription>
{isEdit
? "Update the video details and linked library entries."
: "Drop your videos, add a description, and link them to library entries."}
</DialogDescription>
</DialogHeader>
<div className="min-w-0 space-y-4">
{!isEdit && (
<VideoDropzone
files={files}
onChange={setFiles}
disabled={isBusy}
/>
)}
{isEdit && (
<div className="space-y-1.5">
<Label htmlFor="video-title">Title</Label>
<Input
id="video-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
disabled={isBusy}
/>
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="video-description">Description</Label>
<Textarea
id="video-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="What is this video about? Why did you save it?"
rows={3}
disabled={isBusy}
/>
</div>
<EntryMultiSelect
value={entryIds}
onChange={setEntryIds}
disabled={isBusy}
/>
{progress !== null && !isEdit && (
<Progress value={progress} />
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isBusy}
>
Cancel
</Button>
<Button
onClick={handleSubmit}
disabled={isBusy || (!isEdit && files.length === 0)}
>
{isBusy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isEdit
? "Save changes"
: files.length > 0
? `Upload (${files.length})`
: "Upload"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,162 @@
import { useMemo, useState } from "react";
import { Link2, Search, X } from "lucide-react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Checkbox } from "@/components/ui/checkbox";
import { useLibraryEntries } from "@/stores/useLibraryStore";
import { useDebounce } from "@/hooks/useDebounce";
import { getPosterUrl } from "@/lib/media-utils";
import { cn } from "@/lib/utils";
interface EntryMultiSelectProps {
value: number[];
onChange: (ids: number[]) => void;
disabled?: boolean;
}
export function EntryMultiSelect({
value,
onChange,
disabled,
}: EntryMultiSelectProps) {
const entries = useLibraryEntries();
const [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 250);
const hasQuery = debouncedSearch.trim().length > 0;
// Only list entries once the user starts searching (debounced)
const visibleEntries = useMemo(() => {
if (!hasQuery) return [];
const q = debouncedSearch.trim().toLowerCase();
return entries
.filter((e) => !e.hidden)
.filter((e) => e.title.toLowerCase().includes(q));
}, [entries, debouncedSearch, hasQuery]);
const selectedEntries = useMemo(
() => entries.filter((e) => value.includes(e.id)),
[entries, value],
);
const toggle = (id: number) => {
onChange(
value.includes(id) ? value.filter((v) => v !== id) : [...value, id],
);
};
return (
<div className="space-y-2">
<Popover>
<PopoverTrigger
disabled={disabled}
className={cn(
"inline-flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-3 text-sm transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-50",
)}
>
<Link2 className="size-4" />
Link library entries
{value.length > 0 && (
<span className="rounded-full bg-primary px-1.5 py-0.5 text-[10px] font-medium text-primary-foreground">
{value.length}
</span>
)}
</PopoverTrigger>
<PopoverContent className="w-80 p-0">
<div className="border-b p-2">
<div className="relative">
<Search className="absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search library…"
className="pl-7"
/>
</div>
</div>
<ScrollArea className="h-64">
{!hasQuery ? (
<p className="p-4 text-center text-sm text-muted-foreground">
Type to search your library…
</p>
) : visibleEntries.length === 0 ? (
<p className="p-4 text-center text-sm text-muted-foreground">
No entries found.
</p>
) : (
<div className="p-1">
{visibleEntries.map((entry) => (
<div
key={entry.id}
role="button"
tabIndex={0}
onClick={() => toggle(entry.id)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggle(entry.id);
}
}}
className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 outline-none hover:bg-accent focus-visible:bg-accent"
>
<Checkbox
checked={value.includes(entry.id)}
onCheckedChange={() => toggle(entry.id)}
onClick={(e) => e.stopPropagation()}
tabIndex={-1}
/>
<img
src={getPosterUrl(entry)}
alt=""
loading="lazy"
className="h-9 w-6 shrink-0 rounded object-cover"
/>
<span className="flex-1 truncate text-sm">
{entry.title}
</span>
{entry.is_tvseries && (
<span className="shrink-0 text-[10px] uppercase text-muted-foreground">
TV
</span>
)}
</div>
))}
</div>
)}
</ScrollArea>
</PopoverContent>
</Popover>
{selectedEntries.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{selectedEntries.map((entry) => (
<span
key={entry.id}
className="inline-flex items-center gap-1 rounded-full bg-accent px-2 py-0.5 text-xs text-accent-foreground"
>
{entry.title}
<Button
type="button"
variant="ghost"
size="icon-xs"
disabled={disabled}
onClick={() => toggle(entry.id)}
className="text-muted-foreground hover:text-foreground"
>
<X />
</Button>
</span>
))}
</div>
)}
</div>
);
}
@@ -0,0 +1,120 @@
import { useState } from "react";
import { Link } from "react-router-dom";
import { Film, Pencil, Play, Trash2 } from "lucide-react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { getVideoThumbnailUrl } from "@/lib/api";
import { formatBytes } from "@/lib/format";
import type { DiscoveryVideo } from "@/types";
interface VideoCardProps {
video: DiscoveryVideo;
onPlay: (video: DiscoveryVideo) => void;
onEdit: (video: DiscoveryVideo) => void;
onDelete: (video: DiscoveryVideo) => void;
}
export function VideoCard({ video, onPlay, onEdit, onDelete }: VideoCardProps) {
// If the thumbnail request fails (e.g. unplayable file), fall back to
// the placeholder instead of showing a broken image.
const [thumbFailed, setThumbFailed] = useState(false);
return (
<Card className="group flex h-full flex-col overflow-hidden">
{/* Thumbnail + play overlay → opens the player dialog */}
<div
role="button"
tabIndex={0}
onClick={() => onPlay(video)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onPlay(video);
}
}}
className="relative h-44 w-full cursor-pointer overflow-hidden bg-muted outline-none"
>
{/* Placeholder (visible while the thumbnail loads or if it fails) */}
<div className="absolute inset-0 flex items-center justify-center">
<Film className="h-8 w-8 text-muted-foreground/40" />
</div>
{/* Requesting the thumbnail also triggers on-demand generation
server-side when the video doesn't have one yet. */}
{!thumbFailed && (
<img
src={getVideoThumbnailUrl(video.id)}
alt={video.title}
loading="lazy"
onError={() => setThumbFailed(true)}
className="relative h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
/>
)}
<div className="absolute inset-0 flex items-center justify-center bg-black/30 transition-colors hover:bg-black/20">
<span className="flex h-12 w-12 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-lg transition-transform group-hover:scale-110">
<Play className="ml-1 h-5 w-5" />
</span>
</div>
<div
className="absolute right-2 top-2 z-10 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100"
onClick={(e) => e.stopPropagation()}
>
<Button
variant="secondary"
size="icon-sm"
onClick={() => onEdit(video)}
aria-label="Edit video"
>
<Pencil />
</Button>
<Button
variant="destructive"
size="icon-sm"
onClick={() => onDelete(video)}
aria-label="Delete video"
>
<Trash2 />
</Button>
</div>
</div>
<div className="flex flex-col gap-2 p-3">
<div className="flex h-5 items-start justify-between gap-2">
<h3
className="line-clamp-1 min-w-0 break-all text-sm font-medium"
title={video.title}
>
{video.title}
</h3>
<span className="shrink-0 text-[10px] text-muted-foreground">
{formatBytes(video.size)}
</span>
</div>
{/* Fixed-height description area keeps all cards the same size */}
<p className="h-8 line-clamp-2 text-xs text-muted-foreground">
{video.description || ""}
</p>
{/* Single-row chips — extra entries get clipped, never grow the card */}
<div className="h-5 overflow-hidden">
{video.entries && video.entries.length > 0 && (
<div className="flex gap-1.5 overflow-hidden">
{video.entries.map((entry) => (
<Link
key={entry.id}
to={`/entry/${entry.id}`}
className="shrink-0 rounded-full bg-accent px-2 py-0.5 text-[10px] text-accent-foreground transition-colors hover:bg-accent/70"
>
{entry.title}
</Link>
))}
</div>
)}
</div>
</div>
</Card>
);
}
@@ -0,0 +1,134 @@
import { useRef, useState, type DragEvent } from "react";
import { FileVideo, UploadCloud, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatBytes } from "@/lib/format";
const ALLOWED_MIME = [
"video/mp4",
"video/webm",
"video/quicktime",
"video/x-matroska",
"video/x-msvideo",
];
const ALLOWED_EXT = ["mp4", "webm", "mov", "m4v", "mkv", "avi"];
const MAX_FILES = 10;
function isAccepted(file: File) {
if (ALLOWED_MIME.includes(file.type)) return true;
const ext = file.name.split(".").pop()?.toLowerCase() ?? "";
return ALLOWED_EXT.includes(ext);
}
interface VideoDropzoneProps {
files: File[];
onChange: (files: File[]) => void;
disabled?: boolean;
}
export function VideoDropzone({ files, onChange, disabled }: VideoDropzoneProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [dragActive, setDragActive] = useState(false);
const addFiles = (incoming: FileList | null) => {
if (!incoming || disabled) return;
const existing = new Set(files.map((f) => `${f.name}:${f.size}`));
const fresh = Array.from(incoming)
.filter(isAccepted)
.filter((f) => !existing.has(`${f.name}:${f.size}`))
.slice(0, MAX_FILES - files.length);
if (fresh.length > 0) {
onChange([...files, ...fresh]);
}
};
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setDragActive(false);
addFiles(e.dataTransfer.files);
};
return (
<div className="space-y-3">
<div
role="button"
tabIndex={0}
onClick={() => inputRef.current?.click()}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
inputRef.current?.click();
}
}}
onDragOver={(e) => {
e.preventDefault();
setDragActive(true);
}}
onDragLeave={() => setDragActive(false)}
onDrop={handleDrop}
className={cn(
"flex cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-8 text-center outline-none transition-colors",
dragActive ? "border-primary bg-primary/5" : "border-border",
disabled && "pointer-events-none opacity-50",
)}
>
<UploadCloud className="h-8 w-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
Drag &amp; drop videos here, or{" "}
<span className="font-medium text-primary underline">
browse files
</span>
</p>
<p className="text-xs text-muted-foreground/70">
mp4, webm, mov, m4v, mkv, avi — up to 10 files per upload
</p>
<input
ref={inputRef}
type="file"
accept="video/*"
multiple
className="hidden"
onChange={(e) => {
addFiles(e.target.files);
e.target.value = "";
}}
/>
</div>
{files.length > 0 && (
<ul className="max-h-44 space-y-1.5 overflow-y-auto pr-1">
{files.map((file, index) => (
<li
key={`${file.name}-${file.size}-${index}`}
className="flex items-center gap-2 rounded-md border px-3 py-2 text-sm"
>
<FileVideo className="size-4 shrink-0 text-muted-foreground" />
{/* break-all: a long filename wraps instead of forcing the
dialog wider; line-clamp caps it at two lines */}
<span
className="min-w-0 flex-1 break-all line-clamp-2"
title={file.name}
>
{file.name}
</span>
<span className="shrink-0 text-xs text-muted-foreground">
{formatBytes(file.size)}
</span>
<button
type="button"
disabled={disabled}
onClick={() =>
onChange(files.filter((_, idx) => idx !== index))
}
className="shrink-0 text-muted-foreground transition-colors hover:text-foreground"
>
<X className="size-4" />
</button>
</li>
))}
</ul>
)}
</div>
);
}
@@ -0,0 +1,175 @@
import { useEffect, useRef } from "react";
import { Link } from "react-router-dom";
import { ChevronDown, ChevronUp, Pencil } from "lucide-react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { getVideoStreamUrl } from "@/lib/api";
import { formatBytes } from "@/lib/format";
import type { DiscoveryVideo } from "@/types";
interface VideoPlayerDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
video: DiscoveryVideo | null;
onPrevious?: () => void;
onNext?: () => void;
hasPrevious?: boolean;
hasNext?: boolean;
onEdit?: (video: DiscoveryVideo) => void;
}
export function VideoPlayerDialog({
open,
onOpenChange,
video,
onPrevious,
onNext,
hasPrevious,
hasNext,
onEdit,
}: VideoPlayerDialogProps) {
const videoRef = useRef<HTMLVideoElement>(null);
// Autoplay when the dialog opens or the video changes. The play() call may
// be blocked if the browser considers the gesture consumed — the user can
// always press play manually.
useEffect(() => {
if (open && video) {
videoRef.current?.play().catch(() => {});
}
}, [open, video]);
// Arrow-key navigation. ↑/↓ always switch videos (when available) and are
// captured in the CAPTURE phase with preventDefault, so they never reach
// the <video> element's native controls or move focus onto the player.
// ←/→ switch videos too, except when the player itself is focused — there
// they keep their native seek behaviour.
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
const isVideoFocused = e.target instanceof HTMLVideoElement;
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
if (e.key === "ArrowUp" && hasPrevious) onPrevious?.();
if (e.key === "ArrowDown" && hasNext) onNext?.();
return;
}
if (
!isVideoFocused &&
(e.key === "ArrowLeft" || e.key === "ArrowRight")
) {
e.preventDefault();
if (e.key === "ArrowLeft" && hasPrevious) onPrevious?.();
if (e.key === "ArrowRight" && hasNext) onNext?.();
}
};
window.addEventListener("keydown", onKey, true);
return () => window.removeEventListener("keydown", onKey, true);
}, [open, hasPrevious, hasNext, onPrevious, onNext]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="overflow-hidden sm:max-w-4xl">
<DialogHeader>
<DialogTitle className="truncate pr-8">{video?.title}</DialogTitle>
</DialogHeader>
{open && video && (
<div className="space-y-4">
<div className="relative bg-black">
{/* tabIndex=-1 keeps the player out of the focus order so the
dialog doesn't focus it and arrow keys stay ours */}
<video
key={video.id}
ref={videoRef}
src={getVideoStreamUrl(video.id)}
controls
autoPlay
tabIndex={-1}
onKeyDown={(e) => {
if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
}
}}
className="max-h-[65vh] w-full"
/>
{hasPrevious && (
<Button
variant="secondary"
size="icon"
onClick={onPrevious}
aria-label="Previous video"
className="absolute left-2 top-1/2 -translate-y-1/2 opacity-70"
>
<ChevronUp />
</Button>
)}
{hasNext && (
<Button
variant="secondary"
size="icon"
onClick={onNext}
aria-label="Next video"
className="absolute right-2 top-1/2 -translate-y-1/2 opacity-70"
>
<ChevronDown />
</Button>
)}
</div>
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs text-muted-foreground">
{formatBytes(video.size)}
</span>
<div className="flex flex-wrap items-center gap-1.5">
{video.entries?.map((entry) => (
<Link
key={entry.id}
to={`/entry/${entry.id}`}
onClick={() => onOpenChange(false)}
className="rounded-full bg-accent px-2 py-0.5 text-[10px] text-accent-foreground transition-colors hover:bg-accent/70"
>
{entry.title}
</Link>
))}
{onEdit && (
<Button
variant="ghost"
size="xs"
onClick={() => onEdit(video)}
>
<Pencil />
Edit
</Button>
)}
</div>
</div>
{video.description && (
<p className="text-sm text-muted-foreground">
{video.description}
</p>
)}
{(hasPrevious || hasNext) && (
<p className="text-center text-[10px] text-muted-foreground/60">
Use ↑ / ↓ to switch videos
</p>
)}
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,445 @@
import { useEffect, useMemo, useState } from "react";
import { Check, Download, Loader2, Star } from "lucide-react";
import { useAddArtwork, useArtwork } from "@/hooks/useEntries";
import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import type { ArtworkItem, ArtworkType } from "@/types";
// Rows shown at first and added per "Show more"
const ROWS_STEP = 2;
// Checkerboard behind logos so transparent/dark logos stay visible
const CHECKER =
"bg-[repeating-conic-gradient(#8883_0_25%,transparent_0_50%)] bg-size-[16px_16px]";
const TYPES: {
type: ArtworkType;
key: "posters" | "backdrops" | "logos";
label: string;
thumbSize: string;
grid: string;
/** Columns per breakpoint; must match `grid` */
cols: { base: number; sm?: number; md?: number; xl?: number };
aspect: string;
}[] = [
{
type: "poster",
key: "posters",
label: "Posters",
thumbSize: "w342",
grid: "grid-cols-3 sm:grid-cols-4 md:grid-cols-5 xl:grid-cols-6",
cols: { base: 3, sm: 4, md: 5, xl: 6 },
aspect: "aspect-2/3",
},
{
type: "backdrop",
key: "backdrops",
label: "Backdrops",
thumbSize: "w780",
grid: "grid-cols-1 sm:grid-cols-2 xl:grid-cols-3",
cols: { base: 1, sm: 2, xl: 3 },
aspect: "aspect-video",
},
{
type: "logo",
key: "logos",
label: "Logos",
thumbSize: "w500",
grid: "grid-cols-2 sm:grid-cols-3 xl:grid-cols-4",
cols: { base: 2, sm: 3, xl: 4 },
aspect: "aspect-[2/1]",
},
];
const languageName = (() => {
try {
const names = new Intl.DisplayNames(["en"], { type: "language" });
return (code: string) => names.of(code) ?? code;
} catch {
return (code: string) => code;
}
})();
function imageUrls(item: ArtworkItem, type: ArtworkType, thumbSize: string) {
if (item.file_path) {
return {
thumb: getTmdbImageUrl(item.file_path, thumbSize),
full: getTmdbImageUrl(item.file_path, "original"),
};
}
const folder = `${type}s`;
return {
thumb: getMediaUrl("entries", folder, "preview", item.media_path!),
full: getMediaUrl("entries", folder, "full", item.media_path!),
};
}
const BREAKPOINTS = [
["xl", 1280],
["md", 768],
["sm", 640],
] as const;
/** Current column count for a grid, following the Tailwind breakpoints. */
function useGridColumns(cols: {
base: number;
sm?: number;
md?: number;
xl?: number;
}) {
const compute = () => {
for (const [bp, minWidth] of BREAKPOINTS) {
const value = cols[bp];
if (value && window.matchMedia(`(min-width: ${minWidth}px)`).matches) {
return value;
}
}
return cols.base;
};
const [columns, setColumns] = useState(compute);
useEffect(() => {
const update = () => setColumns(compute());
update();
const queries = BREAKPOINTS.map(([, w]) =>
window.matchMedia(`(min-width: ${w}px)`),
);
queries.forEach((q) => q.addEventListener("change", update));
return () =>
queries.forEach((q) => q.removeEventListener("change", update));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cols.base, cols.sm, cols.md, cols.xl]);
return columns;
}
const itemKey = (item: ArtworkItem) =>
item.file_path ?? `media-${item.media_id}`;
/**
* Posters, backdrops and logos from TMDB merged with the entry's media table.
* For library entries, TMDB images can be added (downloaded) to the library.
*/
export function ArtworkSection({
entryId = 0,
tmdbId = 0,
isTvSeries,
originalLanguage,
}: {
entryId?: number;
tmdbId?: number;
isTvSeries: boolean;
originalLanguage?: string | null;
}) {
const isLibrary = !!entryId;
const { data, isLoading, isError } = useArtwork(
isLibrary ? { entryId } : { tmdbId, type: isTvSeries ? "tv" : "movie" },
);
const addArtwork = useAddArtwork(entryId);
const [activeType, setActiveType] = useState<ArtworkType>("poster");
const [language, setLanguage] = useState("all");
const [libraryOnly, setLibraryOnly] = useState(false);
const [rows, setRows] = useState(ROWS_STEP);
const [pendingPath, setPendingPath] = useState<string | null>(null);
const [viewing, setViewing] = useState<ArtworkItem | null>(null);
const config = TYPES.find((t) => t.type === activeType)!;
const columns = useGridColumns(config.cols);
const visible = columns * rows;
const items = useMemo(() => data?.[config.key] ?? [], [data, config.key]);
// Languages present for this type, most common first ("none" = no text)
const languages = useMemo(() => {
const counts = new Map<string, number>();
for (const item of items) {
if (!item.file_path) continue;
const lang = item.language ?? "none";
counts.set(lang, (counts.get(lang) ?? 0) + 1);
}
const preferred = ["none", "en", originalLanguage].filter(Boolean);
return [...counts.entries()].sort(([a, ca], [b, cb]) => {
const pa = preferred.indexOf(a);
const pb = preferred.indexOf(b);
if (pa !== -1 || pb !== -1)
return (pa === -1 ? 99 : pa) - (pb === -1 ? 99 : pb);
return cb - ca;
});
}, [items, originalLanguage]);
const filtered = items.filter((item) => {
if (libraryOnly && !item.in_library) return false;
if (language === "all" || !item.file_path) return true;
return (item.language ?? "none") === language;
});
const changeType = (type: ArtworkType) => {
setActiveType(type);
setLanguage("all");
setRows(ROWS_STEP);
};
const add = (item: ArtworkItem) => {
if (!item.file_path) return;
setPendingPath(item.file_path);
addArtwork.mutate(
{ type: activeType, file_path: item.file_path },
{
onSuccess: () =>
setViewing((v) =>
v?.file_path === item.file_path ? { ...v, in_library: true } : v,
),
onSettled: () => setPendingPath(null),
},
);
};
if (isError) return null;
const total = data
? data.posters.length + data.backdrops.length + data.logos.length
: 0;
if (!isLoading && total === 0) return null;
return (
<section className="space-y-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="text-lg font-semibold">Artwork</h3>
<div className="flex flex-wrap items-center gap-2">
<select
value={language}
onChange={(e) => {
setLanguage(e.target.value);
setRows(ROWS_STEP);
}}
className="h-8 rounded-md border border-border/60 bg-background px-2 text-xs"
aria-label="Language"
>
<option value="all">All languages</option>
{languages.map(([lang, count]) => (
<option key={lang} value={lang}>
{lang === "none" ? "No text" : languageName(lang)} ({count})
</option>
))}
</select>
{isLibrary && (
<Button
variant={libraryOnly ? "default" : "outline"}
size="sm"
aria-pressed={libraryOnly}
onClick={() => {
setLibraryOnly((v) => !v);
setRows(ROWS_STEP);
}}
>
<Check />
In library
</Button>
)}
</div>
</div>
<Tabs
value={activeType}
onValueChange={(v) => changeType(v as ArtworkType)}
>
<TabsList>
{TYPES.map((t) => (
<TabsTrigger key={t.type} value={t.type}>
{t.label}
{data && (
<span className="ml-1 text-muted-foreground tabular-nums">
{data[t.key].length}
</span>
)}
</TabsTrigger>
))}
</TabsList>
</Tabs>
{isLoading ? (
<div className={`grid gap-3 ${config.grid}`}>
{Array.from({ length: columns * ROWS_STEP }).map((_, i) => (
<Skeleton key={i} className={`${config.aspect} rounded-lg`} />
))}
</div>
) : filtered.length === 0 ? (
<p className="text-sm text-muted-foreground">
No {config.label.toLowerCase()} match these filters.
</p>
) : (
<>
<div className={`grid gap-3 ${config.grid}`}>
{filtered.slice(0, visible).map((item) => (
<ArtworkTile
key={itemKey(item)}
item={item}
type={activeType}
thumbSize={config.thumbSize}
aspect={config.aspect}
canAdd={isLibrary}
adding={pendingPath === item.file_path}
onAdd={() => add(item)}
onOpen={() => setViewing(item)}
/>
))}
</div>
{filtered.length > visible && (
<div className="flex justify-center">
<Button
variant="outline"
size="sm"
onClick={() => setRows((r) => r + ROWS_STEP)}
>
Show more ({filtered.length - visible} left)
</Button>
</div>
)}
</>
)}
<Dialog
open={!!viewing}
onOpenChange={(open) => !open && setViewing(null)}
>
<DialogContent className="w-auto max-w-[calc(100%-2rem)] sm:max-w-[calc(100%-2rem)] gap-3 p-3">
<DialogTitle className="sr-only">{config.label} preview</DialogTitle>
{viewing && (
<>
<img
src={imageUrls(viewing, activeType, config.thumbSize).full}
alt=""
className={`max-h-[80vh] max-w-full rounded-lg object-contain ${
activeType === "logo" ? `${CHECKER} p-4` : ""
}`}
/>
<div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">
<span>
{viewing.width && viewing.height
? `${viewing.width}×${viewing.height}`
: "Local file"}
{viewing.file_path &&
` · ${viewing.language ? languageName(viewing.language) : "No text"}`}
</span>
{viewing.in_library ? (
<LibraryBadge selected={viewing.is_selected} />
) : (
isLibrary &&
viewing.file_path && (
<Button
size="sm"
onClick={() => add(viewing)}
disabled={pendingPath === viewing.file_path}
>
{pendingPath === viewing.file_path ? (
<Loader2 className="animate-spin" />
) : (
<Download />
)}
Add to library
</Button>
)
)}
</div>
</>
)}
</DialogContent>
</Dialog>
</section>
);
}
function LibraryBadge({ selected }: { selected?: boolean }) {
return (
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/90 px-2 py-0.5 text-[10px] font-semibold text-white shadow">
<Check className="h-3 w-3" />
{selected ? "Selected" : "In library"}
</span>
);
}
function ArtworkTile({
item,
type,
thumbSize,
aspect,
canAdd,
adding,
onAdd,
onOpen,
}: {
item: ArtworkItem;
type: ArtworkType;
thumbSize: string;
aspect: string;
canAdd: boolean;
adding: boolean;
onAdd: () => void;
onOpen: () => void;
}) {
const { thumb } = imageUrls(item, type, thumbSize);
return (
<div
className={`group relative overflow-hidden rounded-lg bg-muted ring-1 ${
item.in_library ? "ring-emerald-500/60" : "ring-border/60"
} ${aspect}`}
>
<button
type="button"
onClick={onOpen}
className="block h-full w-full cursor-zoom-in"
aria-label="View full size"
>
<img
src={thumb}
alt=""
loading="lazy"
className={`h-full w-full transition-transform duration-300 group-hover:scale-[1.03] ${
type === "logo" ? `${CHECKER} object-contain p-3` : "object-cover"
}`}
/>
</button>
{/* Top: library badge / language */}
<div className="pointer-events-none absolute inset-x-1.5 top-1.5 flex items-start justify-between gap-1">
{item.in_library ? (
<LibraryBadge selected={item.is_selected} />
) : (
<span />
)}
{item.file_path && item.language && (
<span className="rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium uppercase text-white">
{item.language}
</span>
)}
</div>
{/* Bottom: votes + add */}
<div className="absolute inset-x-1.5 bottom-1.5 flex items-end justify-between gap-1 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100">
{item.vote_count > 0 ? (
<span className="inline-flex items-center gap-0.5 rounded bg-black/60 px-1.5 py-0.5 text-[10px] text-white tabular-nums">
<Star className="h-2.5 w-2.5 fill-yellow-400 text-yellow-400" />
{item.vote_average.toFixed(1)}
</span>
) : (
<span />
)}
{canAdd && !item.in_library && item.file_path && (
<Button
size="xs"
onClick={onAdd}
disabled={adding}
className="shadow"
aria-label="Add to library"
>
{adding ? <Loader2 className="animate-spin" /> : <Download />}
Add
</Button>
)}
</div>
</div>
);
}
@@ -13,6 +13,8 @@ interface CastListProps {
maxItems?: number; maxItems?: number;
/** Override link for "All Cast & Crew" — if unset, uses /entry/:entryId/cast */ /** Override link for "All Cast & Crew" — if unset, uses /entry/:entryId/cast */
allCastHref?: string; allCastHref?: string;
/** Section heading (default: "Cast") */
title?: string;
} }
export function CastList({ export function CastList({
@@ -21,6 +23,7 @@ export function CastList({
isTvSeries, isTvSeries,
maxItems, maxItems,
allCastHref, allCastHref,
title = "Cast",
}: CastListProps) { }: CastListProps) {
let castCredits = credits.filter((c) => c.cast_type === "cast"); let castCredits = credits.filter((c) => c.cast_type === "cast");
const hasMore = maxItems != null && castCredits.length > maxItems; const hasMore = maxItems != null && castCredits.length > maxItems;
@@ -36,7 +39,7 @@ export function CastList({
return ( return (
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Cast</h3> <h3 className="text-lg font-semibold">{title}</h3>
{allCastLink && ( {allCastLink && (
<Link <Link
to={allCastLink} to={allCastLink}
@@ -0,0 +1,55 @@
import {
useEntryRecommendations,
useTmdbRecommendations,
} from "@/hooks/useEntries";
import { EntryCard } from "@/components/entries/EntryCard";
import { Skeleton } from "@/components/ui/skeleton";
const GRID =
"grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-6";
const MAX_ITEMS = 12;
/**
* "More like this": live TMDB recommendations. Pass `entryId` for a library
* entry, or `tmdbId` for one that is not in the library.
*/
export function RecommendationsSection({
entryId = 0,
tmdbId = 0,
isTvSeries,
}: {
entryId?: number;
tmdbId?: number;
isTvSeries: boolean;
}) {
const type = isTvSeries ? "tv" : "movie";
const library = useEntryRecommendations(entryId);
const tmdb = useTmdbRecommendations(entryId ? 0 : tmdbId, type);
const { data, isLoading, isError } = entryId ? library : tmdb;
if (isError) return null;
const results = (data?.results ?? [])
.filter((r) => r.poster_path)
.slice(0, MAX_ITEMS)
// Recommendations don't always carry media_type; it matches the entry's
.map((r) => ({
...r,
media_type: r.media_type ?? (isTvSeries ? "tv" : "movie"),
}));
if (!isLoading && results.length === 0) return null;
return (
<section className="space-y-3">
<h3 className="text-lg font-semibold">More like this</h3>
<div className={GRID}>
{isLoading
? Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 rounded-lg" />
))
: results.map((r) => <EntryCard key={r.id} tmdbEntry={r} />)}
</div>
</section>
);
}
@@ -0,0 +1,59 @@
import { useState } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import type { TmdbVideo } from "@/types";
/** Plays an entry's stored TMDB YouTube videos; trailers come first. */
export function TrailerDialog({
open,
onOpenChange,
title,
videos,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
videos: TmdbVideo[];
}) {
const [activeKey, setActiveKey] = useState(videos[0]?.key);
const active = videos.find((v) => v.key === activeKey) ?? videos[0];
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-full max-w-4xl! gap-3 p-3">
<DialogTitle className="pr-8 text-sm">
{title} · {active?.name}
</DialogTitle>
{active && (
<div className="aspect-video w-full overflow-hidden rounded-lg bg-black">
<iframe
key={active.key}
src={`https://www.youtube-nocookie.com/embed/${active.key}?autoplay=1&rel=0`}
title={active.name}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
className="h-full w-full"
/>
</div>
)}
{videos.length > 1 && (
<div className="flex gap-2 overflow-x-auto pb-1">
{videos.map((v) => (
<button
key={v.key}
type="button"
onClick={() => setActiveKey(v.key)}
className={`shrink-0 rounded-md border px-2.5 py-1 text-xs transition-colors ${
v.key === active?.key
? "border-foreground/30 bg-accent font-medium"
: "border-border/60 text-muted-foreground hover:text-foreground"
}`}
>
{v.type}: {v.name}
</button>
))}
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,121 @@
import { useState } from "react";
import { ExternalLink } from "lucide-react";
import { getTmdbImageUrl } from "@/lib/api";
import type { WatchProvider, WatchProviderRegion } from "@/types";
const CATEGORIES: { key: keyof WatchProviderRegion; label: string }[] = [
{ key: "flatrate", label: "Stream" },
{ key: "free", label: "Free" },
{ key: "ads", label: "With ads" },
{ key: "rent", label: "Rent" },
{ key: "buy", label: "Buy" },
];
/** Country from the browser locale (en-US → US), falling back to US. */
function defaultRegion(available: string[]): string {
const fromLocale = navigator.language?.split("-")[1]?.toUpperCase();
if (fromLocale && available.includes(fromLocale)) return fromLocale;
if (available.includes("US")) return "US";
return available[0];
}
const regionName = (() => {
try {
const names = new Intl.DisplayNames(["en"], { type: "region" });
return (code: string) => names.of(code) ?? code;
} catch {
return (code: string) => code;
}
})();
export function WatchProvidersCard({
providers,
}: {
providers: Record<string, WatchProviderRegion> | null | undefined;
}) {
const regions = Object.keys(providers ?? {}).sort((a, b) =>
regionName(a).localeCompare(regionName(b)),
);
const [region, setRegion] = useState(() =>
regions.length ? defaultRegion(regions) : "",
);
if (!providers || regions.length === 0) return null;
const info = providers[region] ?? providers[regions[0]];
const groups = CATEGORIES.map((c) => ({
...c,
list: (info[c.key] as WatchProvider[] | null | undefined) ?? [],
})).filter((g) => g.list.length > 0);
return (
<div className="rounded-xl border border-border/60 bg-card/50 p-4">
<div className="mb-3 flex items-center justify-between gap-2">
<h3 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Where to watch
</h3>
<select
value={region}
onChange={(e) => setRegion(e.target.value)}
className="max-w-36 rounded-md border border-border/60 bg-background px-1.5 py-0.5 text-xs"
aria-label="Country"
>
{regions.map((r) => (
<option key={r} value={r}>
{regionName(r)}
</option>
))}
</select>
</div>
{groups.length === 0 ? (
<p className="text-sm text-muted-foreground">
Not available in {regionName(region)}.
</p>
) : (
<div className="space-y-3">
{groups.map((g) => (
<div key={g.key} className="space-y-1.5">
<p className="text-[11px] font-medium text-muted-foreground">
{g.label}
</p>
<div className="flex flex-wrap gap-1.5">
{g.list
.slice()
.sort(
(a, b) =>
(a.display_priority ?? 99) - (b.display_priority ?? 99),
)
.map((p) => (
<img
key={p.provider_id}
src={
p.logo_path
? getTmdbImageUrl(p.logo_path, "w92")
: undefined
}
alt={p.provider_name}
title={p.provider_name}
className="h-9 w-9 rounded-lg object-cover ring-1 ring-border/60"
/>
))}
</div>
</div>
))}
</div>
)}
{info.link && (
<a
href={info.link}
target="_blank"
rel="noopener noreferrer"
className="mt-3 inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
<ExternalLink className="h-3 w-3" />
Data from JustWatch via TMDB
</a>
)}
</div>
);
}
@@ -0,0 +1,136 @@
import { Link } from "react-router-dom";
import { Film, Tv, Users } from "lucide-react";
import {
MONTH_NAMES,
formatMinutes,
posterUrl,
sessionEpisodeLabel,
sessionLink,
type HistorySession,
type MonthGroup,
} from "@/lib/history";
/** Month sections (newest first), each split into days. */
export function HistoryList({ months }: { months: MonthGroup[] }) {
return (
<div className="space-y-10">
{months.map((m) => (
<section key={m.month} className="space-y-3">
<header className="sticky top-0 z-10 -mx-1 flex flex-wrap items-baseline justify-between gap-2 border-b border-border/60 bg-background/90 px-1 py-2 backdrop-blur">
<h2 className="text-xl font-bold tracking-tight">
{MONTH_NAMES[m.month]}
</h2>
<p className="text-xs text-muted-foreground tabular-nums">
{[
m.movies > 0 &&
`${m.movies} ${m.movies === 1 ? "movie" : "movies"}`,
m.episodes > 0 &&
`${m.episodes} ${m.episodes === 1 ? "episode" : "episodes"}`,
m.minutes > 0 && formatMinutes(m.minutes),
]
.filter(Boolean)
.join(" · ")}
</p>
</header>
<div className="space-y-5">
{groupByDay(m.sessions).map(([day, sessions]) => (
<div key={day} className="grid gap-2 sm:grid-cols-[7rem_1fr]">
<p className="pt-2 text-sm font-medium text-muted-foreground">
{new Date(sessions[0].date).toLocaleDateString("en-US", {
weekday: "short",
month: "short",
day: "numeric",
})}
</p>
<div className="space-y-1.5">
{sessions.map((s) => (
<HistoryRow key={s.key} session={s} />
))}
</div>
</div>
))}
</div>
</section>
))}
</div>
);
}
function groupByDay(sessions: HistorySession[]) {
const days = new Map<string, HistorySession[]>();
for (const s of sessions) {
const list = days.get(s.day) ?? [];
list.push(s);
days.set(s.day, list);
}
return [...days.entries()];
}
function HistoryRow({ session }: { session: HistorySession }) {
const entry = session.entry;
const isMovie = session.kind === "movie";
const single = session.events.length === 1 ? session.events[0] : null;
const buddies = [
...new Map(
session.events.flatMap((e) => e.buddies).map((b) => [b.id, b]),
).values(),
];
return (
<Link
to={sessionLink(session)}
className="group flex items-center gap-3 rounded-lg border border-transparent p-1.5 transition-colors hover:border-border/60 hover:bg-accent/40"
>
<img
src={posterUrl(entry)}
alt=""
loading="lazy"
className="h-16 w-11 shrink-0 rounded-md object-cover ring-1 ring-border/60"
/>
<div className="min-w-0 flex-1">
<p className="line-clamp-1 font-medium">
{entry?.title ?? "Unknown title"}
</p>
<p className="line-clamp-1 text-xs text-muted-foreground">
{isMovie ? (
<span className="inline-flex items-center gap-1">
<Film className="h-3 w-3" /> Movie
{entry?.release_date &&
` · ${new Date(entry.release_date).getFullYear()}`}
</span>
) : (
<span className="inline-flex items-center gap-1">
<Tv className="h-3 w-3" />
{sessionEpisodeLabel(session)}
{single?.episode?.name
? ` · ${single.episode.name}`
: ` · ${session.events.length} episodes`}
</span>
)}
</p>
</div>
<div className="flex shrink-0 flex-col items-end gap-1 text-xs text-muted-foreground">
{session.minutes > 0 && (
<span className="tabular-nums">{formatMinutes(session.minutes)}</span>
)}
{session.unknownDate && (
<span className="rounded bg-amber-500/15 px-1.5 py-px text-[10px] font-medium text-amber-600 dark:text-amber-400">
Date unknown
</span>
)}
{buddies.length > 0 && (
<span
className="inline-flex items-center gap-1"
title={buddies.map((b) => b.name).join(", ")}
>
<Users className="h-3 w-3" />
<span className="max-w-28 truncate">
{buddies.map((b) => b.name).join(", ")}
</span>
</span>
)}
</div>
</Link>
);
}
@@ -0,0 +1,152 @@
import { Link } from "react-router-dom";
import { Film, Tv } from "lucide-react";
import {
MONTH_NAMES,
formatMinutes,
posterUrl,
sessionEpisodeLabel,
sessionLink,
type HistorySession,
type MonthGroup,
} from "@/lib/history";
/**
* Vertical timeline, latest watch at the top down to January. Episodes of a
* show watched back to back on the same day are stacked into one card.
*/
export function HistoryTimeline({ months }: { months: MonthGroup[] }) {
let index = 0; // alternates sides across the whole year
return (
<div className="relative mx-auto max-w-4xl pb-6">
{/* The line */}
<div className="absolute bottom-0 left-4 top-0 w-px bg-border md:left-1/2 md:-translate-x-1/2" />
{months.map((m) => (
<section key={m.month} className="relative">
{/* Month divider */}
<div className="relative flex items-center py-6 md:justify-center">
<div className="absolute inset-x-0 top-1/2 h-px bg-linear-to-r from-transparent via-border to-transparent" />
<span className="relative ml-8 rounded-full border border-border bg-background px-4 py-1 text-sm font-semibold shadow-sm md:ml-0">
{MONTH_NAMES[m.month]}
<span className="ml-2 text-xs font-normal text-muted-foreground tabular-nums">
{m.movies + m.episodes} watched
</span>
</span>
</div>
<ol className="space-y-6">
{m.sessions.map((s) => {
const side = index++ % 2 === 0 ? "left" : "right";
return <TimelineItem key={s.key} session={s} side={side} />;
})}
</ol>
</section>
))}
</div>
);
}
function TimelineItem({
session,
side,
}: {
session: HistorySession;
side: "left" | "right";
}) {
const entry = session.entry;
const count = session.events.length;
const isMovie = session.kind === "movie";
const date = new Date(session.date).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
});
return (
<li
className={`relative flex pl-12 md:w-1/2 md:pl-0 ${
side === "left"
? "md:mr-auto md:justify-end md:pr-10"
: "md:ml-auto md:pl-10"
}`}
>
{/* Dot on the line */}
<span
className={`absolute top-6 left-4 h-3 w-3 -translate-x-1/2 rounded-full ring-4 ring-background ${
isMovie ? "bg-amber-500" : "bg-sky-500"
} ${side === "left" ? "md:right-0 md:left-auto md:translate-x-1/2" : "md:left-0"}`}
/>
<Link
to={sessionLink(session)}
className={`group flex w-full max-w-sm items-start gap-3 rounded-xl border border-border/60 bg-card/60 p-2.5 transition-colors hover:bg-accent/40 ${
side === "left" ? "md:flex-row-reverse md:text-right" : ""
}`}
>
{/* Poster, stacked for multi-episode sessions */}
<div className="relative shrink-0">
{count > 1 && (
<>
<img
src={posterUrl(entry)}
alt=""
className="absolute inset-0 h-full w-full translate-x-2 -translate-y-1 rotate-6 rounded-lg object-cover opacity-40"
/>
<img
src={posterUrl(entry)}
alt=""
className="absolute inset-0 h-full w-full translate-x-1 rotate-3 rounded-lg object-cover opacity-70"
/>
</>
)}
<img
src={posterUrl(entry, "w342")}
alt=""
loading="lazy"
className="relative h-28 w-[4.7rem] rounded-lg object-cover shadow-md ring-1 ring-border/60 transition-transform group-hover:scale-[1.03]"
/>
{count > 1 && (
<span className="absolute -bottom-1.5 -right-1.5 rounded-full bg-sky-500 px-1.5 py-0.5 text-[10px] font-bold text-white shadow">
×{count}
</span>
)}
</div>
<div className="min-w-0 flex-1 space-y-1 py-0.5">
<p className="text-xs font-medium text-muted-foreground">
{date}
{session.unknownDate && (
<span className="ml-1.5 rounded bg-amber-500/15 px-1 py-px text-[10px] text-amber-600 dark:text-amber-400">
date unknown
</span>
)}
</p>
<p className="line-clamp-2 font-semibold leading-tight">
{entry?.title ?? "Unknown title"}
</p>
<p
className={`flex items-center gap-1 text-xs text-muted-foreground ${
side === "left" ? "md:justify-end" : ""
}`}
>
{isMovie ? (
<Film className="h-3 w-3" />
) : (
<Tv className="h-3 w-3" />
)}
{isMovie
? "Movie"
: count > 1
? `${sessionEpisodeLabel(session)} · ${count} episodes`
: `${sessionEpisodeLabel(session)} · ${session.events[0].episode?.name ?? ""}`}
</p>
{session.minutes > 0 && (
<p className="text-[11px] text-muted-foreground/80 tabular-nums">
{formatMinutes(session.minutes)}
</p>
)}
</div>
</Link>
</li>
);
}
@@ -0,0 +1,496 @@
import type { ReactNode } from "react";
import { Link } from "react-router-dom";
import {
CalendarDays,
Clapperboard,
Flame,
Popcorn,
Repeat,
Sparkles,
Star,
Tv,
Users,
Zap,
} from "lucide-react";
import { getTmdbImageUrl } from "@/lib/api";
import {
MONTH_NAMES,
WEEKDAY_NAMES,
episodeCode,
formatMinutes,
posterUrl,
type YearReview,
} from "@/lib/history";
import type { HistoryEntry, HistoryEvent } from "@/api/history";
const formatDay = (day: string) =>
new Date(`${day}T12:00:00`).toLocaleDateString("en-US", {
weekday: "long",
month: "long",
day: "numeric",
});
export function YearInReview({
year,
review,
entries,
}: {
year: number;
review: YearReview;
entries: Record<number, HistoryEntry>;
}) {
const hours = Math.round(review.totalMinutes / 60);
const maxMonth = Math.max(1, ...review.monthly.map((m) => m.minutes));
const maxWeekday = Math.max(1, ...review.weekdays);
const topWeekday = review.weekdays.indexOf(Math.max(...review.weekdays));
const topMonth = review.monthly.findIndex((m) => m.minutes === maxMonth);
return (
<div className="space-y-6">
{/* Hero */}
<section className="relative overflow-hidden rounded-3xl bg-linear-to-br from-fuchsia-600 via-violet-600 to-indigo-700 p-8 text-white shadow-xl sm:p-10">
<div className="absolute -right-16 -top-16 h-64 w-64 rounded-full bg-white/10 blur-2xl" />
<div className="absolute -bottom-20 left-1/3 h-56 w-56 rounded-full bg-amber-300/20 blur-3xl" />
<div className="relative space-y-6">
<p className="inline-flex items-center gap-2 text-sm font-medium uppercase tracking-[0.2em] text-white/80">
<Sparkles className="h-4 w-4" /> Your {year} in review
</p>
<div>
<p className="text-6xl font-black tracking-tight tabular-nums sm:text-8xl">
{hours.toLocaleString()}
</p>
<p className="text-lg font-medium text-white/85">
hours of movies and TV
{hours >= 24 && (
<span className="text-white/70">
{" "}
— that's {Math.round(hours / 24)} full days
</span>
)}
</p>
</div>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<HeroStat label="Movies" value={review.uniqueMovies} />
<HeroStat label="Episodes" value={review.episodeWatches} />
<HeroStat label="Shows" value={review.uniqueShows} />
<HeroStat label="Days watching" value={review.activeDays} />
</div>
</div>
</section>
{/* Highlights */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{review.longestStreak && review.longestStreak.days > 1 && (
<HighlightCard
icon={<Flame />}
tone="from-orange-500/20 to-red-500/10"
label="Longest streak"
value={`${review.longestStreak.days} days`}
detail={`${shortDay(review.longestStreak.start)} – ${shortDay(review.longestStreak.end)}`}
/>
)}
{review.busiestDay && (
<HighlightCard
icon={<CalendarDays />}
tone="from-sky-500/20 to-cyan-500/10"
label="Busiest day"
value={formatMinutes(review.busiestDay.minutes)}
detail={`${formatDay(review.busiestDay.day)} · ${review.busiestDay.watches} watched`}
/>
)}
{review.biggestBinge && (
<HighlightCard
icon={<Zap />}
tone="from-violet-500/20 to-fuchsia-500/10"
label="Biggest binge"
value={`${review.biggestBinge.episodes} episodes`}
detail={`${review.biggestBinge.entry.title} · ${shortDay(review.biggestBinge.day)}`}
poster={posterUrl(review.biggestBinge.entry)}
/>
)}
<HighlightCard
icon={<Star />}
tone="from-amber-500/20 to-yellow-500/10"
label="Favorite day"
value={WEEKDAY_NAMES[topWeekday]}
detail={`and ${MONTH_NAMES[topMonth]} was your biggest month`}
/>
</div>
<div className="grid gap-6 lg:grid-cols-2">
{/* Top shows */}
{review.topShows.length > 0 && (
<Card title="Top shows" icon={<Tv />}>
<ol className="space-y-2.5">
{review.topShows.map((s, i) => (
<li key={s.entry.id}>
<Link
to={`/entry/${s.entry.id}`}
className="flex items-center gap-3 rounded-lg p-1 transition-colors hover:bg-accent/50"
>
<span className="w-7 text-center text-2xl font-black text-muted-foreground/60 tabular-nums">
{i + 1}
</span>
<img
src={posterUrl(s.entry)}
alt=""
className="h-14 w-10 rounded object-cover ring-1 ring-border/60"
/>
<div className="min-w-0 flex-1">
<p className="line-clamp-1 font-semibold">
{s.entry.title}
</p>
<p className="text-xs text-muted-foreground">
{s.episodes} episodes · {formatMinutes(s.minutes)}
</p>
</div>
</Link>
</li>
))}
</ol>
</Card>
)}
{/* Genres */}
{review.topGenres.length > 0 && (
<Card title="Top genres" icon={<Clapperboard />}>
<div className="space-y-3">
{review.topGenres.map((g, i) => (
<div key={g.name} className="space-y-1">
<div className="flex justify-between text-sm">
<span className="font-medium">{g.name}</span>
<span className="text-muted-foreground tabular-nums">
{Math.round(g.share * 100)}%
</span>
</div>
<div className="h-2 overflow-hidden rounded-full bg-muted">
<div
className="h-full rounded-full bg-linear-to-r from-violet-500 to-fuchsia-500"
style={{
width: `${(g.minutes / review.topGenres[0].minutes) * 100}%`,
opacity: 1 - i * 0.1,
}}
/>
</div>
</div>
))}
</div>
</Card>
)}
</div>
{/* Monthly activity */}
<Card title="Month by month" icon={<CalendarDays />}>
<div className="flex h-44 items-end gap-1.5 sm:gap-3">
{review.monthly.map((m, i) => (
<div key={i} className="flex flex-1 flex-col items-center gap-1.5">
<div className="flex h-36 w-full items-end">
<div
title={`${MONTH_NAMES[i]}: ${formatMinutes(m.minutes)} · ${m.movies} movies · ${m.episodes} episodes`}
className={`w-full rounded-t-md transition-all ${
i === topMonth
? "bg-linear-to-t from-fuchsia-600 to-violet-400"
: "bg-linear-to-t from-violet-500/50 to-violet-400/30"
}`}
style={{
height: `${Math.max(2, (m.minutes / maxMonth) * 100)}%`,
}}
/>
</div>
<span className="text-[10px] font-medium text-muted-foreground">
{MONTH_NAMES[i].slice(0, 3)}
</span>
</div>
))}
</div>
</Card>
<div className="grid gap-6 lg:grid-cols-3">
{/* Top rated movies */}
{review.topMovies.length > 0 && (
<Card
title="Your top-rated movies"
icon={<Popcorn />}
className="lg:col-span-2"
>
<div className="grid grid-cols-3 gap-3 sm:grid-cols-5">
{review.topMovies.map((m) => (
<Link
key={m.entry.id}
to={`/entry/${m.entry.id}`}
className="group space-y-1.5"
>
<img
src={posterUrl(m.entry, "w342")}
alt={m.entry.title}
className="aspect-2/3 w-full rounded-lg object-cover ring-1 ring-border/60 transition-transform group-hover:scale-[1.03]"
/>
<p className="line-clamp-1 text-xs font-medium">
{m.entry.title}
</p>
<p className="inline-flex items-center gap-0.5 text-xs text-muted-foreground tabular-nums">
<Star className="h-3 w-3 fill-yellow-400 text-yellow-400" />
{m.rating}/10
</p>
</Link>
))}
</div>
</Card>
)}
{/* Weekdays */}
<Card title="When you watch" icon={<CalendarDays />}>
<div className="space-y-2">
{review.weekdays.map((n, d) => (
<div key={d} className="flex items-center gap-2 text-xs">
<span className="w-8 text-muted-foreground">
{WEEKDAY_NAMES[d]}
</span>
<div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">
<div
className={`h-full rounded-full ${d === topWeekday ? "bg-amber-500" : "bg-amber-500/40"}`}
style={{ width: `${(n / maxWeekday) * 100}%` }}
/>
</div>
<span className="w-8 text-right tabular-nums text-muted-foreground">
{n}
</span>
</div>
))}
</div>
</Card>
</div>
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{review.rewatches.length > 0 && (
<Card title="On repeat" icon={<Repeat />}>
<ul className="space-y-2">
{review.rewatches.map((r) => (
<li
key={r.entry.id}
className="flex items-center justify-between gap-2 text-sm"
>
<Link
to={`/entry/${r.entry.id}`}
className="line-clamp-1 hover:underline"
>
{r.entry.title}
</Link>
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-xs tabular-nums">
×{r.watches}
</span>
</li>
))}
</ul>
</Card>
)}
{review.topNetworks.length > 0 && (
<Card title="Top networks" icon={<Tv />}>
<ul className="space-y-2.5">
{review.topNetworks.map((n) => (
<li
key={n.name}
className="flex items-center justify-between gap-2 text-sm"
>
{n.logo_path ? (
<img
src={getTmdbImageUrl(n.logo_path, "w92")}
alt={n.name}
title={n.name}
className="h-5 max-w-24 object-contain dark:invert dark:brightness-200"
/>
) : (
<span>{n.name}</span>
)}
<span className="text-xs text-muted-foreground tabular-nums">
{n.episodes} eps
</span>
</li>
))}
</ul>
</Card>
)}
{review.topBuddies.length > 0 && (
<Card title="Watched together" icon={<Users />}>
<ul className="space-y-2">
{review.topBuddies.map((b) => (
<li
key={b.id}
className="flex items-center justify-between gap-2 text-sm"
>
<Link
to={`/watch-buddies/${b.id}`}
className="hover:underline"
>
{b.name}
</Link>
<span className="text-xs text-muted-foreground tabular-nums">
{b.watches} watches
</span>
</li>
))}
</ul>
</Card>
)}
</div>
{/* Started shows */}
{review.startedShows.length > 0 && (
<Card
title={`New shows you started (${review.startedShows.length})`}
icon={<Sparkles />}
>
<div className="flex gap-3 overflow-x-auto pb-2">
{review.startedShows.map((e) => (
<Link
key={e.id}
to={`/entry/${e.id}`}
className="w-24 shrink-0 space-y-1"
>
<img
src={posterUrl(e, "w342")}
alt={e.title}
className="aspect-2/3 w-full rounded-lg object-cover ring-1 ring-border/60"
/>
<p className="line-clamp-1 text-xs">{e.title}</p>
</Link>
))}
</div>
</Card>
)}
{/* Bookends */}
{review.first && review.last && (
<div className="grid gap-4 sm:grid-cols-2">
<BookendCard
label={`First watch of ${year}`}
event={review.first}
entries={entries}
/>
<BookendCard
label={`Last watch of ${year}`}
event={review.last}
entries={entries}
/>
</div>
)}
</div>
);
}
const shortDay = (day: string) =>
new Date(`${day}T12:00:00`).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
});
function HeroStat({ label, value }: { label: string; value: number }) {
return (
<div className="rounded-2xl bg-white/10 px-4 py-3 backdrop-blur">
<p className="text-3xl font-bold tabular-nums">
{value.toLocaleString()}
</p>
<p className="text-xs font-medium uppercase tracking-wider text-white/75">
{label}
</p>
</div>
);
}
function HighlightCard({
icon,
tone,
label,
value,
detail,
poster,
}: {
icon: ReactNode;
tone: string;
label: string;
value: string;
detail: string;
poster?: string;
}) {
return (
<div
className={`relative overflow-hidden rounded-2xl border border-border/60 bg-linear-to-br ${tone} p-5`}
>
{poster && (
<img
src={poster}
alt=""
className="absolute -right-4 -bottom-6 h-32 w-24 rotate-12 rounded-lg object-cover opacity-30"
/>
)}
<div className="relative space-y-1">
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground [&_svg]:h-3.5 [&_svg]:w-3.5">
{icon}
{label}
</p>
<p className="text-3xl font-black tracking-tight">{value}</p>
<p className="line-clamp-2 text-xs text-muted-foreground">{detail}</p>
</div>
</div>
);
}
function Card({
title,
icon,
children,
className = "",
}: {
title: string;
icon: ReactNode;
children: ReactNode;
className?: string;
}) {
return (
<section
className={`rounded-2xl border border-border/60 bg-card/60 p-5 ${className}`}
>
<h3 className="mb-4 flex items-center gap-2 text-sm font-semibold [&_svg]:h-4 [&_svg]:w-4 [&_svg]:text-muted-foreground">
{icon}
{title}
</h3>
{children}
</section>
);
}
function BookendCard({
label,
event,
entries,
}: {
label: string;
event: HistoryEvent;
entries: Record<number, HistoryEntry>;
}) {
const entry = entries[event.entry_id];
return (
<div className="flex items-center gap-4 rounded-2xl border border-border/60 bg-card/60 p-4">
<img
src={posterUrl(entry, "w342")}
alt=""
className="h-24 w-16 rounded-lg object-cover ring-1 ring-border/60"
/>
<div className="min-w-0 space-y-0.5">
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
{label}
</p>
<p className="line-clamp-1 text-lg font-bold">{entry?.title}</p>
<p className="text-xs text-muted-foreground">
{event.kind === "episode" && `${episodeCode(event.episode)} · `}
{new Date(event.date_seen).toLocaleDateString("en-US", {
month: "long",
day: "numeric",
})}
</p>
</div>
</div>
);
}
@@ -13,6 +13,8 @@ import {
Moon, Moon,
Sun, Sun,
Film, Film,
Video,
History,
} from "lucide-react"; } from "lucide-react";
import { useThemeStore } from "@/stores/useThemeStore"; import { useThemeStore } from "@/stores/useThemeStore";
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator";
@@ -25,8 +27,10 @@ const mainNav = [
const libraryNav = [ const libraryNav = [
{ to: "/library", icon: Library, label: "Library" }, { to: "/library", icon: Library, label: "Library" },
{ to: "/watchlist", icon: ListVideo, label: "Watchlist" }, { to: "/watchlist", icon: ListVideo, label: "Watchlist" },
{ to: "/history", icon: History, label: "History" },
{ to: "/collections", icon: FolderOpen, label: "Collections" }, { to: "/collections", icon: FolderOpen, label: "Collections" },
{ to: "/media", icon: Image, label: "Media" }, { to: "/media", icon: Image, label: "Media" },
{ to: "/discovery-videos", icon: Video, label: "Discover" },
]; ];
const otherNav = [ const otherNav = [
@@ -154,28 +154,39 @@ export function CollectionDetailsSkeleton() {
export function EntryDetailsSkeleton() { export function EntryDetailsSkeleton() {
return ( return (
<div className="animate-in fade-in duration-300"> <div className="animate-in fade-in duration-300">
<div className="h-52 -mx-6 -mt-6 bg-muted animate-pulse rounded-b-lg" /> <div className="relative -mx-4 -mt-4 bg-muted/40 md:-mx-6 md:-mt-6">
<div className="max-w-4xl mx-auto flex gap-8 -mt-24"> <div className="mx-auto flex max-w-6xl flex-col items-center gap-6 px-4 pb-8 pt-28 sm:flex-row sm:items-end sm:gap-8 sm:pt-44 md:px-6">
<div className="w-44 shrink-0 space-y-3"> <Skeleton className="aspect-[2/3] w-40 shrink-0 rounded-xl sm:w-52 lg:w-60" />
<Skeleton className="aspect-[2/3] w-full rounded-xl" /> <div className="w-full flex-1 space-y-4">
<Skeleton className="h-9 w-full rounded-lg" /> <Skeleton className="h-5 w-24 rounded-full" />
<Skeleton className="h-9 w-full rounded-lg" /> <Skeleton className="h-12 w-3/4 max-w-md" />
<Skeleton className="h-9 w-full rounded-lg" /> <Skeleton className="h-4 w-48" />
<div className="flex gap-1.5">
<Skeleton className="h-6 w-16 rounded-full" />
<Skeleton className="h-6 w-20 rounded-full" />
<Skeleton className="h-6 w-14 rounded-full" />
</div>
<div className="flex gap-2">
<Skeleton className="h-11 w-36 rounded-md" />
<Skeleton className="h-11 w-28 rounded-md" />
<Skeleton className="h-11 w-11 rounded-full" />
<Skeleton className="h-11 w-11 rounded-full" />
</div>
</div>
</div> </div>
<div className="flex-1 space-y-4 pt-24"> </div>
<Skeleton className="h-9 w-72" /> <div className="mx-auto mt-4 grid max-w-6xl gap-10 lg:grid-cols-[minmax(0,1fr)_300px]">
<Skeleton className="h-4 w-32" /> <div className="space-y-3">
<div className="flex gap-2"> <Skeleton className="h-6 w-28" />
<Skeleton className="h-5 w-12" /> <Skeleton className="h-24 w-full" />
<Skeleton className="h-5 w-16" /> </div>
<Skeleton className="h-5 w-20" /> <div className="space-y-4">
<div className="grid grid-cols-3 gap-2">
<Skeleton className="h-20 rounded-xl" />
<Skeleton className="h-20 rounded-xl" />
<Skeleton className="h-20 rounded-xl" />
</div> </div>
<div className="flex gap-2"> <Skeleton className="h-40 rounded-xl" />
<Skeleton className="h-8 w-24 rounded-full" />
<Skeleton className="h-8 w-24 rounded-full" />
<Skeleton className="h-8 w-20 rounded-full" />
</div>
<Skeleton className="h-20 w-full" />
</div> </div>
</div> </div>
</div> </div>
@@ -314,3 +325,26 @@ export function SettingsSkeleton() {
</div> </div>
); );
} }
export function DiscoveryVideosSkeleton() {
return (
<div className="space-y-6 animate-in fade-in duration-300">
<div className="flex items-center justify-between">
<div className="space-y-2">
<Skeleton className="h-8 w-40" />
<Skeleton className="h-4 w-64" />
</div>
<Skeleton className="h-8 w-28 rounded-lg" />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="space-y-2">
<Skeleton className="aspect-video w-full rounded-lg" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-3 w-full" />
</div>
))}
</div>
</div>
);
}
+1 -1
View File
@@ -83,7 +83,7 @@ function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return ( return (
<div <div
data-slot="dialog-header" data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)} className={cn("flex min-w-0 flex-col gap-2", className)}
{...props} {...props}
/> />
); );
@@ -0,0 +1,73 @@
import { useInfiniteQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import {
discoveryVideosApi,
type UpdateVideoData,
} from "@/api/discoveryVideos";
export const discoveryVideoKeys = {
all: ["discovery-videos"] as const,
};
export function useDiscoveryVideos() {
return useInfiniteQuery({
queryKey: discoveryVideoKeys.all,
queryFn: ({ pageParam }) =>
discoveryVideosApi.getAll((pageParam as number) ?? 1, 24),
initialPageParam: 1,
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.totalPages ? lastPage.page + 1 : undefined,
});
}
export function useUploadVideos() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
formData,
onProgress,
}: {
formData: FormData;
onProgress?: (percent: number) => void;
}) => discoveryVideosApi.create(formData, onProgress),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: discoveryVideoKeys.all });
toast.success("Video uploaded successfully");
},
onError: () => {
toast.error("Failed to upload video");
},
});
}
export function useUpdateVideo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, data }: { id: number; data: UpdateVideoData }) =>
discoveryVideosApi.update(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: discoveryVideoKeys.all });
toast.success("Video updated");
},
onError: () => {
toast.error("Failed to update video");
},
});
}
export function useDeleteVideo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) => discoveryVideosApi.remove(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: discoveryVideoKeys.all });
toast.success("Video deleted");
},
onError: () => {
toast.error("Failed to delete video");
},
});
}
+62 -1
View File
@@ -2,13 +2,19 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner"; import { toast } from "sonner";
import { entriesApi } from "@/api/entries"; import { entriesApi } from "@/api/entries";
import { useLibraryStore } from "@/stores/useLibraryStore"; import { useLibraryStore } from "@/stores/useLibraryStore";
import type { Entry } from "@/types"; import type { ArtworkType, Entry } from "@/types";
export const entryKeys = { export const entryKeys = {
all: ["entries"] as const, all: ["entries"] as const,
detail: (id: number) => ["entries", id] as const, detail: (id: number) => ["entries", id] as const,
seasons: (id: number) => ["entries", id, "seasons"] as const, seasons: (id: number) => ["entries", id, "seasons"] as const,
credits: (id: number) => ["entries", id, "credits"] as const, credits: (id: number) => ["entries", id, "credits"] as const,
recommendations: (id: number) => ["entries", id, "recommendations"] as const,
artwork: (id: number) => ["entries", id, "artwork"] as const,
tmdbArtwork: (tmdbId: number, type: string) =>
["entries", "tmdb-artwork", type, tmdbId] as const,
tmdbRecommendations: (tmdbId: number, type: string) =>
["entries", "tmdb-recommendations", type, tmdbId] as const,
tmdbPreview: (tmdbId: number, type: string) => tmdbPreview: (tmdbId: number, type: string) =>
["entries", "tmdb-preview", type, tmdbId] as const, ["entries", "tmdb-preview", type, tmdbId] as const,
}; };
@@ -43,6 +49,61 @@ export function useEntrySeasons(id: number) {
}); });
} }
export function useEntryRecommendations(id: number) {
return useQuery({
queryKey: entryKeys.recommendations(id),
queryFn: () => entriesApi.getRecommendations(id),
enabled: !!id,
staleTime: 30 * 60 * 1000,
});
}
export function useTmdbRecommendations(
tmdbId: number,
type: "movie" | "tv",
) {
return useQuery({
queryKey: entryKeys.tmdbRecommendations(tmdbId, type),
queryFn: () => entriesApi.getTmdbRecommendations(type, tmdbId),
enabled: !!tmdbId,
staleTime: 30 * 60 * 1000,
});
}
/** Artwork for a library entry (TMDB + media table), or by TMDB id otherwise. */
export function useArtwork(
source: { entryId: number } | { tmdbId: number; type: "movie" | "tv" },
) {
const isLibrary = "entryId" in source;
return useQuery({
queryKey: isLibrary
? entryKeys.artwork(source.entryId)
: entryKeys.tmdbArtwork(source.tmdbId, source.type),
queryFn: () =>
isLibrary
? entriesApi.getArtwork(source.entryId)
: entriesApi.getTmdbArtwork(source.type, source.tmdbId),
enabled: isLibrary ? !!source.entryId : !!source.tmdbId,
staleTime: 10 * 60 * 1000,
});
}
export function useAddArtwork(entryId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: { type: ArtworkType; file_path: string }) =>
entriesApi.addArtwork(entryId, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: entryKeys.artwork(entryId) });
queryClient.invalidateQueries({ queryKey: entryKeys.detail(entryId) });
queryClient.invalidateQueries({ queryKey: entryKeys.all, exact: true });
},
onError: () => {
toast.error("Failed to add artwork");
},
});
}
export function useEntryCredits(id: number) { export function useEntryCredits(id: number) {
return useQuery({ return useQuery({
queryKey: entryKeys.credits(id), queryKey: entryKeys.credits(id),
+24
View File
@@ -0,0 +1,24 @@
import { useQuery } from "@tanstack/react-query";
import { historyApi } from "@/api/history";
export const historyKeys = {
years: ["history", "years"] as const,
year: (year: number) => ["history", year] as const,
};
export function useHistoryYears() {
return useQuery({
queryKey: historyKeys.years,
queryFn: historyApi.getYears,
staleTime: 5 * 60 * 1000,
});
}
export function useHistoryYear(year: number) {
return useQuery({
queryKey: historyKeys.year(year),
queryFn: () => historyApi.getYear(year),
enabled: !!year,
staleTime: 5 * 60 * 1000,
});
}
+41 -1
View File
@@ -1,5 +1,6 @@
import { useQuery } from "@tanstack/react-query"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { seasonsApi } from "@/api/seasons"; import { seasonsApi } from "@/api/seasons";
import { toast } from "sonner";
export const seasonKeys = { export const seasonKeys = {
all: ["seasons"] as const, all: ["seasons"] as const,
@@ -22,3 +23,42 @@ export function useSeasonEpisodes(id: number) {
enabled: !!id, enabled: !!id,
}); });
} }
export function useRefreshSeason() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) => seasonsApi.refresh(id),
onSuccess: (season) => {
queryClient.invalidateQueries({ queryKey: seasonKeys.detail(season.id) });
queryClient.invalidateQueries({
queryKey: seasonKeys.episodes(season.id),
});
toast.success("Season refreshed");
},
onError: () => {
toast.error("Failed to refresh season");
},
});
}
export function useUpdateSeason() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
id,
data,
}: {
id: number;
data: Partial<Parameters<typeof seasonsApi.update>[1]>;
}) => seasonsApi.update(id, data),
onSuccess: (season) => {
queryClient.invalidateQueries({ queryKey: seasonKeys.detail(season.id) });
toast.success("Season updated");
},
onError: () => {
toast.error("Failed to update season");
},
});
}
+1 -1
View File
@@ -14,7 +14,7 @@ interface TmdbEntryLink {
/** /**
* Resolves the correct navigation link for a TmdbEntry. * Resolves the correct navigation link for a TmdbEntry.
* If the entry is already in the library, links directly to EntryDetailsPage. * If the entry is already in the library, links directly to EntryDetailsPage.
* Otherwise, links to the TmdbPreviewPage. * Otherwise, links to the TMDB preview of the entry details page.
*/ */
export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink { export function useTmdbEntryLink(entry: TmdbEntry): TmdbEntryLink {
const libraryEntries = useLibraryStore((s) => s.entries); const libraryEntries = useLibraryStore((s) => s.entries);
+14
View File
@@ -28,5 +28,19 @@ export const getMediaUrl = (
file: string, file: string,
) => `${API_BASE_URL}/media/${category}/${type}/${size}/${file}`; ) => `${API_BASE_URL}/media/${category}/${type}/${size}/${file}`;
export const getVideoStreamUrl = (id: number) => {
const token = useAuthStore.getState().token;
return `${API_BASE_URL}/discovery-videos/${id}/stream${
token ? `?token=${encodeURIComponent(token)}` : ''
}`;
};
export const getVideoThumbnailUrl = (id: number) => {
const token = useAuthStore.getState().token;
return `${API_BASE_URL}/discovery-videos/${id}/thumbnail${
token ? `?token=${encodeURIComponent(token)}` : ''
}`;
};
export const getTmdbImageUrl = (path: string, size = 'w342') => export const getTmdbImageUrl = (path: string, size = 'w342') =>
`https://image.tmdb.org/t/p/${size}${path}`; `https://image.tmdb.org/t/p/${size}${path}`;
@@ -0,0 +1,65 @@
import { getMediaUrl, getTmdbImageUrl } from "@/lib/api";
import { getBackdropUrl, getPosterUrl } from "@/lib/media-utils";
import type { Collection, Media } from "@/types";
export const DEFAULT_POSTER = "/images/default-poster.png";
/**
* Collection poster: uploaded poster, then the collection's own TMDB poster,
* then the poster of its first entry, then the default placeholder.
*/
export function getCollectionDisplayPosterUrl(collection: Collection): string {
const selectedPoster = collection.medias?.find(
(m: Media) => m.type === "poster" && m.is_selected,
);
if (selectedPoster?.path) {
return getMediaUrl(
"collections",
"posters",
"preview",
selectedPoster.path,
);
}
if (collection.poster_path) {
return getTmdbImageUrl(collection.poster_path, "w342");
}
const firstEntry = collection.entries?.[0];
if (firstEntry) {
return getPosterUrl({ ...firstEntry, isInLibrary: true });
}
return DEFAULT_POSTER;
}
/**
* Collection backdrop: uploaded backdrop, then the collection's own TMDB
* backdrop, then the first entry that has one. Null when nothing is available.
*/
export function getCollectionDisplayBackdropUrl(
collection: Collection,
): string | null {
const selectedBackdrop = collection.medias?.find(
(m: Media) => m.type === "backdrop" && m.is_selected,
);
if (selectedBackdrop?.path) {
return getMediaUrl(
"collections",
"backdrops",
"full",
selectedBackdrop.path,
);
}
if (collection.backdrop_path) {
return getTmdbImageUrl(collection.backdrop_path, "w1280");
}
for (const entry of collection.entries ?? []) {
const url = getBackdropUrl(entry);
if (url) return url;
}
return null;
}
+11
View File
@@ -0,0 +1,11 @@
export function formatBytes(bytes: number): string {
if (!bytes || bytes <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit += 1;
}
return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
}
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff. Show more