diff --git a/server/index.ts b/server/index.ts index 66202e1..45d93f7 100644 --- a/server/index.ts +++ b/server/index.ts @@ -1,7 +1,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; import { readFile } from 'node:fs/promises'; import { resolve } from 'node:path'; -import { defaultConfig, type AppConfig, type AuthPayload, type TitleDetailsRequest } from '../shared/contracts.js'; +import { defaultConfig, type AppConfig, type AuthPayload, type EpisodeWatchStateRequest, type TitleDetailsRequest } from '../shared/contracts.js'; import { decryptJson, deriveEncryptionKey, encryptJson, randomToken, verifyPassword, createPasswordRecord } from './lib/security.js'; import { loadState, readAdmin, readEncryptedConfig, saveAdminAndConfig, updateEncryptedConfig } from './lib/store.js'; import { @@ -17,6 +17,7 @@ import { removeDownload, requestMovie, requestSeries, + setEpisodeWatchState, sanitizeConfig } from './lib/services.js'; @@ -224,6 +225,14 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/episodes/watch-state' && method === 'POST') { + const config = await readConfig(session!.encryptionKey); + const body = await readJson(request); + await setEpisodeWatchState(config, body); + sendJson(response, 200, { ok: true }); + return; + } + if (url.pathname === '/api/downloads/delete' && method === 'POST') { const config = await readConfig(session!.encryptionKey); const body = await readJson<{ id: string }>(request); diff --git a/server/lib/services.ts b/server/lib/services.ts index 789fd44..7f97d80 100644 --- a/server/lib/services.ts +++ b/server/lib/services.ts @@ -11,7 +11,8 @@ import type { TitleDetailsEpisode, TitleDetailsRequest, TitleDetailsResponse, - TitleDetailsSeason + TitleDetailsSeason, + EpisodeWatchStateRequest } from '../../shared/contracts.js'; const TMDB_IMAGE = 'https://image.tmdb.org/t/p'; @@ -406,17 +407,21 @@ export async function getTitleDetails( } const seasons = await getSeriesSeasons(config, seriesItem.Id); - const selectedSeason = chooseSelectedSeason(seasons, seasonId, item); + const nextEpisode = await getNextEpisodeToPlay(config, seriesItem.Id); + const selectedSeason = chooseSelectedSeason(seasons, seasonId, item, nextEpisode); const episodes = selectedSeason?.id - ? await getSeasonEpisodes(config, selectedSeason.id) + ? await getSeasonEpisodes(config, seriesItem.Id, selectedSeason.id) : []; - const nextEpisode = await getNextEpisodeToPlay(config, seriesItem.Id, episodes); + + const resolvedNextEpisode = nextEpisode && episodes.some((episode) => episode.id === nextEpisode.id) + ? episodes.find((episode) => episode.id === nextEpisode.id) || nextEpisode + : nextEpisode; return { id: card.id, tmdbId, providerId: seriesItem.Id, - playTargetId: nextEpisode?.id || seriesItem.Id, + playTargetId: resolvedNextEpisode?.id || seriesItem.Id, availableInJellyfin: Boolean(seriesItem.Id), title, overview, @@ -714,7 +719,8 @@ async function getSeriesSeasons(config: AppConfig, seriesId: string): Promise season.id === requestedSeasonId); @@ -723,6 +729,13 @@ function chooseSelectedSeason( } } + if (typeof nextEpisode?.seasonNumber === 'number') { + const matchingSeason = seasons.find((season) => season.seasonNumber === nextEpisode.seasonNumber); + if (matchingSeason) { + return matchingSeason; + } + } + if (item?.Type === 'Episode' && typeof item.ParentIndexNumber === 'number') { const matchingSeason = seasons.find((season) => season.seasonNumber === item.ParentIndexNumber); if (matchingSeason) { @@ -733,32 +746,17 @@ function chooseSelectedSeason( return seasons.find((season) => season.seasonNumber && season.seasonNumber > 0) || seasons[0]; } -async function getSeasonEpisodes(config: AppConfig, seasonId: string): Promise { +async function getSeasonEpisodes(config: AppConfig, seriesId: string, seasonId: string): Promise { try { const episodes = await jellyfinFetch( config, - `/Users/${encodeURIComponent(config.jellyfin.userId)}/Items?parentId=${encodeURIComponent(seasonId)}&includeItemTypes=Episode&fields=Overview,ImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber&sortBy=SortName` + `/Shows/${encodeURIComponent(seriesId)}/Episodes?userId=${encodeURIComponent(config.jellyfin.userId)}&seasonId=${encodeURIComponent(seasonId)}&enableUserData=true&fields=Overview,ImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber&sortBy=SortName` ); return episodes .filter((episode) => episode.Id) .sort((left, right) => (left.IndexNumber ?? 0) - (right.IndexNumber ?? 0)) - .map((episode) => { - const imageTag = episode.ImageTags?.Primary || ''; - return { - id: String(episode.Id), - title: episode.Name || `Episode ${episode.IndexNumber ?? ''}`.trim(), - overview: episode.Overview || '', - subtitle: [ - typeof episode.ParentIndexNumber === 'number' ? `Season ${episode.ParentIndexNumber}` : '', - typeof episode.IndexNumber === 'number' ? `Episode ${episode.IndexNumber}` : '' - ].filter(Boolean).join(', '), - imageUrl: buildJellyfinAssetUrl(String(episode.Id), 'Primary', 960, imageTag), - seasonNumber: episode.ParentIndexNumber, - episodeNumber: episode.IndexNumber, - runtimeMinutes: episode.RunTimeTicks ? Math.max(1, Math.round(episode.RunTimeTicks / 600000000)) : undefined - }; - }); + .map(mapJellyfinEpisode); } catch { return []; } @@ -766,40 +764,71 @@ async function getSeasonEpisodes(config: AppConfig, seasonId: string): Promise { if (!config.jellyfin.baseUrl || !config.jellyfin.apiKey || !config.jellyfin.userId) { - return currentEpisodes[0] || null; + return null; } try { const response = await jellyfinFetch<{ Items?: JellyfinItem[] }>( config, - `/Shows/NextUp?userId=${encodeURIComponent(config.jellyfin.userId)}&seriesId=${encodeURIComponent(seriesId)}&fields=Overview,ImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber&limit=1` + `/Shows/NextUp?userId=${encodeURIComponent(config.jellyfin.userId)}&seriesId=${encodeURIComponent(seriesId)}&enableUserData=true&fields=Overview,ImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber&limit=1` ); - const episode = response.Items?.[0]; - if (!episode?.Id) { - return currentEpisodes[0] || null; + const episode = response.Items?.find((item) => item.Id); + if (episode) { + return mapJellyfinEpisode(episode); } - - const imageTag = episode.ImageTags?.Primary || ''; - return { - id: String(episode.Id), - title: episode.Name || `Episode ${episode.IndexNumber ?? ''}`.trim(), - overview: episode.Overview || '', - subtitle: [ - typeof episode.ParentIndexNumber === 'number' ? `Season ${episode.ParentIndexNumber}` : '', - typeof episode.IndexNumber === 'number' ? `Episode ${episode.IndexNumber}` : '' - ].filter(Boolean).join(', '), - imageUrl: buildJellyfinAssetUrl(String(episode.Id), 'Primary', 960, imageTag), - seasonNumber: episode.ParentIndexNumber, - episodeNumber: episode.IndexNumber, - runtimeMinutes: episode.RunTimeTicks ? Math.max(1, Math.round(episode.RunTimeTicks / 600000000)) : undefined - }; } catch { - return currentEpisodes[0] || null; } + + try { + const episodes = await getSeriesEpisodesForNextUp(config, seriesId); + const nextEpisode = episodes.find((episode) => !episode.watched); + return nextEpisode || episodes[0] || null; + } catch { + return null; + } +} + +async function getSeriesEpisodesForNextUp(config: AppConfig, seriesId: string): Promise { + const episodes = await jellyfinFetch( + config, + `/Users/${encodeURIComponent(config.jellyfin.userId)}/Items?parentId=${encodeURIComponent(seriesId)}&recursive=true&includeItemTypes=Episode&enableUserData=true&fields=Overview,ImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber&sortBy=SortName` + ); + + return episodes + .filter((episode) => episode.Id) + .sort((left, right) => { + const seasonDifference = (left.ParentIndexNumber ?? 0) - (right.ParentIndexNumber ?? 0); + if (seasonDifference !== 0) { + return seasonDifference; + } + + return (left.IndexNumber ?? 0) - (right.IndexNumber ?? 0); + }) + .map(mapJellyfinEpisode); +} + +function mapJellyfinEpisode(episode: JellyfinItem): TitleDetailsEpisode { + const imageTag = episode.ImageTags?.Primary || ''; + + return { + id: String(episode.Id), + title: episode.Name || `Episode ${episode.IndexNumber ?? ''}`.trim(), + overview: episode.Overview || '', + subtitle: [ + typeof episode.ParentIndexNumber === 'number' ? `Season ${episode.ParentIndexNumber}` : '', + typeof episode.IndexNumber === 'number' ? `Episode ${episode.IndexNumber}` : '' + ].filter(Boolean).join(', '), + imageUrl: buildJellyfinAssetUrl(String(episode.Id), 'Primary', 960, imageTag), + seasonNumber: episode.ParentIndexNumber, + episodeNumber: episode.IndexNumber, + runtimeMinutes: episode.RunTimeTicks ? Math.max(1, Math.round(episode.RunTimeTicks / 600000000)) : undefined, + watched: Boolean(episode.UserData?.Played), + progress: Math.max(0, Math.min(100, Math.round(episode.UserData?.PlayedPercentage || 0))) || undefined, + playbackPositionTicks: episode.UserData?.PlaybackPositionTicks + }; } export async function requestMovie(config: AppConfig, tmdbId: number): Promise { @@ -866,6 +895,31 @@ export async function requestSeries(config: AppConfig, tmdbId: number): Promise< }); } +export async function setEpisodeWatchState(config: AppConfig, payload: EpisodeWatchStateRequest): Promise { + if (!config.jellyfin.baseUrl || !config.jellyfin.apiKey || !config.jellyfin.userId) { + throw new Error('Jellyfin is not configured.'); + } + + const episodeId = String(payload.episodeId || '') + if (!episodeId) { + throw new Error('Episode id is required.') + } + + const path = `/Users/${encodeURIComponent(config.jellyfin.userId)}/PlayedItems/${encodeURIComponent(episodeId)}` + const url = `${config.jellyfin.baseUrl}${path}` + const response = await fetch(payload.watched ? `${url}?datePlayed=${encodeURIComponent(new Date().toISOString())}` : url, { + method: payload.watched ? 'POST' : 'DELETE', + headers: { + Accept: 'application/json', + 'X-Emby-Token': config.jellyfin.apiKey + } + }) + + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`) + } +} + export async function proxyJellyfinImage( config: AppConfig, itemId: string, diff --git a/shared/contracts.ts b/shared/contracts.ts index e06decc..723a86f 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -116,6 +116,9 @@ export interface TitleDetailsEpisode { seasonNumber?: number; episodeNumber?: number; runtimeMinutes?: number; + watched?: boolean; + progress?: number; + playbackPositionTicks?: number; } export interface TitleDetailsSeason { @@ -175,6 +178,11 @@ export interface TitleDetailsRequest { seasonId?: string; } +export interface EpisodeWatchStateRequest { + episodeId: string; + watched: boolean; +} + export interface HubSection { id: string; title: string; diff --git a/src/App.tsx b/src/App.tsx index 6f69aa7..6d35716 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,7 @@ import { type CSSProperties, type FormEvent, + type MouseEvent, type ReactNode, startTransition, useEffect, @@ -27,6 +28,12 @@ type EntryStage = 'onboarding' | 'profiles' | 'dashboard' const MAX_CACHED_HUB_PAGES = 3 type ModalOriginRect = { left: number; top: number; width: number; height: number } type SelectedCardState = { card: MediaCard; originRect: ModalOriginRect | null } +type VisibleSeasonEpisode = TitleDetailsResponse['episodes'][number] & { seasonId: string } + +const SEASON_CACHE_RADIUS = 2 +const SEASON_PREFETCH_OFFSETS = [1, -1, 2, -2] as const +const SEASON_PRELOAD_THRESHOLD_RATIO = 0.45 +const EPISODE_SCROLL_DISTANCE_RATIO = 0.72 const sidebarItems: Array<{ route: AppRoute; label: string; short: string }> = [ { route: 'home', label: 'Inicio', short: 'H' }, @@ -860,6 +867,46 @@ function resolveHeroSlideStyle(card: MediaCard | undefined) { return slideImage ? { backgroundImage: `url("${slideImage}")` } : undefined } +function getSeasonWindowIds(seasons: TitleDetailsResponse['seasons'], centerIndex: number, radius = SEASON_CACHE_RADIUS) { + return seasons + .slice(Math.max(0, centerIndex - radius), centerIndex + radius + 1) + .map((season) => season.id) +} + +function getVisibleSeasonEpisodes( + seasons: TitleDetailsResponse['seasons'], + centerIndex: number, + cache: Map +): VisibleSeasonEpisode[] { + return seasons + .filter((_, index) => Math.abs(index - centerIndex) <= SEASON_CACHE_RADIUS) + .flatMap((season) => + (cache.get(season.id)?.episodes || []).map((episode) => ({ + ...episode, + seasonId: season.id, + })) + ) +} + +function findSeasonAnchorElement(list: HTMLDivElement, seasonId: string) { + return list.querySelector(`[data-season-id="${CSS.escape(seasonId)}"]`) +} + +function findEpisodeElement(list: HTMLDivElement, episodeId: string) { + return list.querySelector(`[data-episode-id="${CSS.escape(episodeId)}"]`) +} + +function centerEpisodeInList(list: HTMLDivElement, episodeId: string, behavior: ScrollBehavior) { + const targetEpisode = findEpisodeElement(list, episodeId) + if (!targetEpisode) { + return false + } + + const centeredLeft = Math.max(0, targetEpisode.offsetLeft - (list.clientWidth - targetEpisode.offsetWidth) / 2) + list.scrollTo({ left: centeredLeft, behavior }) + return true +} + function cacheHubPage( current: Partial>, page: HubPageResponse['page'], @@ -944,6 +991,7 @@ function TitleDetailsModal(props: { const [activeSeasonId, setActiveSeasonId] = useState(undefined) const [seasonCacheVersion, setSeasonCacheVersion] = useState(0) const [loadingSeasonIds, setLoadingSeasonIds] = useState([]) + const [episodeWatchBusyId, setEpisodeWatchBusyId] = useState(null) const [playerTarget, setPlayerTarget] = useState<{ id: string; title: string } | null>(null) const [isOverviewExpanded, setIsOverviewExpanded] = useState(false) const [episodeScrollState, setEpisodeScrollState] = useState({ canScrollLeft: false, canScrollRight: false }) @@ -958,6 +1006,7 @@ function TitleDetailsModal(props: { const seasonRequestsRef = useRef(new Map>()) const pendingSeasonScrollRef = useRef(null) const previousRenderedSeasonIdsRef = useRef([]) + const initialEpisodeFocusKeyRef = useRef('') useLayoutEffect(() => { if (!props.originRect || !modalRef.current) { @@ -1007,12 +1056,14 @@ function TitleDetailsModal(props: { setActiveSeasonId(undefined) setSeasonCacheVersion(0) setLoadingSeasonIds([]) + setEpisodeWatchBusyId(null) setPlayerTarget(null) setIsOverviewExpanded(false) seasonDetailsCacheRef.current.clear() seasonRequestsRef.current.clear() pendingSeasonScrollRef.current = null previousRenderedSeasonIdsRef.current = [] + initialEpisodeFocusKeyRef.current = '' }, [props.card.id]) function cacheSeasonDetails(nextDetails: TitleDetailsResponse, requestedSeason?: string) { @@ -1053,6 +1104,31 @@ function TitleDetailsModal(props: { return request } + function updateEpisodeInCaches(episodeId: string, updater: (episode: NonNullable[number]) => NonNullable[number]) { + let changed = false + for (const [key, cachedDetails] of seasonDetailsCacheRef.current.entries()) { + if (!cachedDetails.episodes.some((episode) => episode.id === episodeId)) { + continue + } + + seasonDetailsCacheRef.current.set(key, { + ...cachedDetails, + episodes: cachedDetails.episodes.map((episode) => episode.id === episodeId ? updater(episode) : episode) + }) + changed = true + } + + if (changed) { + setSeasonCacheVersion((current) => current + 1) + setDetails((current) => current && current.episodes.some((episode) => episode.id === episodeId) + ? { + ...current, + episodes: current.episodes.map((episode) => episode.id === episodeId ? updater(episode) : episode) + } + : current) + } + } + useEffect(() => { let cancelled = false const cacheKey = requestedSeasonId || '__default__' @@ -1112,11 +1188,7 @@ function TitleDetailsModal(props: { return } - const keepSeasonIds = new Set( - details.seasons - .slice(Math.max(0, currentIndex - 2), currentIndex + 3) - .map((season) => season.id) - ) + const keepSeasonIds = new Set(getSeasonWindowIds(details.seasons, currentIndex)) for (const seasonId of Array.from(seasonDetailsCacheRef.current.keys())) { if (seasonId !== '__default__' && !keepSeasonIds.has(seasonId)) { @@ -1135,12 +1207,9 @@ function TitleDetailsModal(props: { return } - const prioritySeasonIds = [ - details.seasons[activeIndex + 1]?.id, - details.seasons[activeIndex - 1]?.id, - details.seasons[activeIndex + 2]?.id, - details.seasons[activeIndex - 2]?.id, - ].filter(Boolean) as string[] + const prioritySeasonIds = SEASON_PREFETCH_OFFSETS + .map((offset) => details.seasons[activeIndex + offset]?.id) + .filter(Boolean) as string[] for (const seasonId of prioritySeasonIds) { if (!seasonDetailsCacheRef.current.has(seasonId)) { @@ -1156,7 +1225,7 @@ function TitleDetailsModal(props: { return } - const targetEpisode = list.querySelector(`[data-season-id="${CSS.escape(targetSeasonId)}"]`) + const targetEpisode = findSeasonAnchorElement(list, targetSeasonId) if (!targetEpisode) { return } @@ -1170,6 +1239,25 @@ function TitleDetailsModal(props: { pendingSeasonScrollRef.current = null }, [details, seasonCacheVersion, seasonValue]) + useLayoutEffect(() => { + const list = episodeListRef.current + const playTargetId = details?.playTargetId + if (!list || !playTargetId || pendingSeasonScrollRef.current) { + return + } + + const focusKey = `${props.card.id}:${playTargetId}` + if (initialEpisodeFocusKeyRef.current === focusKey) { + return + } + + if (!centerEpisodeInList(list, playTargetId, 'auto')) { + return + } + + initialEpisodeFocusKeyRef.current = focusKey + }, [details?.playTargetId, props.card.id, seasonCacheVersion]) + useLayoutEffect(() => { const list = episodeListRef.current if (!list || pendingSeasonScrollRef.current) { @@ -1193,12 +1281,12 @@ function TitleDetailsModal(props: { if (previousFirstSeasonId && currentFirstSeasonId && previousFirstSeasonId !== currentFirstSeasonId) { if (currentRenderedSeasonIds.includes(previousFirstSeasonId)) { - const anchorCard = list.querySelector(`[data-season-id="${CSS.escape(previousFirstSeasonId)}"]`) + const anchorCard = findSeasonAnchorElement(list, previousFirstSeasonId) if (anchorCard) { list.scrollLeft += anchorCard.offsetLeft } } else if (previousRenderedSeasonIds.includes(currentFirstSeasonId)) { - const currentFirstCard = list.querySelector(`[data-season-id="${CSS.escape(currentFirstSeasonId)}"]`) + const currentFirstCard = findSeasonAnchorElement(list, currentFirstSeasonId) if (currentFirstCard) { list.scrollLeft = Math.max(0, list.scrollLeft - currentFirstCard.offsetLeft) } @@ -1265,7 +1353,7 @@ function TitleDetailsModal(props: { return } - const preloadThreshold = list.clientWidth * 0.45 + const preloadThreshold = list.clientWidth * SEASON_PRELOAD_THRESHOLD_RATIO const previousSeasonId = details.seasons[activeIndex - 1]?.id const nextSeasonId = details.seasons[activeIndex + 1]?.id const nextNextSeasonId = details.seasons[activeIndex + 2]?.id @@ -1326,14 +1414,9 @@ function TitleDetailsModal(props: { const nextSeasonId = hasNextSeason ? details?.seasons[resolvedSeasonIndex + 1]?.id : undefined const isPreviousSeasonLoading = Boolean(previousSeasonId && loadingSeasonIds.includes(previousSeasonId)) const isNextSeasonLoading = Boolean(nextSeasonId && loadingSeasonIds.includes(nextSeasonId)) - const visibleEpisodes = details?.seasons - .filter((season, index) => Math.abs(index - resolvedSeasonIndex) <= 2) - .flatMap((season) => - (seasonDetailsCacheRef.current.get(season.id)?.episodes || []).map((episode) => ({ - ...episode, - seasonId: season.id, - })) - ) ?? [] + const visibleEpisodes = details + ? getVisibleSeasonEpisodes(details.seasons, resolvedSeasonIndex, seasonDetailsCacheRef.current) + : [] function handleRequestClose() { if (!props.originRect || transitionState === 'closing') { @@ -1351,7 +1434,7 @@ function TitleDetailsModal(props: { const list = episodeListRef.current if (!list) return - const distance = Math.max(list.clientWidth * 0.72, 320) + const distance = Math.max(list.clientWidth * EPISODE_SCROLL_DISTANCE_RATIO, 320) list.scrollBy({ left: direction === 'left' ? -distance : distance, behavior: 'smooth', @@ -1382,13 +1465,46 @@ function TitleDetailsModal(props: { }) } + function handleEpisodeWatchToggle( + event: MouseEvent, + episodeId: string, + watched: boolean | undefined, + progress: number | undefined, + playbackPositionTicks: number | undefined + ) { + event.preventDefault() + event.stopPropagation() + + const nextWatched = !watched + setEpisodeWatchBusyId(episodeId) + updateEpisodeInCaches(episodeId, (episode) => ({ + ...episode, + watched: nextWatched, + progress: nextWatched ? undefined : 0, + playbackPositionTicks: nextWatched ? undefined : 0, + })) + + void api.setEpisodeWatchState({ episodeId, watched: nextWatched }) + .catch(() => { + updateEpisodeInCaches(episodeId, (episode) => ({ + ...episode, + watched: watched ?? false, + progress, + playbackPositionTicks, + })) + }) + .finally(() => { + setEpisodeWatchBusyId((current) => current === episodeId ? null : current) + }) + } + if (playerTarget && jellyfinPlayerUrl) { return (
- +