diff --git a/public/networks/disney.webp b/public/networks/disney.webp new file mode 100644 index 0000000..d4e9450 Binary files /dev/null and b/public/networks/disney.webp differ diff --git a/public/networks/hbo.svg b/public/networks/hbo.svg new file mode 100644 index 0000000..f3ef07a --- /dev/null +++ b/public/networks/hbo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/networks/netflix.png b/public/networks/netflix.png new file mode 100644 index 0000000..4291554 Binary files /dev/null and b/public/networks/netflix.png differ diff --git a/public/networks/prime.svg b/public/networks/prime.svg new file mode 100644 index 0000000..1705aea --- /dev/null +++ b/public/networks/prime.svg @@ -0,0 +1,74 @@ + + + + diff --git a/public/networks/viki.png b/public/networks/viki.png new file mode 100644 index 0000000..38ebb67 Binary files /dev/null and b/public/networks/viki.png differ diff --git a/server/index.ts b/server/index.ts index e75c88d..0051049 100644 --- a/server/index.ts +++ b/server/index.ts @@ -9,6 +9,7 @@ import { getDashboard, getDownloads, getHubPage, + getTmdbLogos, getServiceOptions, loadJellyfinUsers, proxyJellyfinImage, @@ -196,13 +197,15 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): if (url.pathname.startsWith('/api/hubs/') && method === 'GET') { const config = await readConfig(session!.encryptionKey); - const page = decodeURIComponent(url.pathname.replace('/api/hubs/', '')) as - | 'stream' - | 'home' - | 'anime' - | 'dorama' - | 'library'; - sendJson(response, 200, await getHubPage(config, page)); + const page = decodeURIComponent(url.pathname.replace('/api/hubs/', '')); + console.log(`[API] GET /api/hubs/${page}`); + try { + const result = await getHubPage(config, page as any); + sendJson(response, 200, result); + } catch (err) { + console.error(`[API] Error in GET /api/hubs/${page}:`, err); + sendJson(response, 500, { error: err instanceof Error ? err.message : 'Internal server error' }); + } return; } @@ -251,6 +254,22 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/tmdb/logo' && method === 'GET') { + const config = await readConfig(session!.encryptionKey); + const tmdbId = Number(url.searchParams.get('tmdbId') || 0); + const mediaTypeParam = url.searchParams.get('mediaType'); + const mediaType = mediaTypeParam === 'tv' ? 'tv' : mediaTypeParam === 'movie' ? 'movie' : null; + + if (!tmdbId || !mediaType) { + sendJson(response, 400, { error: 'tmdbId and mediaType are required.' }); + return; + } + + const logos = await getTmdbLogos(config, tmdbId, mediaType); + sendJson(response, 200, { logos }); + return; + } + await serveApp(url.pathname, response); } diff --git a/server/lib/services.ts b/server/lib/services.ts index 6bf2f0e..b21b7e2 100644 --- a/server/lib/services.ts +++ b/server/lib/services.ts @@ -28,9 +28,12 @@ interface JellyfinItem { Played?: boolean; UnplayedItemCount?: number; }; + SeriesId?: string; SeriesName?: string; ParentIndexNumber?: number; IndexNumber?: number; + ParentBackdropItemId?: string; + ParentBackdropImageTags?: string[]; DateCreated?: string; DateLastMediaAdded?: string; } @@ -69,21 +72,6 @@ interface QbitTorrent { const ANIME_PROVIDERS = '337|8|9|430|283'; const DORAMA_PROVIDERS = '344|337|8|9|464'; -const GENRE_ASSETS: Array<{ id: number; title: string; posterUrl: string }> = [ - { id: 28, title: 'Action', posterUrl: '/reiverr/genres/action.jpg' }, - { id: 12, title: 'Adventure', posterUrl: '/reiverr/genres/adventure.jpg' }, - { id: 16, title: 'Animation', posterUrl: '/reiverr/genres/animation.jpg' }, - { id: 35, title: 'Comedy', posterUrl: '/reiverr/genres/comedy.jpg' }, - { id: 80, title: 'Crime', posterUrl: '/reiverr/genres/crime.jpg' } -]; -const NETWORK_ASSETS: Array<{ id: number; title: string; posterUrl: string }> = [ - { id: 213, title: 'Netflix', posterUrl: '/reiverr/networks/netflix.svg' }, - { id: 2739, title: 'Disney+', posterUrl: '/reiverr/networks/disney.svg' }, - { id: 49, title: 'HBO', posterUrl: '/reiverr/networks/hbo.svg' }, - { id: 453, title: 'Hulu', posterUrl: '/reiverr/networks/hulu.svg' }, - { id: 1024, title: 'Prime Video', posterUrl: '/reiverr/networks/amazon.svg' }, - { id: 2552, title: 'Apple TV+', posterUrl: '/reiverr/networks/apple.svg' } -]; export function sanitizeConfig(input: AppConfig): AppConfig { return { @@ -212,18 +200,77 @@ export async function getHubPage( config: AppConfig, page: HubPageResponse['page'] ): Promise { - const [library, downloads] = await Promise.all([ - getLibrarySnapshot(config), - getDownloads(config) - ]); + console.log(`[getHubPage] Loading page: ${page}`); + let library: { continueWatching: MediaCard[]; recentlyAdded: MediaCard[]; allItems: JellyfinItem[] }; + let downloads: DownloadItem[]; - const allSections = await buildHubSections(config, library, page); + try { + [library, downloads] = await Promise.all([ + getLibrarySnapshot(config), + getDownloads(config) + ]); + } catch (err) { + console.error(`[getHubPage] Error fetching library/downloads for ${page}:`, err); + library = { continueWatching: [], recentlyAdded: [], allItems: [] }; + downloads = []; + } + + const allSections = await buildHubSections(config, library, page).catch((err) => { + console.error(`[getHubPage] Error building hub sections for ${page}:`, err); + return { hero: [], sections: [] }; + }) || { hero: [], sections: [] }; + + console.log(`[getHubPage] Sections built for ${page}. Hero count: ${allSections.hero?.length}, Section count: ${allSections.sections?.length}`); + const isNetworkPage = ['netflix', 'primevideo', 'hbo', 'viki', 'disney'].includes(page); + if (page !== 'home' && !isNetworkPage && allSections.hero?.length === 0 && allSections.sections?.every(s => s.items.length === 0)) { + console.log(`[getHubPage] Hub for ${page} is completely empty, using Home as fallback`); + return getHubPage(config, 'home'); + } + + const backdropCache = new Map>(); + const networkScopedContinueWatching = isNetworkPage + ? (() => { + const sectionTmdbIds = new Set( + uniqueCards([...allSections.hero, ...allSections.sections.flatMap((section) => section.items)]) + .map((item) => item.tmdbId) + .filter((value): value is number => Boolean(value)) + ); + const filtered = library.continueWatching.filter((card) => card.tmdbId && sectionTmdbIds.has(card.tmdbId)); + const minimumScopedItems = Math.min(3, library.continueWatching.length); + return filtered.length >= minimumScopedItems ? filtered : library.continueWatching; + })() + : library.continueWatching; + + const [continueWatching, heroWithHighResBackdrops, sectionsWithHighResBackdrops] = await Promise.all([ + applyHighResBackdropsToCards( + config, + networkScopedContinueWatching, + shouldUseHighResBackdropForCard, + backdropCache, + 'en' + ), + applyHighResBackdropsToCards( + config, + (allSections && allSections.hero) || [], + shouldUseHighResBackdropForCard, + backdropCache, + null + ), + applyHighResBackdropsToSections( + config, + (allSections && allSections.sections) || [], + backdropCache, + 'en' + ) + ]); return { page, - hero: allSections.hero, - continueWatching: library.continueWatching, - sections: allSections.sections.concat( + hero: heroWithHighResBackdrops || [], + continueWatching, + sections: (sectionsWithHighResBackdrops || []) + .filter((section) => section.items.some((item) => item.backdropUrl || item.posterUrl)) + .concat( page === 'library' && downloads.length ? [{ id: 'downloads', @@ -416,8 +463,8 @@ async function getLibrarySnapshot(config: AppConfig): Promise<{ try { [resume, nextUp, allItems] = await Promise.all([ - jellyfinFetch(config, `/Users/${config.jellyfin.userId}/Items/Resume?mediaTypes=Video&fields=ProviderIds,Overview`), - jellyfinFetch(config, `/Shows/NextUp?userId=${config.jellyfin.userId}&fields=ProviderIds,Overview`), + jellyfinFetch(config, `/Users/${config.jellyfin.userId}/Items/Resume?mediaTypes=Video&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber`), + jellyfinFetch(config, `/Shows/NextUp?userId=${config.jellyfin.userId}&fields=ProviderIds,Overview,SeriesId,ParentBackdropItemId,ParentBackdropImageTags,RunTimeTicks,ParentIndexNumber,IndexNumber`), jellyfinFetch( config, `/Users/${config.jellyfin.userId}/Items?recursive=true&includeItemTypes=Movie,Series&hasTmdbId=true&fields=ProviderIds,DateCreated,DateLastMediaAdded,Overview` @@ -431,9 +478,15 @@ async function getLibrarySnapshot(config: AppConfig): Promise<{ }; } + const tmdbIdByItemId = new Map( + allItems + .filter((item) => item.Id) + .map((item) => [String(item.Id), Number(item.ProviderIds?.Tmdb) || undefined] as const) + ); + const continueWatching = [...resume, ...nextUp] .slice(0, 12) - .map((item) => jellyfinToCard(item, item.SeriesName || item.Name || 'Continue watching')) + .map((item) => jellyfinToCard(item, item.SeriesName || item.Name || 'Continue watching', tmdbIdByItemId)) .filter(Boolean) as MediaCard[]; const recentlyAdded = [...allItems] @@ -458,6 +511,7 @@ async function buildHubSections( library: Awaited>, page: HubPageResponse['page'] ): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { + console.log(`[buildHubSections] Routing for page: ${page}`); switch (page) { case 'stream': return buildStreamHub(config, library); @@ -467,8 +521,21 @@ async function buildHubSections( return buildAnimeHub(config, library); case 'dorama': return buildDoramaHub(config, library); + case 'netflix': + return buildNetworkHub(config, library, 213, 'Netflix'); + case 'primevideo': + return buildNetworkHub(config, library, 1024, 'Prime Video'); + case 'hbo': + return buildNetworkHub(config, library, 49, 'HBO'); + case 'viki': + return buildNetworkHub(config, library, 1595, 'Viki'); + case 'disney': + return buildNetworkHub(config, library, 2739, 'Disney+'); case 'library': return buildLibraryHub(config, library); + default: + console.warn(`[buildHubSections] No specific handler for page: ${page}, falling back to home`); + return buildHomeHub(config, library); } } @@ -476,28 +543,40 @@ async function buildStreamHub( config: AppConfig, library: Awaited> ): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { - const tmdb = await getTmdbSnapshot(config); + const language = config.preferences.language || 'en-US'; + const region = config.preferences.region || 'US'; + + const [trending, recommended, trendingSeries] = await Promise.all([ + tmdbResultCards(config, `/trending/movie/week?language=${encodeURIComponent(language)}`, 'landscape'), + tmdbResultCards(config, `/movie/popular?language=${encodeURIComponent(language)}®ion=${encodeURIComponent(region)}`, 'landscape'), + tmdbResultCards(config, `/tv/popular?language=${encodeURIComponent(language)}`, 'landscape') + ]); + + const filter = (items: MediaCard[]) => { + const libraryTmdbIds = new Set(library.allItems.map((item) => Number(item.ProviderIds?.Tmdb)).filter(Boolean)); + return config.preferences.excludeLibraryItems + ? items.filter(item => !item.tmdbId || !libraryTmdbIds.has(item.tmdbId)) + : items; + }; + + const filteredHero = filter(trending || []); + const filteredRecommendations = filter(recommended || []); + const filteredTrendingSeries = filter(trendingSeries || []); return { - hero: [...library.continueWatching, ...tmdb.hero].slice(0, 6), + hero: filteredHero.slice(0, 6), sections: [ - { - id: 'continue', - title: 'Continue Watching', - style: 'landscape', - items: library.continueWatching - }, { id: 'recommendations', title: 'Recommendations', style: 'landscape', - items: tmdb.recommendations + items: filteredRecommendations.slice(0, 12) }, { id: 'trending-series', title: 'Trending Series', style: 'landscape', - items: tmdb.trendingSeries + items: filteredTrendingSeries.slice(0, 12) } ] }; @@ -507,50 +586,51 @@ async function buildHomeHub( config: AppConfig, library: Awaited> ): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { + const language = config.preferences.language || 'en-US'; + const region = config.preferences.region || 'US'; + const [ trending, - popularPeople, upcomingMovies, upcomingSeries, digitalReleases, streamingNow ] = await Promise.all([ - tmdbResultCards(config, `/trending/all/day?language=${encodeURIComponent(config.preferences.language)}`, 'landscape'), - tmdbPeopleCards(config, `/trending/person/week?language=${encodeURIComponent(config.preferences.language)}`), - tmdbResultCards( - config, - `/discover/movie?primary_release_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}®ion=${encodeURIComponent(config.preferences.region)}`, - 'landscape' - ), - tmdbResultCards( - config, - `/discover/tv?first_air_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}`, - 'landscape' - ), - tmdbResultCards( - config, - `/discover/movie?with_release_type=4&sort_by=popularity.desc&release_date.lte=${todayIso()}&language=${encodeURIComponent(config.preferences.language)}`, - 'landscape' - ), - tmdbResultCards( - config, - `/discover/tv?air_date.gte=${todayIso()}&first_air_date.lte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}`, - 'landscape' - ) + tmdbResultCards(config, `/trending/all/day?language=${encodeURIComponent(language)}`, 'landscape'), + tmdbResultCards(config, `/discover/movie?primary_release_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(language)}®ion=${encodeURIComponent(region)}`, 'landscape'), + tmdbResultCards(config, `/discover/tv?first_air_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(language)}`, 'landscape'), + tmdbResultCards(config, `/discover/movie?with_release_type=4&sort_by=popularity.desc&release_date.lte=${todayIso()}&language=${encodeURIComponent(language)}`, 'landscape'), + tmdbResultCards(config, `/discover/tv?air_date.gte=${todayIso()}&first_air_date.lte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(language)}`, 'landscape') ]); + const filter = (items: MediaCard[]) => { + const libraryTmdbIds = new Set(library.allItems.map((item) => Number(item.ProviderIds?.Tmdb)).filter(Boolean)); + return config.preferences.excludeLibraryItems + ? items.filter(item => !item.tmdbId || !libraryTmdbIds.has(item.tmdbId)) + : items; + }; + + const filteredHero = filter(trending || []); + + const heroCandidates = uniqueCards([ + ...filteredHero, + ...filter(digitalReleases || []), + ...filter(streamingNow || []), + ...filter(upcomingMovies || []), + ...filter(upcomingSeries || []) + ]) + .filter((item) => item.backdropUrl || item.posterUrl) + .slice(0, 6); + return { - hero: trending.slice(0, 6), + hero: heroCandidates, sections: [ - { id: 'trending', title: 'Trending', style: 'landscape', items: trending }, - { id: 'people', title: 'Popular People', style: 'profile', items: popularPeople }, - { id: 'upcoming-movies', title: 'Upcoming Movies', style: 'landscape', items: upcomingMovies }, - { id: 'upcoming-series', title: 'Upcoming Series', style: 'landscape', items: upcomingSeries }, - { id: 'genres', title: 'Genres', style: 'genre', items: genreCards() }, - { id: 'digital', title: 'New Digital Releases', style: 'landscape', items: digitalReleases }, - { id: 'streaming', title: 'Streaming Now', style: 'landscape', items: streamingNow }, - { id: 'networks', title: 'TV Networks', style: 'network', items: networkCards() }, - { id: 'recently-added', title: 'Recently Added', style: 'landscape', items: library.recentlyAdded } + { id: 'trending', title: 'Trending', style: 'landscape', items: filteredHero }, + { id: 'upcoming-movies', title: 'Upcoming Movies', style: 'landscape', items: filter(upcomingMovies || []) }, + { id: 'upcoming-series', title: 'Upcoming Series', style: 'landscape', items: filter(upcomingSeries || []) }, + { id: 'digital', title: 'New Digital Releases', style: 'landscape', items: filter(digitalReleases || []) }, + { id: 'streaming', title: 'Streaming Now', style: 'landscape', items: filter(streamingNow || []) }, + { id: 'recently-added', title: 'Recently Added', style: 'landscape', items: library.recentlyAdded || [] } ] }; } @@ -559,35 +639,94 @@ async function buildAnimeHub( config: AppConfig, library: Awaited> ): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { + const region = config.preferences.region || 'US'; + const language = config.preferences.language || 'en-US'; + const recentWindowDays = 365; + const providerFilter = `watch_region=${encodeURIComponent(region)}&with_watch_providers=${ANIME_PROVIDERS}`; + const animeFilter = `include_adult=false&with_genres=16&with_original_language=ja&language=${encodeURIComponent(language)}`; + const [ - hero, - trendingSeries, + trendingShows, trendingMovies, - popularSeries, - popularMovies, + fallbackTrendingMovies, + allTimePopularShows, + allTimePopularMovies, upcomingSeries, upcomingMovies ] = await Promise.all([ - tmdbResultCards(config, `/discover/tv?include_adult=false&sort_by=popularity.desc&watch_region=JP&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16&with_original_language=ja&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${daysAgoIso(90)}&include_adult=false&sort_by=popularity.desc&watch_region=JP&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16&with_original_language=ja&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/movie?primary_release_date.gte=${daysAgoIso(360)}&include_adult=false&sort_by=popularity.desc&watch_region=JP&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16&with_original_language=ja&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?include_adult=false&sort_by=popularity.desc&watch_region=JP&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16&with_original_language=ja&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/movie?include_adult=false&sort_by=popularity.desc&watch_region=JP&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16&with_original_language=ja&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}&with_original_language=ja&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16`, 'landscape'), - tmdbResultCards(config, `/discover/movie?primary_release_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}&with_original_language=ja&with_watch_providers=${ANIME_PROVIDERS}&with_genres=16`, 'landscape') + tmdbPagedResultCards( + config, + `/discover/tv?sort_by=popularity.desc&first_air_date.gte=${daysAgoIso(recentWindowDays)}&first_air_date.lte=${todayIso()}&${providerFilter}&${animeFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=popularity.desc&primary_release_date.gte=${daysAgoIso(recentWindowDays)}&primary_release_date.lte=${todayIso()}&${providerFilter}&${animeFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=popularity.desc&${providerFilter}&${animeFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/tv?sort_by=vote_count.desc&${providerFilter}&${animeFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=vote_count.desc&${providerFilter}&${animeFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/tv?sort_by=popularity.desc&first_air_date.gte=${todayIso()}&include_adult=false&with_genres=16&with_original_language=ja&language=${encodeURIComponent(language)}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=popularity.desc&primary_release_date.gte=${todayIso()}&include_adult=false&with_genres=16&with_original_language=ja&language=${encodeURIComponent(language)}`, + 'landscape' + ) ]); + const filter = (items: MediaCard[]) => { + const libraryTmdbIds = new Set(library.allItems.map((item) => Number(item.ProviderIds?.Tmdb)).filter(Boolean)); + const uniqueItems = uniqueCards(items.filter(Boolean)); + return config.preferences.excludeLibraryItems + ? uniqueItems.filter(item => !item.tmdbId || !libraryTmdbIds.has(item.tmdbId)) + : uniqueItems; + }; + + const filteredTrendingShows = filter(trendingShows || []); + const filteredTrendingMovies = uniqueCards([ + ...filter(trendingMovies || []), + ...filter(fallbackTrendingMovies || []) + ]).slice(0, 12); + const filteredAllTimePopular = uniqueCards([ + ...filter(allTimePopularShows || []), + ...filter(allTimePopularMovies || []) + ]); + const filteredUpcoming = uniqueCards([ + ...filter(upcomingSeries || []), + ...filter(upcomingMovies || []) + ]); + const filteredHero = uniqueCards([ + ...filteredTrendingShows, + ...filteredTrendingMovies + ]); + + const sections: HubSection[] = [ + { id: 'anime-trending-shows', title: 'Trending Shows', style: 'landscape', items: filteredTrendingShows }, + { id: 'anime-trending-movies', title: 'Trending Movies', style: 'landscape', items: filteredTrendingMovies }, + { id: 'anime-all-time-popular', title: 'All Time Popular', style: 'landscape', items: filteredAllTimePopular }, + { id: 'anime-upcoming', title: 'Upcoming', style: 'landscape', items: filteredUpcoming } + ]; + return { - hero: hero.slice(0, 6), - sections: [ - { id: 'continue', title: 'Continue Watching', style: 'landscape', items: library.continueWatching }, - { id: 'anime-series-new', title: 'New & Trending Series', style: 'landscape', items: trendingSeries }, - { id: 'anime-movies-new', title: 'New & Trending Movies', style: 'landscape', items: trendingMovies }, - { id: 'anime-series-popular', title: 'Popular Series', style: 'landscape', items: popularSeries }, - { id: 'anime-movies-popular', title: 'Popular Movies', style: 'landscape', items: popularMovies }, - { id: 'anime-upcoming-series', title: 'Upcoming Series', style: 'landscape', items: upcomingSeries }, - { id: 'anime-upcoming-movies', title: 'Upcoming Movies', style: 'landscape', items: upcomingMovies } - ] + hero: filteredHero.slice(0, 6), + sections: sections.filter((section) => section.items.length > 0) }; } @@ -595,41 +734,94 @@ async function buildDoramaHub( config: AppConfig, library: Awaited> ): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { + const region = config.preferences.region || 'US'; + const language = config.preferences.language || 'en-US'; + const recentWindowDays = 365; + const providerFilter = `watch_region=${encodeURIComponent(region)}&with_watch_providers=${DORAMA_PROVIDERS}`; + const doramaFilter = `include_adult=false&with_original_language=ko&language=${encodeURIComponent(language)}`; + const [ - hero, - trendingSeries, - viki, - disney, - netflix, - popularSeries, - popularMovies, + trendingShows, + trendingMovies, + fallbackTrendingMovies, + allTimePopularShows, + allTimePopularMovies, upcomingSeries, upcomingMovies ] = await Promise.all([ - tmdbResultCards(config, `/discover/tv?include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=${DORAMA_PROVIDERS}&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${daysAgoIso(40)}&include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=${DORAMA_PROVIDERS}&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${daysAgoIso(100)}&include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=344&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${daysAgoIso(150)}&include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=337&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${daysAgoIso(120)}&include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=8&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=${DORAMA_PROVIDERS}&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/movie?include_adult=false&sort_by=popularity.desc&watch_region=US&with_watch_providers=${DORAMA_PROVIDERS}&with_original_language=ko&language=en-US`, 'landscape'), - tmdbResultCards(config, `/discover/tv?first_air_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}&with_original_language=ko&with_watch_providers=${DORAMA_PROVIDERS}`, 'landscape'), - tmdbResultCards(config, `/discover/movie?primary_release_date.gte=${todayIso()}&sort_by=popularity.desc&language=${encodeURIComponent(config.preferences.language)}&with_original_language=ko`, 'landscape') + tmdbPagedResultCards( + config, + `/discover/tv?sort_by=popularity.desc&first_air_date.gte=${daysAgoIso(recentWindowDays)}&first_air_date.lte=${todayIso()}&${providerFilter}&${doramaFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=popularity.desc&primary_release_date.gte=${daysAgoIso(recentWindowDays)}&primary_release_date.lte=${todayIso()}&${providerFilter}&${doramaFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=popularity.desc&${providerFilter}&${doramaFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/tv?sort_by=vote_count.desc&${providerFilter}&${doramaFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=vote_count.desc&${providerFilter}&${doramaFilter}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/tv?sort_by=popularity.desc&first_air_date.gte=${todayIso()}&include_adult=false&with_original_language=ko&language=${encodeURIComponent(language)}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?sort_by=popularity.desc&primary_release_date.gte=${todayIso()}&include_adult=false&with_original_language=ko&language=${encodeURIComponent(language)}`, + 'landscape' + ) ]); + const filter = (items: MediaCard[]) => { + const libraryTmdbIds = new Set(library.allItems.map((item) => Number(item.ProviderIds?.Tmdb)).filter(Boolean)); + const uniqueItems = uniqueCards(items.filter(Boolean)); + return config.preferences.excludeLibraryItems + ? uniqueItems.filter(item => !item.tmdbId || !libraryTmdbIds.has(item.tmdbId)) + : uniqueItems; + }; + + const filteredTrendingShows = filter(trendingShows || []); + const filteredTrendingMovies = uniqueCards([ + ...filter(trendingMovies || []), + ...filter(fallbackTrendingMovies || []) + ]).slice(0, 12); + const filteredAllTimePopular = uniqueCards([ + ...filter(allTimePopularShows || []), + ...filter(allTimePopularMovies || []) + ]); + const filteredUpcoming = uniqueCards([ + ...filter(upcomingSeries || []), + ...filter(upcomingMovies || []) + ]); + const filteredHero = uniqueCards([ + ...filteredTrendingShows, + ...filteredTrendingMovies + ]); + + const sections: HubSection[] = [ + { id: 'dorama-trending-shows', title: 'Trending Shows', style: 'landscape', items: filteredTrendingShows }, + { id: 'dorama-trending-movies', title: 'Trending Movies', style: 'landscape', items: filteredTrendingMovies }, + { id: 'dorama-all-time-popular', title: 'All Time Popular', style: 'landscape', items: filteredAllTimePopular }, + { id: 'dorama-upcoming', title: 'Upcoming', style: 'landscape', items: filteredUpcoming } + ]; + return { - hero: hero.slice(0, 6), - sections: [ - { id: 'continue', title: 'Continue Watching', style: 'landscape', items: library.continueWatching }, - { id: 'dorama-trending', title: 'New & Trending', style: 'landscape', items: trendingSeries }, - { id: 'dorama-viki', title: 'Popular on Viki', style: 'landscape', items: viki }, - { id: 'dorama-disney', title: 'Popular on Disney+', style: 'landscape', items: disney }, - { id: 'dorama-netflix', title: 'Popular on Netflix', style: 'landscape', items: netflix }, - { id: 'dorama-popular-series', title: 'Popular Series', style: 'landscape', items: popularSeries }, - { id: 'dorama-popular-movies', title: 'Popular Movies', style: 'landscape', items: popularMovies }, - { id: 'dorama-upcoming-series', title: 'Upcoming Series', style: 'landscape', items: upcomingSeries }, - { id: 'dorama-upcoming-movies', title: 'Upcoming Movies', style: 'landscape', items: upcomingMovies } - ] + hero: filteredHero.slice(0, 6), + sections: sections.filter((section) => section.items.length > 0) }; } @@ -640,15 +832,105 @@ async function buildLibraryHub( const downloads = await getDownloads(config); return { - hero: [...library.continueWatching, ...library.recentlyAdded].slice(0, 6), + hero: [...(library.continueWatching || []), ...(library.recentlyAdded || [])].slice(0, 6), sections: [ - { id: 'continue', title: 'Continue Watching', style: 'landscape', items: library.continueWatching }, - { id: 'recent', title: 'Recently Added', style: 'landscape', items: library.recentlyAdded }, - { id: 'downloads', title: 'Downloading', style: 'episode', items: downloads.map(downloadToCard) } + { id: 'recent', title: 'Recently Added', style: 'landscape', items: library.recentlyAdded || [] }, + { id: 'downloads', title: 'Downloading', style: 'episode', items: (downloads || []).map(downloadToCard) } ] }; } +async function buildNetworkHub( + config: AppConfig, + _library: Awaited>, + networkId: number, + title: string +): Promise<{ hero: MediaCard[]; sections: HubSection[] }> { + const region = 'US'; + const language = config.preferences.language || 'en-US'; + const providerIdsByNetworkId: Record = { + 213: [8, 175, 459, 1796], + 49: [27, 31, 118, 384, 425, 616, 1825, 1899], + 2739: [337, 390, 377, 508], + 1024: [9, 10, 119], + 453: [15], + 1595: [344], + 2552: [2, 350], + 344: [350] + }; + const providerIdList = providerIdsByNetworkId[networkId] || [networkId]; + const providerIds = providerIdList.join('|'); + const providerFilter = `with_watch_providers=${providerIds}&watch_region=${encodeURIComponent(region)}&with_watch_monetization_types=flatrate`; + const tvFilter = [1024, 2739].includes(networkId) + ? `with_networks=${networkId}` + : providerFilter; + const recentTvWindowDays = 365; + const recentMovieWindowDays = 365; + + console.log(`[buildNetworkHub] Building hub for ${title} (networkId: ${networkId}, providerIds: ${providerIds}, region: ${region})`); + + const [ + recentPopularShows, + recentPopularMovies, + fallbackPopularMovies, + allTimePopularShows, + allTimePopularMovies + ] = await Promise.all([ + tmdbPagedResultCards( + config, + `/discover/tv?include_adult=false&sort_by=popularity.desc&first_air_date.gte=${daysAgoIso(recentTvWindowDays)}&first_air_date.lte=${todayIso()}&${tvFilter}&language=${encodeURIComponent(language)}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?include_adult=false&sort_by=popularity.desc&primary_release_date.gte=${daysAgoIso(recentMovieWindowDays)}&primary_release_date.lte=${todayIso()}&${providerFilter}&language=${encodeURIComponent(language)}`, + 'landscape' + ), + networkId === 2739 + ? tmdbPagedResultCards( + config, + `/discover/movie?include_adult=false&sort_by=popularity.desc&${providerFilter}&language=${encodeURIComponent(language)}`, + 'landscape' + ) + : Promise.resolve([]), + tmdbPagedResultCards( + config, + `/discover/tv?include_adult=false&sort_by=vote_count.desc&${tvFilter}&language=${encodeURIComponent(language)}`, + 'landscape' + ), + tmdbPagedResultCards( + config, + `/discover/movie?include_adult=false&sort_by=vote_count.desc&${providerFilter}&language=${encodeURIComponent(language)}`, + 'landscape' + ) + ]); + const filter = (items: MediaCard[]) => uniqueCards(items.filter(Boolean)); + const filteredRecentPopularShows = filter(recentPopularShows); + const filteredRecentPopularMovies = networkId === 2739 + ? uniqueCards([ + ...filter(recentPopularMovies), + ...filter(fallbackPopularMovies) + ]).slice(0, 12) + : filter(recentPopularMovies); + const filteredAllTimePopular = uniqueCards([ + ...filter(allTimePopularShows), + ...filter(allTimePopularMovies) + ]); + const hero = uniqueCards([ + ...filteredRecentPopularShows, + ...filteredRecentPopularMovies + ]).slice(0, 6); + + const sectionCandidates: HubSection[] = [ + { id: 'network-trending-shows', title: `Trending Shows on ${title}`, style: 'landscape', items: filteredRecentPopularShows }, + { id: 'network-trending-movies', title: `Trending Movies on ${title}`, style: 'landscape', items: filteredRecentPopularMovies }, + { id: 'network-all-time-popular', title: `All Time Popular on ${title}`, style: 'landscape', items: filteredAllTimePopular } + ]; + const sections = sectionCandidates.filter((section) => section.items.length > 0); + + return { hero, sections }; +} + async function getTmdbSnapshot(config: AppConfig): Promise<{ hero: MediaCard[]; recommendations: MediaCard[]; @@ -1004,14 +1286,20 @@ async function jellyfinFetch(config: AppConfig, pathWithQuery: string): Promi async function tmdbFetch(config: AppConfig, pathWithQuery: string): Promise | null> { const token = getTmdbToken(config); if (!token) { + console.warn('TMDb token is missing'); return null; } - return fetchJson>(`https://api.themoviedb.org/3${pathWithQuery}`, { - headers: { - Authorization: `Bearer ${token}` - } - }); + try { + return await fetchJson>(`https://api.themoviedb.org/3${pathWithQuery}`, { + headers: { + Authorization: `Bearer ${token}` + } + }); + } catch (err) { + console.error(`TMDb fetch failed for ${pathWithQuery}:`, err); + return null; + } } async function loginQbit(config: AppConfig): Promise { @@ -1066,18 +1354,25 @@ async function fetchJson(url: string, init?: RequestInit): Promise { } } -function jellyfinToCard(item: JellyfinItem, fallbackTitle: string): MediaCard | null { +function jellyfinToCard( + item: JellyfinItem, + fallbackTitle: string, + tmdbIdByItemId?: Map +): MediaCard | null { if (!item.Id) { return null; } const posterTag = item.ImageTags?.Primary || ''; - const backdropTag = item.BackdropImageTags?.[0] || posterTag; + const backdropItemId = item.ParentBackdropItemId || item.Id; + const backdropTag = item.ParentBackdropImageTags?.[0] || item.BackdropImageTags?.[0] || posterTag; const progress = Math.round(item.UserData?.PlayedPercentage || 0); + const tmdbId = Number(item.ProviderIds?.Tmdb) || (item.SeriesId ? tmdbIdByItemId?.get(item.SeriesId) : undefined); + const episodeCode = formatEpisodeCode(item.ParentIndexNumber, item.IndexNumber); return { id: `jellyfin-${item.Id}`, - tmdbId: Number(item.ProviderIds?.Tmdb) || undefined, + tmdbId, providerId: item.Id, title: fallbackTitle, subtitle: item.Type === 'Episode' @@ -1088,10 +1383,15 @@ function jellyfinToCard(item: JellyfinItem, fallbackTitle: string): MediaCard | overview: item.Overview || '', mediaType: item.Type === 'Movie' ? 'movie' : item.Type === 'Episode' ? 'episode' : 'series', posterUrl: `/api/assets/jellyfin/${item.Id}?kind=Primary&maxWidth=480&tag=${encodeURIComponent(posterTag)}`, - backdropUrl: `/api/assets/jellyfin/${item.Id}?kind=Backdrop&maxWidth=1280&tag=${encodeURIComponent(backdropTag)}`, + backdropUrl: `/api/assets/jellyfin/${backdropItemId}?kind=Backdrop&maxWidth=1280&tag=${encodeURIComponent(backdropTag)}`, badge: item.Type || 'Jellyfin', progress: progress > 0 ? progress : undefined, - secondaryValue: item.UserData?.Played ? 'Watched' : undefined + secondaryValue: item.UserData?.Played ? 'Watched' : undefined, + hoverLabel: item.Type === 'Movie' + ? formatPlaybackTime(item.UserData?.PlaybackPositionTicks) + : item.Type === 'Episode' && episodeCode + ? `${item.UserData?.PlaybackPositionTicks ? 'Current' : 'Next'} ${episodeCode}` + : undefined }; } @@ -1100,7 +1400,11 @@ function tmdbToCard(item: Record, mediaType: 'movie' | 'tv'): M const id = Number(item.id || 0); const posterPath = String(item.poster_path || ''); const backdropPath = String(item.backdrop_path || ''); - const year = String(item.release_date || item.first_air_date || '').slice(0, 4); + const releaseDate = String(item.release_date || item.first_air_date || ''); + const firstAirDate = mediaType === 'tv' ? String(item.first_air_date || '') : ''; + const genreIds = asArray(item.genre_ids).map((value) => Number(value)).filter(Boolean); + const originalLanguage = String(item.original_language || ''); + const year = releaseDate.slice(0, 4); return { id: `tmdb-${mediaType}-${id}`, @@ -1110,9 +1414,16 @@ function tmdbToCard(item: Record, mediaType: 'movie' | 'tv'): M overview: String(item.overview || ''), mediaType, posterUrl: posterPath ? `${TMDB_IMAGE}/w500${posterPath}` : '', - backdropUrl: backdropPath ? `${TMDB_IMAGE}/w1280${backdropPath}` : '', + backdropUrl: backdropPath ? `${TMDB_IMAGE}/original${backdropPath}` : '', badge: mediaType === 'movie' ? 'Radarr' : 'Sonarr', - actionLabel: mediaType === 'movie' ? 'Add to Radarr' : 'Add to Sonarr' + actionLabel: mediaType === 'movie' ? 'Add to Radarr' : 'Add to Sonarr', + popularity: Number(item.popularity || 0) || undefined, + voteAverage: Number(item.vote_average || 0) || undefined, + voteCount: Number(item.vote_count || 0) || undefined, + originalLanguage: originalLanguage || undefined, + releaseDate: releaseDate || undefined, + firstAirDate: firstAirDate || undefined, + genreIds: genreIds.length ? genreIds : undefined }; } @@ -1125,13 +1436,24 @@ function customCard(partial: Partial & Pick { try { const result = await tmdbFetch(config, pathWithQuery); - return asArray(result?.results) + if (!result || !result.results || (Array.isArray(result.results) && result.results.length === 0)) { + console.warn(`TMDb returned no results for ${pathWithQuery}`); + // Do not broaden provider-scoped discover queries. Upcoming provider rows can become + // cross-platform noise if watch_region is stripped and TMDb stops honoring the provider. + if ( + pathWithQuery.includes('/discover/') && + pathWithQuery.includes('watch_region') && + !pathWithQuery.includes('with_watch_providers=') + ) { + const fallbackPath = pathWithQuery.replace(/&watch_region=[^&]*/, ''); + if (fallbackPath !== pathWithQuery) { + console.log(`[tmdbResultCards] Retrying TMDb without region filter: ${fallbackPath}`); + return tmdbResultCards(config, fallbackPath, style); + } + } + return []; + } + const cards = asArray(result?.results) + .map((item) => tmdbToCard(asRecord(item), inferMediaType(pathWithQuery, asRecord(item)))) + .filter((card) => (style === 'landscape' ? Boolean(card.backdropUrl) : Boolean(card.posterUrl))) + .slice(0, 18); + + if (cards.length === 0 && asArray(result?.results).length > 0) { + console.log(`TMDb results filtered out by style (${style}), retrying without style filter`); + const allCards = asArray(result?.results) .map((item) => tmdbToCard(asRecord(item), inferMediaType(pathWithQuery, asRecord(item)))) - .filter((card) => style === 'landscape' ? Boolean(card.backdropUrl) : Boolean(card.posterUrl)) .slice(0, 18); - } catch { + console.log(`TMDb fetched ${allCards.length} cards (fallback) for ${pathWithQuery}`); + return allCards; + } + + console.log(`TMDb fetched ${cards.length} cards for ${pathWithQuery}`); + return cards; + } catch (err) { + console.error(`Error fetching TMDb cards from ${pathWithQuery}:`, err); return []; } } -async function tmdbPeopleCards(config: AppConfig, pathWithQuery: string): Promise { - try { - const result = await tmdbFetch(config, pathWithQuery); - return asArray(result?.results) - .map((item) => { - const person = asRecord(item); - const profilePath = String(person.profile_path || ''); - return customCard({ - id: `person-${person.id || ''}`, - tmdbId: Number(person.id || 0) || undefined, - title: String(person.name || 'Person'), - subtitle: String(person.known_for_department || ''), - mediaType: 'mixed', - posterUrl: profilePath ? `${TMDB_IMAGE}/w342${profilePath}` : '', - backdropUrl: profilePath ? `${TMDB_IMAGE}/w342${profilePath}` : '', - badge: 'TMDb' - }); - }) - .filter((card) => Boolean(card.posterUrl)) - .slice(0, 18); - } catch { - return []; - } -} +async function tmdbPagedResultCards( + config: AppConfig, + pathWithQuery: string, + style: HubSection['style'], + pageCount = 3 +): Promise { + const paths = Array.from({ length: pageCount }, (_, index) => { + const page = index + 1; + return `${pathWithQuery}${pathWithQuery.includes('?') ? '&' : '?'}page=${page}`; + }); -function genreCards(): MediaCard[] { - return GENRE_ASSETS.map((genre) => - customCard({ - id: `genre-${genre.id}`, - title: genre.title, - subtitle: 'Genre', - mediaType: 'mixed', - posterUrl: genre.posterUrl, - backdropUrl: genre.posterUrl, - badge: 'TMDb' - }) - ); -} - -function networkCards(): MediaCard[] { - return NETWORK_ASSETS.map((network) => - customCard({ - id: `network-${network.id}`, - title: network.title, - subtitle: 'Network', - mediaType: 'mixed', - posterUrl: network.posterUrl, - backdropUrl: network.posterUrl, - badge: 'TV' - }) - ); + const pages = await Promise.all(paths.map((path) => tmdbResultCards(config, path, style))); + return uniqueCards(pages.flat()).slice(0, 36); } function downloadToCard(download: DownloadItem): MediaCard { @@ -1229,6 +1543,174 @@ function inferMediaType(pathWithQuery: string, item: Record): ' return pathWithQuery.includes('/movie') ? 'movie' : 'tv'; } +function uniqueCards(items: MediaCard[]): MediaCard[] { + const seen = new Set(); + return items.filter((item) => { + if (seen.has(item.id)) { + return false; + } + + seen.add(item.id); + return true; + }); +} + +// Match TMDb's English backdrop tab for landscape cards where available. +async function applyHighResBackdropsToSections( + config: AppConfig, + sections: HubSection[], + backdropCache: Map>, + preferredLanguage?: string | null +): Promise { + return Promise.all( + sections.map(async (section) => { + if (section.style !== 'landscape') { + return section; + } + + const items = await applyHighResBackdropsToCards( + config, + section.items, + shouldUseHighResBackdropForCard, + backdropCache, + preferredLanguage + ); + + return { + ...section, + items + }; + }) + ); +} + +async function applyHighResBackdropsToCards( + config: AppConfig, + cards: MediaCard[], + shouldApply: (card: MediaCard) => boolean, + backdropCache: Map>, + preferredLanguage?: string | null +): Promise { + return Promise.all( + cards.map(async (card) => { + if (!shouldApply(card)) { + return card; + } + + const mediaType: 'movie' | 'tv' = card.mediaType === 'movie' ? 'movie' : 'tv'; + const cacheKey = `${mediaType}:${card.tmdbId}:${preferredLanguage || 'any'}`; + let backdropPromise = backdropCache.get(cacheKey); + if (!backdropPromise) { + backdropPromise = getTmdbHighResBackdrop(config, card.tmdbId!, mediaType, preferredLanguage); + backdropCache.set(cacheKey, backdropPromise); + } + + const backdropUrl = await backdropPromise; + return backdropUrl + ? { + ...card, + backdropUrl + } + : card; + }) + ); +} + +function shouldUseHighResBackdropForCard(card: MediaCard): boolean { + return Boolean( + card.tmdbId + && ( + card.mediaType === 'movie' + || card.mediaType === 'tv' + || card.mediaType === 'series' + || card.mediaType === 'episode' + ) + ); +} + +function tmdbImagesPath(tmdbId: number, mediaType: 'movie' | 'tv'): string { + return `/${mediaType}/${tmdbId}/images?include_image_language=en,en-US,null`; +} + +function formatPlaybackTime(playbackPositionTicks?: number): string | undefined { + if (!playbackPositionTicks || playbackPositionTicks <= 0) { + return undefined; + } + + const totalSeconds = Math.floor(playbackPositionTicks / 10_000_000); + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + + return hours > 0 + ? `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` + : `${minutes}:${String(seconds).padStart(2, '0')}`; +} + +export async function getTmdbLogos( + config: AppConfig, + tmdbId: number, + mediaType: 'movie' | 'tv' +): Promise> { + try { + const response = await tmdbFetch( + config, + tmdbImagesPath(tmdbId, mediaType) + ); + const logos = asArray(response?.logos) + .map((entry) => asRecord(entry)) + .filter((entry) => typeof entry.file_path === 'string' && entry.file_path) + .map((entry) => ({ + file_path: String(entry.file_path), + iso_639_1: typeof entry.iso_639_1 === 'string' ? entry.iso_639_1 : null + })); + return logos; + } catch { + return []; + } +} + +async function getTmdbHighResBackdrop( + config: AppConfig, + tmdbId: number, + mediaType: 'movie' | 'tv', + preferredLanguage?: string | null +): Promise { + try { + const response = await tmdbFetch(config, tmdbImagesPath(tmdbId, mediaType)); + let backdrops = asArray(response?.backdrops) + .map((entry) => asRecord(entry)); + + if (backdrops.length === 0) { + return ''; + } + + // Filter by language if requested + if (preferredLanguage) { + const filtered = backdrops.filter( + (b) => String(b.iso_639_1) === preferredLanguage + ); + if (filtered.length > 0) { + backdrops = filtered; + } + } + + // Sort by width descending if no language preference (Carousel use case) + if (!preferredLanguage) { + backdrops.sort((a, b) => Number(b.width || 0) - Number(a.width || 0)); + } + + // The first one is the first available one (after language filter and/or sorting) + const selectedBackdrop = backdrops.find( + (entry) => typeof entry.file_path === 'string' && entry.file_path + ); + + return selectedBackdrop?.file_path ? `${TMDB_IMAGE}/original${String(selectedBackdrop.file_path)}` : ''; + } catch { + return ''; + } +} + function todayIso(): string { return new Date().toISOString().slice(0, 10); } diff --git a/shared/contracts.ts b/shared/contracts.ts index 1717265..eb58fcb 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -3,6 +3,11 @@ export type AppRoute = | 'home' | 'anime' | 'dorama' + | 'netflix' + | 'primevideo' + | 'hbo' + | 'viki' + | 'disney' | 'library' | 'downloads' | 'settings'; @@ -89,11 +94,23 @@ export interface MediaCard { mediaType: 'movie' | 'tv' | 'episode' | 'series' | 'mixed'; posterUrl: string; backdropUrl: string; + logoUrl?: string; badge?: string; progress?: number; secondaryValue?: string; + hoverLabel?: string; actionLabel?: string; accent?: string; + popularity?: number; + voteAverage?: number; + voteCount?: number; + originalLanguage?: string; + releaseDate?: string; + firstAirDate?: string; + lastAirDate?: string; + seasonCount?: number; + mediaStatus?: string; + genreIds?: number[]; } export interface DownloadItem { @@ -126,7 +143,7 @@ export interface HubSection { } export interface HubPageResponse { - page: 'stream' | 'home' | 'anime' | 'dorama' | 'library'; + page: 'stream' | 'home' | 'anime' | 'dorama' | 'netflix' | 'primevideo' | 'hbo' | 'viki' | 'disney' | 'library'; hero: MediaCard[]; continueWatching?: MediaCard[]; sections: HubSection[]; diff --git a/src/App.tsx b/src/App.tsx index f3b9932..d95bbab 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -29,6 +29,14 @@ const sidebarItems: Array<{ route: AppRoute; label: string; short: string }> = [ { route: 'downloads', label: 'Downloads', short: 'D' }, ] +const networkSidebarItems: Array<{ route: AppRoute; label: string; icon: string; iconClassName?: string }> = [ + { route: 'netflix', label: 'Netflix', icon: '/networks/netflix.png' }, + { route: 'primevideo', label: 'Prime Video', icon: '/networks/prime.svg' }, + { route: 'hbo', label: 'HBO', icon: '/networks/hbo.svg', iconClassName: 'sidebar-network-icon-image white-network-icon' }, + { route: 'viki', label: 'Viki', icon: '/networks/viki.png' }, + { route: 'disney', label: 'Disney+', icon: '/networks/disney.webp' }, +] + function App() { const [authState, setAuthState] = useState('loading') const [entryStage, setEntryStage] = useState('profiles') @@ -67,15 +75,19 @@ function App() { setEntryStage(resolveEntryStage(settings, serviceOptions)) } - async function loadHub(page: HubPageResponse['page']) { - setHubLoading(true) + async function loadHub(page: HubPageResponse['page'], options?: { silent?: boolean }) { + if (!options?.silent) { + setHubLoading(true) + } try { const hub = await api.getHub(page) setHubPages((current) => ({ ...current, [page]: hub })) } catch (loadError) { setError(loadError instanceof Error ? loadError.message : 'Failed to load this section.') } finally { - setHubLoading(false) + if (!options?.silent) { + setHubLoading(false) + } } } @@ -126,6 +138,7 @@ function App() { const page = route as HubPageResponse['page'] let cancelled = false + setHubLoading(true) void api.getHub(page) .then((hub) => { @@ -154,7 +167,7 @@ function App() { const interval = window.setInterval(() => { void refreshBaseData() if (route !== 'downloads' && route !== 'settings') { - void loadHub(route as HubPageResponse['page']) + void loadHub(route as HubPageResponse['page'], { silent: true }) } }, 30000) @@ -255,7 +268,7 @@ function App() { await api.requestSeries(card.tmdbId) } if (route !== 'downloads' && route !== 'settings') { - await loadHub(route as HubPageResponse['page']) + await loadHub(route as HubPageResponse['page'], { silent: true }) } setNotice(`${card.title} sent to ${card.mediaType === 'movie' ? 'Radarr' : 'Sonarr'}.`) } catch (requestError) { @@ -351,6 +364,7 @@ function App() { ) : null} @@ -392,6 +407,8 @@ function Sidebar(props: { busy: boolean onExitProfile: () => void }) { + const hasServiceFailure = props.connections.some((connection) => !connection.ok) + return (