Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac0030d611 | ||
|
|
a88423163e |
No files matched your search
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
@@ -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,
|
||||
|
||||
@@ -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<Media>(`/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<StaleRefreshJob>("/entries/sync-series").then((r) => r.data),
|
||||
|
||||
syncSeriesStatus: () =>
|
||||
api
|
||||
.get<StaleRefreshJob>("/entries/sync-series/status")
|
||||
.then((r) => r.data),
|
||||
|
||||
previewTmdb: (tmdbId: number, type: "movie" | "tv") =>
|
||||
api
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex flex-col h-[calc(100vh-3rem)]">
|
||||
<div className="flex items-center justify-between mb-4 shrink-0">
|
||||
<h1 className="text-2xl font-bold">Calendar</h1>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<h1 className="text-2xl font-bold">Calendar</h1>
|
||||
{syncRunning && syncJob?.total ? (
|
||||
<span
|
||||
className="inline-flex min-w-0 items-center gap-1.5 rounded-full border border-border/60 bg-muted/40 px-2.5 py-0.5 text-xs text-muted-foreground"
|
||||
title="Refreshing TV series not updated in the last 24 hours"
|
||||
>
|
||||
<Loader2 className="h-3 w-3 shrink-0 animate-spin" />
|
||||
<span className="tabular-nums">
|
||||
{syncJob.scope === "all" ? "Refreshing library" : "Updating series"}{" "}
|
||||
{syncJob.done ?? 0}/{syncJob.total}
|
||||
</span>
|
||||
{syncJob.current?.title && (
|
||||
<span className="hidden max-w-40 truncate sm:inline">
|
||||
· {syncJob.current.title}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
Reference in new issue
Block a user