From ac0030d61196cb03c098d3e24d0ff0fc75045f0b Mon Sep 17 00:00:00 2001 From: X4Lo Date: Fri, 20 Nov 2026 04:02:43 +0000 Subject: [PATCH] Refresh airing TV series when the calendar is opened - POST /entries/sync-series starts a background refresh of airing TV series (not Ended/Canceled, auto sync on) not refreshed in the last 24h; manual refreshes reset that clock. GET kept as an alias, plus GET /entries/sync-series/status for progress - Reuses the rate-limited stale refresh job with a series-only scope; only one refresh job runs at a time - Calendar starts the sync on visit, shows progress, and reloads episodes and the library when it finishes - Remove the old SyncSeriesData, whose date check no longer worked --- backend/controllers/entryController.js | 20 ++- backend/routes/entry.routes.js | 3 + backend/services/entryManager.js | 204 ---------------------- backend/services/maintenanceService.js | 14 +- react_frontend/src/api/entries.ts | 10 +- react_frontend/src/api/maintenance.ts | 2 + react_frontend/src/hooks/useSeriesSync.ts | 48 +++++ react_frontend/src/pages/CalendarPage.tsx | 32 +++- 8 files changed, 119 insertions(+), 214 deletions(-) create mode 100644 react_frontend/src/hooks/useSeriesSync.ts diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js index 1eb9cda..f8d1822 100644 --- a/backend/controllers/entryController.js +++ b/backend/controllers/entryController.js @@ -10,6 +10,10 @@ const { mapEntryRatings, } = require("../mappers/entryMapper"); const asyncWrapper = require("../utils/asyncWrapper"); +const maintenanceService = require("../services/maintenanceService"); + +// TV series are refreshed at most once per this many hours by the calendar sync +const SERIES_SYNC_HOURS = 24; const _collectionManager = collectionManager; const _entryManager = entryManager; @@ -97,11 +101,19 @@ class EntryController { res.status(200).json({ message: `Entry with ID ${id} deleted.` }); }); - // * GET - SYNC ALL ENTIRES DATA - syncSeries = asyncWrapper(async (req, res, next) => { - const entries = await _entryManager.SyncSeriesData(); + // * POST - SYNC TV SERIES (calendar) + // Starts a background refresh of airing TV series not refreshed in the last + // 24h (manual refreshes reset that clock). Returns the job status at once. + syncSeries = asyncWrapper(async (req, res) => { + const job = await maintenanceService.startStaleRefresh(SERIES_SYNC_HOURS, { + seriesOnly: true, + }); + res.status(job.alreadyRunning ? 200 : 202).json(job); + }); - res.status(201).json(entries); + // * GET - SYNC TV SERIES STATUS + syncSeriesStatus = asyncWrapper(async (req, res) => { + res.status(200).json(maintenanceService.getStaleRefreshStatus()); }); // * GET - Get seasons of an entry diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index dd17494..18354c3 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -24,7 +24,10 @@ entryRouter.get( ); entryRouter.get("/tmdb/artwork/:type/:tmdbId", entryController.getTmdbArtwork); +// Calendar sync: refresh airing TV series older than 24h (GET kept as an alias) +entryRouter.post("/sync-series", entryController.syncSeries); entryRouter.get("/sync-series", entryController.syncSeries); +entryRouter.get("/sync-series/status", entryController.syncSeriesStatus); entryRouter.get("/", entryController.getAllEntries); entryRouter.get("/:id", entryController.getEntryById); diff --git a/backend/services/entryManager.js b/backend/services/entryManager.js index b2d4e17..42aeb1a 100644 --- a/backend/services/entryManager.js +++ b/backend/services/entryManager.js @@ -565,210 +565,6 @@ class EntryManager { return entry; } - /** This function will refresh data of series that have the status not 'ended/canceled' and have not been refreshed today - */ - async SyncSeriesData() { - const today = moment().format("YYYY-MM-DD"); - const entries = await Entry.findAll({ - where: { - is_tvseries: true, - autoSync: true, - last_fetch: { - [Op.ne]: today, - }, - status: { - [Op.notIn]: ["Ended", "Canceled"], - }, - }, - }); - - logToFile(`Started syncing ${entries.length} Tv-Series`); - - const results = await Promise.all( - entries.map((entry) => this.SyncSerieData(entry.id)), - ); - logToFile(`Syncing Tv-Series Finished`); - - return results; - } - - async SyncSerieData(entryId) { - const oldEntry = await Entry.findByPk(entryId, { - include: [ - { model: EntryId, as: "entryId" }, - { model: EntryRating, as: "entryRating" }, - { model: EntrySeen, as: "entrySeen" }, - { model: Season, as: "seasons" }, - { model: Media, as: "medias" }, - { - model: Genre, - as: "genres", - attributes: ["id"], - through: { - attributes: [], - }, - }, - ], - }); - - logToFile( - `Sync Started For: ${oldEntry.entryId.tmdb_id}/${oldEntry.title}`, - ); - - if (!oldEntry) throw NotFoundError("Entry Not Found"); - - const entryData = await fetchEntryData( - oldEntry.entryId.tmdb_id, - oldEntry.is_tvseries, - ); - - if (!entryData) throw new ValidationError(`Couldn't Fetch Entry Data`); - - // ! 1 - Normal Data - let newData = { - title: entryData.title || entryData.name, - original_title: entryData.original_title || entryData.original_name, - release_date: entryData.release_date || entryData.first_air_date, - 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(), - }; - - await oldEntry.update(newData); - - // ! 2 - Ids - // TODO: get more ids - await oldEntry.entryId.update({ - imdb_id: entryData.imdb_id, - }); - - // ! 3 - Ratings - await oldEntry.entryRating.update({ - tmdb_rating: entryData.vote_average, - }); - - // ! 4 - Genres - const currentGenresIds = oldEntry.genres.map((genre) => genre.id); - entryData.genres.forEach(async (genre) => { - // ? only assing the genre if its not already asigned - if (!currentGenresIds.includes(genre.id)) { - await EntryGenre.create({ - genre_id: genre.id, - entry_id: oldEntry.id, - }); - } - }); - - // ! 5 - Seasons - // ? only update the last seasons available + season 0 (specials) - if (oldEntry.is_tvseries) { - const latestAvailableSeason = await Math.max( - ...oldEntry.seasons.map((s) => s.season_number), - ); - for (const season of entryData.seasons) { - if ( - season.season_number != 0 && - season.season_number != latestAvailableSeason - ) - continue; - - // ? fetch new season data from tmdb - let seasonData = await fetchSeasonData( - oldEntry.entryId.tmdb_id, - season.season_number, - ); - - // * find or create the season - const [oldSeason, createdSeason] = await Season.findOrCreate({ - where: { tmdb_id: season.id }, - defaults: { - tmdb_id: seasonData.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, - tmdb_rating: seasonData.vote_average, - poster_path: seasonData.poster_path, - banner_path: null, - }, - }); - - // ? if the season already exist then just update it with new data - if (!createdSeason) { - await oldSeason.update({ - tmdb_id: seasonData.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, - tmdb_rating: seasonData.vote_average, - poster_path: seasonData.poster_path, - banner_path: null, - }); - } - - // * forging updated/created season into a variable - let existingSeason = oldSeason || createdSeason; - - // ! 6 - Episodes - for (const episode of seasonData.episodes) { - // * find or create the episode - const [oldEpisode, createdEpisode] = await Episode.findOrCreate({ - where: { tmdb_id: episode.id }, - defaults: { - 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, - }, - }); - - // ? if the episode already exist then just update it with new data - if (!createdEpisode) { - await oldEpisode.update({ - tmdb_id: episode.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, - }); - } - } - } - } - - await oldEntry.reload(); - - return oldEntry; - } } module.exports = new EntryManager(); diff --git a/backend/services/maintenanceService.js b/backend/services/maintenanceService.js index 5cd68d5..7d017f8 100644 --- a/backend/services/maintenanceService.js +++ b/backend/services/maintenanceService.js @@ -575,14 +575,20 @@ class MaintenanceService { * 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] + * @param {{ seriesOnly?: boolean }} [options] - seriesOnly: only TV series + * that are still airing (not Ended/Canceled), for the calendar sync */ - async getStaleEntries(hours = 24) { + async getStaleEntries(hours = 24, { seriesOnly = false } = {}) { 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 } }], + ...(seriesOnly && { + is_tvseries: true, + status: { [Op.or]: [null, { [Op.notIn]: ["Ended", "Canceled"] }] }, + }), }, order: [["last_fetch", "ASC"]], }); @@ -600,18 +606,20 @@ class MaintenanceService { * TMDB requests go through tmdbService's rate limiter, so a large library * is spread out instead of hammering the API. * @param {number} [hours=24] + * @param {{ seriesOnly?: boolean }} [options] - see getStaleEntries * @returns {Object} the job status, or `{ alreadyRunning: true, ... }` */ - async startStaleRefresh(hours = 24) { + async startStaleRefresh(hours = 24, options = {}) { if (this.staleRefreshJob?.running) { return { alreadyRunning: true, ...this.getStaleRefreshStatus() }; } - const entries = await this.getStaleEntries(hours); + const entries = await this.getStaleEntries(hours, options); const job = { running: true, cancelRequested: false, hours, + scope: options.seriesOnly ? "series" : "all", total: entries.length, done: 0, succeeded: 0, diff --git a/react_frontend/src/api/entries.ts b/react_frontend/src/api/entries.ts index 4e76617..349dd8a 100644 --- a/react_frontend/src/api/entries.ts +++ b/react_frontend/src/api/entries.ts @@ -1,5 +1,6 @@ import { api } from "@/lib/api"; import { normalizeEntry, normalizeCredit } from "@/lib/normalizers"; +import type { StaleRefreshJob } from "@/api/maintenance"; import type { Entry, Credit, @@ -90,7 +91,14 @@ export const entriesApi = { addArtwork: (id: number, data: { type: ArtworkType; file_path: string }) => api.post(`/entries/${id}/artwork`, data).then((r) => r.data), - syncSeries: () => api.get("/entries/sync-series").then((r) => r.data), + /** Starts the background refresh of airing TV series older than 24h. */ + syncSeries: () => + api.post("/entries/sync-series").then((r) => r.data), + + syncSeriesStatus: () => + api + .get("/entries/sync-series/status") + .then((r) => r.data), previewTmdb: (tmdbId: number, type: "movie" | "tv") => api diff --git a/react_frontend/src/api/maintenance.ts b/react_frontend/src/api/maintenance.ts index 4a724aa..99382e7 100644 --- a/react_frontend/src/api/maintenance.ts +++ b/react_frontend/src/api/maintenance.ts @@ -13,6 +13,8 @@ export interface OrphanPeopleResult { export interface StaleRefreshJob { running: boolean; + /** "series" = calendar sync of airing TV series, "all" = maintenance refresh */ + scope?: "series" | "all"; hours?: number; total?: number; done?: number; diff --git a/react_frontend/src/hooks/useSeriesSync.ts b/react_frontend/src/hooks/useSeriesSync.ts new file mode 100644 index 0000000..95c648e --- /dev/null +++ b/react_frontend/src/hooks/useSeriesSync.ts @@ -0,0 +1,48 @@ +import { useEffect, useRef } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { entriesApi } from "@/api/entries"; +import { entryKeys } from "@/hooks/useEntries"; + +/** + * Refreshes airing TV series when the calendar is opened. The backend only + * picks series not refreshed in the last 24h (a manual refresh resets that), + * so most visits start nothing. While a sync runs its status is polled, and + * calendar episodes + the library are reloaded when it finishes. + */ +export function useSeriesSync() { + const queryClient = useQueryClient(); + const start = useMutation({ mutationFn: entriesApi.syncSeries }); + const startedRef = useRef(false); + + // Kick off once per visit (StrictMode's second call just sees it running) + useEffect(() => { + if (startedRef.current) return; + startedRef.current = true; + start.mutate(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const startedJob = start.data; + const status = useQuery({ + queryKey: ["entries", "sync-series", "status"], + queryFn: entriesApi.syncSeriesStatus, + enabled: !!startedJob?.running, + refetchInterval: (query) => + query.state.data?.running === false ? false : 2500, + }); + + const job = status.data ?? startedJob; + const running = !!job?.running; + + // Reload calendar data once the sync that was running finishes + const wasRunning = useRef(false); + useEffect(() => { + if (wasRunning.current && !running) { + queryClient.invalidateQueries({ queryKey: ["episodes"] }); + queryClient.invalidateQueries({ queryKey: entryKeys.all, exact: true }); + } + wasRunning.current = running; + }, [running, queryClient]); + + return { job, running }; +} diff --git a/react_frontend/src/pages/CalendarPage.tsx b/react_frontend/src/pages/CalendarPage.tsx index fff4f36..26b2a05 100644 --- a/react_frontend/src/pages/CalendarPage.tsx +++ b/react_frontend/src/pages/CalendarPage.tsx @@ -10,7 +10,13 @@ import { subMonths, isSameDay, } from "date-fns"; -import { ChevronLeft, ChevronRight, LayoutGrid, List } from "lucide-react"; +import { + ChevronLeft, + ChevronRight, + LayoutGrid, + List, + Loader2, +} from "lucide-react"; import { Button } from "@/components/ui/button"; import { Dialog, @@ -19,6 +25,7 @@ import { DialogTitle, } from "@/components/ui/dialog"; import { useEpisodesByMonth } from "@/hooks/useEpisodes"; +import { useSeriesSync } from "@/hooks/useSeriesSync"; import { Tooltip, TooltipContent, @@ -46,6 +53,8 @@ export function CalendarPage() { const endDateStr = format(monthEnd, "yyyy-MM-dd"); const { data: episodes = [] } = useEpisodesByMonth(startDateStr, endDateStr); + // Refresh airing TV series (at most every 24h each) so air dates are current + const { job: syncJob, running: syncRunning } = useSeriesSync(); const days = useMemo( () => eachDayOfInterval({ start: monthStart, end: monthEnd }), @@ -69,7 +78,26 @@ export function CalendarPage() { return (
-

Calendar

+
+

Calendar

+ {syncRunning && syncJob?.total ? ( + + + + {syncJob.scope === "all" ? "Refreshing library" : "Updating series"}{" "} + {syncJob.done ?? 0}/{syncJob.total} + + {syncJob.current?.title && ( + + ยท {syncJob.current.title} + + )} + + ) : null} +