diff --git a/server/index.ts b/server/index.ts index 34d0715..4a16eec 100644 --- a/server/index.ts +++ b/server/index.ts @@ -19,6 +19,7 @@ import { getDashboard, getDownloads, getHubPage, + searchTitles, getTitleDetails, getTmdbLogos, deleteSeasonFiles, @@ -237,6 +238,13 @@ async function routeRequest(request: IncomingMessage, response: ServerResponse): return; } + if (url.pathname === '/api/search' && method === 'GET') { + const config = await readConfig(session!.encryptionKey); + const query = String(url.searchParams.get('query') || ''); + sendJson(response, 200, await searchTitles(config, query)); + return; + } + if (url.pathname === '/api/title-details' && method === 'POST') { const config = await readConfig(session!.encryptionKey); const body = await readJson(request); diff --git a/server/lib/services.ts b/server/lib/services.ts index dce4fb4..d7eff25 100644 --- a/server/lib/services.ts +++ b/server/lib/services.ts @@ -129,6 +129,11 @@ interface DownloadMetadataHint { subtitle?: string; } +interface TmdbBackdropChoice { + url: string; + backdropLanguageFallback: boolean; +} + interface SonarrSeriesRecord { id?: number; title?: string; @@ -333,7 +338,7 @@ export async function getHubPage( return getHubPage(config, 'home'); } - const backdropCache = new Map>(); + const backdropCache = new Map>(); const networkScopedContinueWatching = isNetworkPage ? (() => { const sectionTmdbIds = new Set( @@ -369,13 +374,15 @@ export async function getHubPage( 'en' ) ]); + const continueWatchingWithLogos = await applyTitleLogosToCards(config, continueWatching || []); const heroWithLogos = await applyTitleLogosToCards(config, heroWithHighResBackdrops || []); + const sectionsWithLogos = await applyTitleLogosToSections(config, sectionsWithHighResBackdrops || []); return { page, hero: heroWithLogos, - continueWatching, - sections: (sectionsWithHighResBackdrops || []) + continueWatching: continueWatchingWithLogos, + sections: sectionsWithLogos .filter((section) => section.items.some((item) => item.backdropUrl || item.posterUrl)) .concat( page === 'library' && downloads.length @@ -460,7 +467,7 @@ export async function getCalendar(config: AppConfig): Promise const allItems = [...sonarrItems, ...radarrItems] .filter((item): item is CalendarEntry => Boolean(item)); - const backdropCache = new Map>(); + const backdropCache = new Map>(); const cards = await applyHighResBackdropsToCards(config, allItems.map(i => i.card), shouldUseHighResBackdropForCard, backdropCache, 'en'); const itemsWithBackdrops = allItems.map(item => { @@ -481,6 +488,73 @@ export async function getCalendar(config: AppConfig): Promise } } +export async function searchTitles( + config: AppConfig, + rawQuery: string +): Promise<{ query: string; items: MediaCard[] }> { + const query = rawQuery.trim(); + if (!query) { + return { query: '', items: [] }; + } + + const library = await getLibrarySnapshot(config); + const libraryCards = library.allItems + .map((item) => jellyfinToCard(item, item.Name || 'Library')) + .filter(Boolean) as MediaCard[]; + const normalizedQuery = normalizeSearchValue(query); + const libraryMatches = libraryCards.filter((card) => { + const haystack = normalizeSearchValue([card.title, card.subtitle].filter(Boolean).join(' ')); + return haystack.includes(normalizedQuery); + }); + + const libraryCardByTmdbId = new Map( + libraryCards + .filter((card) => card.tmdbId) + .map((card) => [card.tmdbId!, card] as const) + ); + + const remoteResults = await tmdbFetch( + config, + `/search/multi?query=${encodeURIComponent(query)}&language=${encodeURIComponent(config.preferences.language)}&include_adult=false` + ); + + const remoteCards = asArray(remoteResults?.results) + .map((entry) => asRecord(entry)) + .filter((entry) => entry.media_type === 'movie' || entry.media_type === 'tv') + .map((entry) => { + const mediaType = entry.media_type === 'movie' ? 'movie' : 'tv'; + const card = tmdbToCard(entry, mediaType); + const libraryMatch = card.tmdbId ? libraryCardByTmdbId.get(card.tmdbId) : undefined; + return libraryMatch + ? { + ...card, + providerId: libraryMatch.providerId, + badge: libraryMatch.badge, + progress: libraryMatch.progress, + secondaryValue: libraryMatch.secondaryValue, + hoverLabel: libraryMatch.hoverLabel + } + : card; + }); + + const searchBackdropCache = new Map>(); + const enrichedCards = await applyTitleLogosToCards( + config, + await applyHighResBackdropsToCards( + config, + uniqueSearchCards([...libraryMatches, ...remoteCards]).slice(0, 36), + shouldUseHighResBackdropForCard, + searchBackdropCache, + 'en' + ) + ); + + return { + query, + items: enrichedCards.filter((card) => Boolean(card.backdropUrl)) + }; +} + export async function removeDownload(config: AppConfig, id: string): Promise { const [source, rawId] = id.split('-', 2); if (!source || !rawId) { @@ -1777,7 +1851,7 @@ async function getLibrarySnapshot(config: AppConfig): Promise<{ 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` + `/Users/${config.jellyfin.userId}/Items?recursive=true&includeItemTypes=Movie,Series&hasTmdbId=true&fields=ProviderIds,DateCreated,DateLastMediaAdded,Overview,ImageTags,BackdropImageTags,ProductionYear` ) ]); } catch { @@ -2741,6 +2815,7 @@ function customCard(partial: Partial & Pick(); + return items.filter((item) => { + const key = item.tmdbId + ? `tmdb:${item.tmdbId}` + : item.providerId + ? `provider:${item.providerId}` + : item.id; + if (seen.has(key)) { + return false; + } + + seen.add(key); + return true; + }); +} + +function normalizeSearchValue(value: string): string { + return value + .normalize('NFKD') + .replace(/[\u0300-\u036f]/g, '') + .toLowerCase(); +} + // Match TMDb's English backdrop tab for landscape cards where available. async function applyHighResBackdropsToSections( config: AppConfig, sections: HubSection[], - backdropCache: Map>, + backdropCache: Map>, preferredLanguage?: string | null ): Promise { return Promise.all( @@ -2888,11 +2987,31 @@ async function applyHighResBackdropsToSections( ); } +async function applyTitleLogosToSections( + config: AppConfig, + sections: HubSection[] +): Promise { + return Promise.all( + sections.map(async (section) => { + if (section.style !== 'landscape') { + return section; + } + + const items = await applyTitleLogosToCards(config, section.items); + + return { + ...section, + items + }; + }) + ); +} + async function applyHighResBackdropsToCards( config: AppConfig, cards: MediaCard[], shouldApply: (card: MediaCard) => boolean, - backdropCache: Map>, + backdropCache: Map>, preferredLanguage?: string | null ): Promise { return Promise.all( @@ -2905,15 +3024,16 @@ async function applyHighResBackdropsToCards( const cacheKey = `${mediaType}:${card.tmdbId}:${preferredLanguage || 'any'}:${card.originalLanguage || 'none'}`; let backdropPromise = backdropCache.get(cacheKey); if (!backdropPromise) { - backdropPromise = getTmdbHighResBackdrop(config, card.tmdbId!, mediaType, preferredLanguage, card.originalLanguage); + backdropPromise = getTmdbHighResBackdropChoice(config, card.tmdbId!, mediaType, preferredLanguage, card.originalLanguage); backdropCache.set(cacheKey, backdropPromise); } - const backdropUrl = await backdropPromise; - return backdropUrl + const backdropChoice = await backdropPromise; + return backdropChoice.url ? { ...card, - backdropUrl + backdropUrl: backdropChoice.url, + backdropLanguageFallback: backdropChoice.backdropLanguageFallback } : card; }) @@ -3032,13 +3152,24 @@ async function getTmdbHighResBackdrop( preferredLanguage?: string | null, originalLanguage?: string | null ): Promise { + const choice = await getTmdbHighResBackdropChoice(config, tmdbId, mediaType, preferredLanguage, originalLanguage); + return choice.url; +} + +async function getTmdbHighResBackdropChoice( + config: AppConfig, + tmdbId: number, + mediaType: 'movie' | 'tv', + preferredLanguage?: string | null, + originalLanguage?: string | null +): Promise<{ url: string; backdropLanguageFallback: boolean }> { try { const response = await tmdbFetch(config, tmdbBackdropImagesPath(tmdbId, mediaType)); let backdrops = asArray(response?.backdrops) .map((entry) => asRecord(entry)); if (backdrops.length === 0) { - return ''; + return { url: '', backdropLanguageFallback: false }; } const sortByWidthDesc = (items: Record[]) => @@ -3083,9 +3214,14 @@ async function getTmdbHighResBackdrop( (entry) => typeof entry.file_path === 'string' && entry.file_path ); - return selectedBackdrop?.file_path ? `${TMDB_IMAGE}/original${String(selectedBackdrop.file_path)}` : ''; + return selectedBackdrop?.file_path + ? { + url: `${TMDB_IMAGE}/original${String(selectedBackdrop.file_path)}`, + backdropLanguageFallback: preferredLanguage === 'en' && selectedBackdrop.iso_639_1 == null + } + : { url: '', backdropLanguageFallback: false }; } catch { - return ''; + return { url: '', backdropLanguageFallback: false }; } } diff --git a/shared/contracts.ts b/shared/contracts.ts index 4446c6b..5e1b017 100644 --- a/shared/contracts.ts +++ b/shared/contracts.ts @@ -1,6 +1,7 @@ export type AppRoute = | 'stream' | 'home' + | 'search' | 'anime' | 'dorama' | 'netflix' @@ -90,6 +91,7 @@ export interface MediaCard { posterUrl: string; backdropUrl: string; logoUrl?: string; + backdropLanguageFallback?: boolean; badge?: string; progress?: number; secondaryValue?: string; @@ -207,6 +209,11 @@ export interface CalendarResponse { items: CalendarEntry[]; } +export interface SearchResponse { + query: string; + items: MediaCard[]; +} + export interface DashboardResponse { connections: ConnectionStatus[]; hero: MediaCard[]; diff --git a/src/App.tsx b/src/App.tsx index 4184a8f..0d556ca 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -19,6 +19,7 @@ import { type DownloadItem, type HubPageResponse, type MediaCard, + type SearchResponse, type SelectOption, type ServiceOptionsResponse, type TitleDetailsCastMember, @@ -36,8 +37,9 @@ const EPISODE_SCROLL_DISTANCE_RATIO = 0.72 const SEASON_DOMINANCE_SWITCH_RATIO = 0.12 const SEASON_DOMINANCE_SWITCH_MIN_PX = 56 -const sidebarItems: Array<{ route: AppRoute; label: string; short: string; icon?: 'calendar' }> = [ +const sidebarItems: Array<{ route: AppRoute; label: string; short: string; icon?: 'calendar' | 'search'; iconClassName?: string }> = [ { route: 'home', label: 'Inicio', short: 'H' }, + { route: 'search', label: 'Search', short: 'S', icon: 'search', iconClassName: 'sidebar-search-icon' }, { route: 'dorama', label: 'K-Drama', short: 'K' }, { route: 'anime', label: 'Anime', short: 'A' }, { route: 'library', label: 'Library', short: 'L' }, @@ -77,6 +79,10 @@ function App() { const [hubLoading, setHubLoading] = useState(false) const [calendarItems, setCalendarItems] = useState([]) const [calendarLoading, setCalendarLoading] = useState(false) + const [searchQuery, setSearchQuery] = useState('') + const [searchResults, setSearchResults] = useState([]) + const [searchLoading, setSearchLoading] = useState(false) + const [lastSearchQuery, setLastSearchQuery] = useState('') const [selectedCard, setSelectedCard] = useState(null) const [downloadDeleteId, setDownloadDeleteId] = useState('') const [entryTransitionState, setEntryTransitionState] = useState('idle') @@ -190,7 +196,7 @@ function App() { return } - if (route === 'downloads' || route === 'settings' || route === 'calendar') { + if (route === 'downloads' || route === 'settings' || route === 'calendar' || route === 'search') { return } @@ -234,7 +240,7 @@ function App() { void refreshBaseData() if (route === 'calendar') { void loadCalendar({ silent: true }) - } else if (route !== 'downloads' && route !== 'settings') { + } else if (route !== 'downloads' && route !== 'settings' && route !== 'search') { void loadHub(route as HubPageResponse['page'], { silent: true }) } }, 30000) @@ -338,7 +344,7 @@ function App() { } if (route === 'calendar') { await loadCalendar({ silent: true }) - } else if (route !== 'downloads' && route !== 'settings') { + } else if (route !== 'downloads' && route !== 'settings' && route !== 'search') { await loadHub(route as HubPageResponse['page'], { silent: true }) } setNotice(`${card.title} sent to ${card.mediaType === 'movie' ? 'Radarr' : 'Sonarr'}.`) @@ -365,6 +371,29 @@ function App() { } } + async function handleSearchSubmit(query: string) { + const trimmedQuery = query.trim() + setSearchQuery(query) + setError('') + + if (!trimmedQuery) { + setLastSearchQuery('') + setSearchResults([]) + return + } + + setSearchLoading(true) + try { + const response = await api.searchTitles(trimmedQuery) + setSearchResults(response.items) + setLastSearchQuery(response.query) + } catch (searchError) { + setError(searchError instanceof Error ? searchError.message : 'Failed to search the catalog.') + } finally { + setSearchLoading(false) + } + } + function updateConfig(key: K, value: AppConfig[K]) { setConfig((current) => ({ ...current, @@ -427,7 +456,7 @@ function App() { const currentJellyfinUser = options.jellyfinUsers.find((option) => option.id === config.jellyfin.userId)?.label || 'Media cockpit' - const currentHub = route !== 'downloads' && route !== 'settings' && route !== 'calendar' ? hubPages[route as HubPageResponse['page']] : undefined + const currentHub = route !== 'downloads' && route !== 'settings' && route !== 'calendar' && route !== 'search' ? hubPages[route as HubPageResponse['page']] : undefined return (
@@ -450,6 +479,17 @@ function App() { {route === 'calendar' ? setSelectedCard({ card, originRect: originRect ?? null })} /> : null} {route === 'downloads' ? : null} + {route === 'search' ? ( + setSelectedCard({ card, originRect: originRect ?? null })} + onSearch={handleSearchSubmit} + query={searchQuery} + results={searchResults} + submittedQuery={lastSearchQuery} + updateQuery={setSearchQuery} + /> + ) : null} {route === 'settings' ? ( ) : null} - {route !== 'downloads' && route !== 'settings' && route !== 'calendar' ? ( + {route !== 'downloads' && route !== 'settings' && route !== 'calendar' && route !== 'search' ? ( startTransition(() => props.setRoute(item.route))} type="button" > -