From ce9b9cb2b1e3b032fd6c09fd540dd5a4a417e54d Mon Sep 17 00:00:00 2001 From: Ncbudd Date: Fri, 27 Nov 2026 22:20:00 -0500 Subject: [PATCH 1/4] feat(search): understand queries, rank results, suggest and stream Search now reads what was typed. "nate standup" is split into a person ("nate") and an intent (stand-up), finds Nate Bargatze through TMDB person search (comedians ranked up), and returns his specials (comedy credits where he plays himself, TMDB keyword 9716, titles with his name) as a top result. The same parser handles " live", " audiobook", " season 3", "2015 horror" and "80s action movies". The query is always still searched as typed; the intent only adds. - searchIntent: tested parser for formats, genres, media types, roles, seasons, years and decades, "X by Y" - searchRanking: typo and prefix tolerant matching ("bargatze", "nate barg", "bergatze"), one 0-100 score per result (text fit, exact title, intent fit, owned, popularity, provider order), results ordered within each media type, cross-provider dedupe - GET /search adds intent, topResult, correctedQuery (did-you-mean when nothing matched), matchScore and failedSources - GET /search/stream answers per provider group as NDJSON, so TMDB results arrive while slow catalogs fill in or time out on their own - GET /search/suggest answers from an in-memory index (library, recent answers, trending) within 120 ms: titles, people, intent queries such as "Nate Bargatze stand-up specials" and spelling corrections - 2-minute cache with in-flight sharing for Bookshelf and ComicVine - searchTiming.bench.ts measures classic, streamed and suggest timings - a person's stand-up top result lists only their own specials: the whole name in the title, or a first-billed "Self" credit (a surname alone matched a relative's special, and guest spots or produced specials slipped in) --- config/i18n/api-message-sources.json | 351 +++++++-- config/i18n/source-snapshot.json | 4 + seerr-api.yml | 207 ++++++ server/api/themoviedb/index.ts | 40 + server/lib/searchIntent.test.ts | 146 ++++ server/lib/searchIntent.ts | 716 ++++++++++++++++++ server/lib/searchIntentResolver.ts | 567 ++++++++++++++ server/lib/searchProviderCache.ts | 72 ++ server/lib/searchRanking.test.ts | 167 +++++ server/lib/searchRanking.ts | 425 +++++++++++ server/lib/searchSuggest.ts | 427 +++++++++++ server/routes/search.test.ts | 4 + server/routes/search.ts | 1019 ++++++++++++++++++++++++-- server/routes/searchSmart.test.ts | 727 ++++++++++++++++++ server/routes/searchTiming.bench.ts | 354 +++++++++ src/i18n/apiMessages.ts | 4 + src/i18n/locale/en.json | 4 + 17 files changed, 5089 insertions(+), 145 deletions(-) create mode 100644 server/lib/searchIntent.test.ts create mode 100644 server/lib/searchIntent.ts create mode 100644 server/lib/searchIntentResolver.ts create mode 100644 server/lib/searchProviderCache.ts create mode 100644 server/lib/searchRanking.test.ts create mode 100644 server/lib/searchRanking.ts create mode 100644 server/lib/searchSuggest.ts create mode 100644 server/routes/searchSmart.test.ts create mode 100644 server/routes/searchTiming.bench.ts diff --git a/config/i18n/api-message-sources.json b/config/i18n/api-message-sources.json index 737b3cce46..7ece1fdf7a 100644 --- a/config/i18n/api-message-sources.json +++ b/config/i18n/api-message-sources.json @@ -1393,6 +1393,25 @@ } ] }, + { + "key": "m059d378dcd252eadde7e", + "id": "utils.ApiMessage.m059d378dcd252eadde7e", + "source": "Unknown group.", + "defaultMessage": "Unknown group.", + "sourceHash": "059d378dcd252eadde7ee37448683c81f0282bc3ec5311a7275442fe08859d37", + "parts": ["Unknown group."], + "parameterCount": 0, + "callsites": [ + { + "path": "server/routes/search.ts", + "line": 2293, + "kind": "authored-message-field", + "field": "message", + "expression": "'Unknown group.'", + "captured": [] + } + ] + }, { "key": "m05be21b447e46cab5128", "id": "utils.ApiMessage.m05be21b447e46cab5128", @@ -3457,7 +3476,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 978, + "line": 981, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB did not confirm application authentication.'", @@ -5364,7 +5383,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2249, + "line": 2289, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB network response'", @@ -5985,7 +6004,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 888, + "line": 1588, "kind": "authored-message-field", "field": "message", "expression": "'LazyLibrarian, the service used for magazine searches, is unavailable. Please try again.'", @@ -6582,7 +6601,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1796, + "line": 1836, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover TV: ${e.message}`", @@ -6798,7 +6817,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2238, + "line": 2278, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie studio: ${e.message}`", @@ -7433,7 +7452,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2175, + "line": 2215, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch countries: ${e.message}`", @@ -8619,7 +8638,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1478, + "line": 1516, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover movies: ${e.message}`", @@ -8633,7 +8652,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1506, + "line": 1544, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover movies: ${e.message}`", @@ -8647,7 +8666,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1692, + "line": 1732, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover movies: ${e.message}`", @@ -9133,7 +9152,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1369, + "line": 1407, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV show details: ${e.message}`", @@ -9147,7 +9166,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1450, + "line": 1488, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV show details: ${e.message}`", @@ -12399,7 +12418,7 @@ }, { "path": "server/routes/search.ts", - "line": 1495, + "line": 2239, "kind": "authored-message-field", "field": "errorMessage", "expression": "e instanceof Error ? e.message : 'Unknown error'", @@ -13168,7 +13187,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 262, + "line": 872, "kind": "app-error-candidate", "field": "message", "expression": "'Magazine search timed out.'", @@ -13187,7 +13206,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1869, + "line": 1909, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB list ID must be a positive decimal ID'", @@ -14185,7 +14204,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2311, + "line": 2351, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie genres: ${e.message}`", @@ -15654,7 +15673,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2362, + "line": 2402, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV genres: ${e.message}`", @@ -15732,7 +15751,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2022, + "line": 2062, "kind": "app-error-candidate", "field": "message", "expression": "`No movie or show returned from API for ID ${imdbId}`", @@ -17140,6 +17159,31 @@ } ] }, + { + "key": "m3a871ad796606381cdbe", + "id": "utils.ApiMessage.m3a871ad796606381cdbe", + "source": "{value0} did not answer in time.", + "defaultMessage": "{value0} did not answer in time.", + "sourceHash": "3a871ad796606381cdbead2d78152683311f965a99e4fab25bf5728fc57a5ec2", + "parts": ["", " did not answer in time."], + "parameterCount": 1, + "callsites": [ + { + "path": "server/routes/search.ts", + "line": 2350, + "kind": "authored-message-field", + "field": "message", + "expression": "`${SEARCH_SOURCE_NAMES[group]} did not answer in time.`", + "captured": [ + { + "name": "value0", + "expression": "SEARCH_SOURCE_NAMES[group]", + "disposition": "opaque captured value; preserve verbatim" + } + ] + } + ] + }, { "key": "m3a88700c18ea37a62b14", "id": "utils.ApiMessage.m3a88700c18ea37a62b14", @@ -20351,7 +20395,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2054, + "line": 2094, "kind": "app-error-candidate", "field": "message", "expression": "`No show returned from API for ID ${tvdbId}`", @@ -21202,7 +21246,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1879, + "line": 1919, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch list ${listId}: ${e.message}`", @@ -22054,7 +22098,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1853, + "line": 1893, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch all trending: ${e.message}`", @@ -22068,7 +22112,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1907, + "line": 1947, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch all trending: ${e.message}`", @@ -22082,7 +22126,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1935, + "line": 1975, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch all trending: ${e.message}`", @@ -23029,7 +23073,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1196, + "line": 1234, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch person combined credits: ${e.message}`", @@ -24213,7 +24257,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1528, + "line": 2419, "kind": "authored-message-field", "field": "message", "expression": "'Unable to retrieve keyword search results.'", @@ -24257,7 +24301,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1824, + "line": 1864, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch upcoming movies: ${e.message}`", @@ -24855,7 +24899,7 @@ }, { "path": "server/routes/search.ts", - "line": 664, + "line": 1352, "kind": "authored-message-field", "field": "error", "expression": "'OK'", @@ -24863,7 +24907,15 @@ }, { "path": "server/routes/search.ts", - "line": 1007, + "line": 1712, + "kind": "authored-message-field", + "field": "error", + "expression": "'OK'", + "captured": [] + }, + { + "path": "server/routes/searchTiming.bench.ts", + "line": 191, "kind": "authored-message-field", "field": "error", "expression": "'OK'", @@ -25917,7 +25969,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 844, + "line": 1544, "kind": "authored-message-field", "field": "message", "expression": "bookFormat === 'audiobook'\n ? 'The configured audiobook catalog is unavailable. Please try again.'\n : 'Open Library and configured book catalogs are unavailable. Please try again.'", @@ -26427,7 +26479,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2429, + "line": 2469, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch keyword: ${e.message}`", @@ -27031,7 +27083,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 814, + "line": 1514, "kind": "authored-message-field", "field": "message", "expression": "'MusicBrainz, the service used for music searches, timed out or is unavailable. Please try again.'", @@ -27136,7 +27188,7 @@ }, { "path": "server/routes/search.ts", - "line": 874, + "line": 1574, "kind": "authored-message-field", "field": "message", "expression": "'ComicVine, the service used for comic searches, timed out or is unavailable. Please try again.'", @@ -27626,7 +27678,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2224, + "line": 2264, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB studio response'", @@ -28428,7 +28480,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2619, + "line": 2659, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV watch providers: ${e.message}`", @@ -28699,7 +28751,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1172, + "line": 1210, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch person details: ${e.message}`", @@ -28799,7 +28851,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2118, + "line": 2158, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB returned an invalid collection response.'", @@ -28988,7 +29040,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1564, + "line": 1602, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV recommendations: ${e.message}`", @@ -29086,7 +29138,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1267, + "line": 1305, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie details: ${e.message}`", @@ -32397,7 +32449,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1589, + "line": 1627, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV similar: ${e.message}`", @@ -39786,6 +39838,25 @@ } ] }, + { + "key": "m8b930328dd402c0300db", + "id": "utils.ApiMessage.m8b930328dd402c0300db", + "source": "Search failed.", + "defaultMessage": "Search failed.", + "sourceHash": "8b930328dd402c0300dbafa39810476f27d11ba2876dbd76748569b28e739842", + "parts": ["Search failed."], + "parameterCount": 0, + "callsites": [ + { + "path": "server/routes/search.ts", + "line": 2338, + "kind": "authored-message-field", + "field": "message", + "expression": "'Search failed.'", + "captured": [] + } + ] + }, { "key": "m8ba020c75e047a8ef847", "id": "utils.ApiMessage.m8ba020c75e047a8ef847", @@ -40491,7 +40562,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2483, + "line": 2523, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to search companies: ${e.message}`", @@ -40905,7 +40976,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2571, + "line": 2611, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie watch providers: ${e.message}`", @@ -41943,7 +42014,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1989, + "line": 2029, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to find by external ID: ${e.message}`", @@ -42258,7 +42329,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1392, + "line": 1430, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV show scan details: ${e.message}`", @@ -42865,7 +42936,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 491, + "line": 492, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB TV response'", @@ -43254,7 +43325,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2523, + "line": 2563, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch available watch regions: ${e.message}`", @@ -43321,7 +43392,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 861, + "line": 1561, "kind": "authored-message-field", "field": "message", "expression": "'The author catalogs timed out or are unavailable. Please try again.'", @@ -44118,7 +44189,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1556, + "line": 2447, "kind": "authored-message-field", "field": "message", "expression": "'Unable to retrieve company search results.'", @@ -46054,7 +46125,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 311, + "line": 312, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB person response'", @@ -46891,7 +46962,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 690, + "line": 691, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB list response'", @@ -47999,7 +48070,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 380, + "line": 998, "kind": "authored-message-field", "field": "message", "expression": "'Music filters require the Music media type.'", @@ -48124,7 +48195,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1419, + "line": 1457, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB returned an invalid season response.'", @@ -48840,7 +48911,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 771, + "line": 1466, "kind": "authored-message-field", "field": "errorMessage", "expression": "'Provider did not finish before the global search deadline.'", @@ -49002,7 +49073,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 844, + "line": 1544, "kind": "authored-message-field", "field": "message", "expression": "bookFormat === 'audiobook'\n ? 'The configured audiobook catalog is unavailable. Please try again.'\n : 'Open Library and configured book catalogs are unavailable. Please try again.'", @@ -49588,7 +49659,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2396, + "line": 2436, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV certifications: ${e.message}`", @@ -50636,7 +50707,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2456, + "line": 2496, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to search keyword: ${e.message}`", @@ -51557,7 +51628,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2141, + "line": 2181, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch collection: ${e.message}`", @@ -52148,7 +52219,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 383, + "line": 384, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB movie response'", @@ -54277,7 +54348,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1500, + "line": 2244, "kind": "authored-message-field", "field": "message", "expression": "'Unable to retrieve search results.'", @@ -54914,6 +54985,25 @@ } ] }, + { + "key": "mc76e7bca13022526f579", + "id": "utils.ApiMessage.mc76e7bca13022526f579", + "source": "503 Service Unavailable", + "defaultMessage": "503 Service Unavailable", + "sourceHash": "c76e7bca13022526f579c85d3d94d52ac45802f71067739cc6409d4e2c37e617", + "parts": ["503 Service Unavailable"], + "parameterCount": 0, + "callsites": [ + { + "path": "server/routes/searchTiming.bench.ts", + "line": 116, + "kind": "app-error-candidate", + "field": "message", + "expression": "'503 Service Unavailable'", + "captured": [] + } + ] + }, { "key": "mc7736058413ee241e5c4", "id": "utils.ApiMessage.mc7736058413ee241e5c4", @@ -55099,7 +55189,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 409, + "line": 1025, "kind": "authored-message-field", "field": "message", "expression": "'Format can only be used with book searches.'", @@ -56774,7 +56864,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 805, + "line": 1505, "kind": "authored-message-field", "field": "message", "expression": "'Artist search is temporarily unavailable. Please try again.'", @@ -59429,7 +59519,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2260, + "line": 2300, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV network: ${e.message}`", @@ -59633,7 +59723,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1535, + "line": 1573, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movies by keyword: ${e.message}`", @@ -63410,7 +63500,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2025, + "line": 2065, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to find media using external IMDb ID: ${e.message}`", @@ -64605,7 +64695,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2211, + "line": 2251, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch langauges: ${e.message}`", @@ -64801,7 +64891,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2074, + "line": 2114, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to get TV show using the external TVDB ID: ${e.message}`", @@ -64815,7 +64905,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 2094, + "line": 2134, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to get TV show using the external TVDB ID: ${e.message}`", @@ -67819,7 +67909,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1969, + "line": 2009, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid external media ID'", @@ -70039,7 +70129,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2379, + "line": 2419, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie certifications: ${e}`", @@ -74720,7 +74810,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 59, + "line": 60, "kind": "authored-message-variable", "field": "isTmdbCollectionSearchPageSummary", "expression": "(\n value: unknown\n): value is TmdbCollectionSearchPageSummary =>\n isRecord(value) &&\n Number.isSafeInteger(value.total_pages) &&\n (value.total_pages as number) > 0 &&\n Number.isSafeInteger(value.total_results) &&\n (value.total_results as number) >= 0", @@ -74729,7 +74819,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 62, + "line": 63, "kind": "message-helper-expression", "field": "message", "expression": "isRecord(value) &&\n Number.isSafeInteger(value.total_pages) &&\n (value.total_pages as number) > 0 &&\n Number.isSafeInteger(value.total_results) &&\n (value.total_results as number) >= 0", @@ -74738,7 +74828,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1053, + "line": 1056, "kind": "authored-message-variable", "field": "knownSummary", "expression": "pageCache.get(pageCacheKey)", @@ -81351,6 +81441,24 @@ "source": "{value0}", "reason": "dynamic/provider/user value" }, + { + "path": "server/lib/searchSuggest.ts", + "line": 301, + "kind": "authored-message-field", + "field": "errorMessage", + "expression": "error instanceof Error ? error.message : String(error)", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/lib/searchSuggest.ts", + "line": 301, + "kind": "authored-message-field", + "field": "errorMessage", + "expression": "error instanceof Error ? error.message : String(error)", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, { "path": "server/lib/settings/fileSecurity.ts", "line": 41, @@ -90038,7 +90146,52 @@ }, { "path": "server/routes/search.ts", - "line": 345, + "line": 249, + "kind": "message-helper-expression", + "field": "message", + "expression": "({ error })", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 369, + "kind": "authored-message-field", + "field": "reason", + "expression": "'intent' as const", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 384, + "kind": "authored-message-field", + "field": "reason", + "expression": "'intent' as const", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 408, + "kind": "authored-message-field", + "field": "reason", + "expression": "'match' as const", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 530, + "kind": "authored-message-field", + "field": "message", + "expression": "parsed.error", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 958, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90047,7 +90200,7 @@ }, { "path": "server/routes/search.ts", - "line": 355, + "line": 975, "kind": "authored-message-field", "field": "message", "expression": "parsedLanguage.error", @@ -90056,7 +90209,7 @@ }, { "path": "server/routes/search.ts", - "line": 367, + "line": 987, "kind": "authored-message-field", "field": "message", "expression": "parsedType.error", @@ -90065,7 +90218,7 @@ }, { "path": "server/routes/search.ts", - "line": 374, + "line": 992, "kind": "authored-message-field", "field": "message", "expression": "parsedMusicFilters.error", @@ -90074,7 +90227,7 @@ }, { "path": "server/routes/search.ts", - "line": 392, + "line": 1008, "kind": "authored-message-field", "field": "message", "expression": "parsedResultFilter.error", @@ -90083,7 +90236,7 @@ }, { "path": "server/routes/search.ts", - "line": 403, + "line": 1019, "kind": "authored-message-field", "field": "message", "expression": "parsedFormat.error", @@ -90092,7 +90245,7 @@ }, { "path": "server/routes/search.ts", - "line": 1495, + "line": 2239, "kind": "authored-message-field", "field": "errorMessage", "expression": "e instanceof Error ? e.message : 'Unknown error'", @@ -90101,7 +90254,43 @@ }, { "path": "server/routes/search.ts", - "line": 1508, + "line": 2282, + "kind": "authored-message-field", + "field": "message", + "expression": "parsedQuery.error", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 2357, + "kind": "authored-message-variable", + "field": "error", + "expression": "'error' in outcome\n ? outcome.error\n : {\n status: outcome.status,\n message: String(outcome.body.message ?? 'Search failed.'),\n }", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 2357, + "kind": "authored-message-variable", + "field": "error", + "expression": "'error' in outcome\n ? outcome.error\n : {\n status: outcome.status,\n message: String(outcome.body.message ?? 'Search failed.'),\n }", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 2361, + "kind": "authored-message-field", + "field": "message", + "expression": "String(outcome.body.message ?? 'Search failed.')", + "source": "{value0}", + "reason": "dynamic/provider/user value" + }, + { + "path": "server/routes/search.ts", + "line": 2399, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90110,7 +90299,7 @@ }, { "path": "server/routes/search.ts", - "line": 1523, + "line": 2414, "kind": "authored-message-field", "field": "errorMessage", "expression": "e.message", @@ -90119,7 +90308,7 @@ }, { "path": "server/routes/search.ts", - "line": 1536, + "line": 2427, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90128,7 +90317,7 @@ }, { "path": "server/routes/search.ts", - "line": 1551, + "line": 2442, "kind": "authored-message-field", "field": "errorMessage", "expression": "e.message", diff --git a/config/i18n/source-snapshot.json b/config/i18n/source-snapshot.json index 5e6f22bf33..a2ff74660f 100644 --- a/config/i18n/source-snapshot.json +++ b/config/i18n/source-snapshot.json @@ -7679,6 +7679,7 @@ "utils.ApiMessage.m053d64cdb6bb108bb03d": "053d64cdb6bb108bb03d706f52b3b22f98bbcbf45939c90d434dd069ff3619e7", "utils.ApiMessage.m056a1948099f9b30635e": "056a1948099f9b30635eddd9bcf1090c43e43ffced94ed636663ec06f6da0155", "utils.ApiMessage.m058efc336f3cb16247d0": "058efc336f3cb16247d0c36d222a2c8e77b8f27ad9ca56298eb682ee85d7a11e", + "utils.ApiMessage.m059d378dcd252eadde7e": "059d378dcd252eadde7ee37448683c81f0282bc3ec5311a7275442fe08859d37", "utils.ApiMessage.m05be21b447e46cab5128": "05be21b447e46cab5128654b2cde177c5d55a7451c5e7dec70f4a8a2a743552b", "utils.ApiMessage.m05e26dcf8a5c67102cb4": "05e26dcf8a5c67102cb44f3dc672764a2be71fff52fc1803f0e94b72f5f27634", "utils.ApiMessage.m05f73fd10a09b2ff6f16": "05f73fd10a09b2ff6f1631330f1ad96e4385051e55a7ed7891eb6b39029af710", @@ -8303,6 +8304,7 @@ "utils.ApiMessage.m3a3c19b21d003f376119": "3a3c19b21d003f3761193e625b5eadf3ec37a3d50fcaad0ec29f7948e45f9242", "utils.ApiMessage.m3a6b2cf84156fb6b9625": "3a6b2cf84156fb6b962534a066018824ce6bb1af72d14e9c3b668fcbd52aea00", "utils.ApiMessage.m3a869f82af3294e3b3be": "3a869f82af3294e3b3be93c53e37b40dab901fe1cb5f573d42365d93618f0278", + "utils.ApiMessage.m3a871ad796606381cdbe": "3a871ad796606381cdbead2d78152683311f965a99e4fab25bf5728fc57a5ec2", "utils.ApiMessage.m3a88700c18ea37a62b14": "3a88700c18ea37a62b14c129ac6085e40e5c0ffc6aaa34009100cc1a3c65676d", "utils.ApiMessage.m3a8a8df9111bce9e1ca1": "3a8a8df9111bce9e1ca14aade054469ed3eba1348c74c6c243c2af22270d0824", "utils.ApiMessage.m3a92414194497eaed76e": "3a92414194497eaed76e5a76d2ff92d8601f663e01004e771a6a4b23fca9e354", @@ -9277,6 +9279,7 @@ "utils.ApiMessage.m8b6b0d42f0707af0f39f": "8b6b0d42f0707af0f39fb831118e985117ca867fd2cfdd9cbe54be10bc975494", "utils.ApiMessage.m8b7741e1aac03b859db0": "8b7741e1aac03b859db0446b638b17d20c4e726a431503ee2723c16bf5dfdc37", "utils.ApiMessage.m8b83363faf5540e7fb69": "8b83363faf5540e7fb6940d9125e4abcdffccd6f922caee956239213237c1a58", + "utils.ApiMessage.m8b930328dd402c0300db": "8b930328dd402c0300dbafa39810476f27d11ba2876dbd76748569b28e739842", "utils.ApiMessage.m8ba020c75e047a8ef847": "8ba020c75e047a8ef8479bce111edf9c4e21ce75fbbab4740f5bef154e8e7721", "utils.ApiMessage.m8babbcacd4584f331250": "8babbcacd4584f331250562d9025a3496650acf091b24cc76d7691a95d780066", "utils.ApiMessage.m8bbbcb298e40333bd9ad": "8bbbcb298e40333bd9adb4296cf1c11cdc2abae8325e9b8896155c09a1b607b7", @@ -9951,6 +9954,7 @@ "utils.ApiMessage.mc72069ca3d442af8ac8f": "c72069ca3d442af8ac8f3ae3721a5b71d965837d0f9279e577bb7004519aef3c", "utils.ApiMessage.mc73fee6c5396519dd225": "c73fee6c5396519dd22517cf53bbe92105366b5fb020d247bbf3f592dc5ae2e4", "utils.ApiMessage.mc74896863adb52dfa21b": "c74896863adb52dfa21bba854175a87f829de35dd5b3708de06071043340ae90", + "utils.ApiMessage.mc76e7bca13022526f579": "c76e7bca13022526f579c85d3d94d52ac45802f71067739cc6409d4e2c37e617", "utils.ApiMessage.mc7736058413ee241e5c4": "c7736058413ee241e5c486b490ab6b919603308dbd5b710e864aeeaa8538b727", "utils.ApiMessage.mc7a46d91ce09d577f6c1": "c7a46d91ce09d577f6c1728f2493d27aa7645a49b4fe31af9af9ee23f8633824", "utils.ApiMessage.mc7c17d51f450414ddbc9": "c7c17d51f450414ddbc920f40d342fbf5bdf2e2c5af9d41a64e901f4d3865062", diff --git a/seerr-api.yml b/seerr-api.yml index 6fd2b4c23e..f4f6b44295 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -8390,6 +8390,95 @@ components: type: string mediaInfo: $ref: '#/components/schemas/MediaInfo' + SearchIntent: + type: object + description: How the server understood a search query. A hint; the query is still searched as typed. + properties: + kind: + type: string + enum: [title, person-works, discover, show-season] + entity: + type: string + description: The query without its intent words ("nate" for "nate standup"). + format: + type: string + enum: + [ + standup, + documentary, + anime, + live, + audiobook, + ebook, + album, + soundtrack, + manga, + ] + mediaType: + type: string + enum: [movie, tv, book, music, podcast, comic, person] + genre: { type: string } + year: { type: number } + decade: + type: object + properties: + start: { type: number } + end: { type: number } + season: { type: number } + episode: { type: number } + role: { type: string } + creator: { type: string } + label: + type: string + description: Short English label, such as Stand-up specials. + matched: + type: array + items: { type: string } + sections: + type: array + description: Result media types in the order they should be shown. + items: { type: string } + SearchTopResult: + type: object + description: The card to show above the sections when the intent is clear. + properties: + kind: + type: string + enum: [person, title] + reason: + type: string + enum: [intent, match] + label: { type: string } + item: + type: object + description: A search result (person, movie, series, album...). + works: + type: array + description: For a person, the works that fit the query (their stand-up specials). + items: + type: object + season: { type: number } + episode: { type: number } + SearchSuggestion: + type: object + properties: + mediaType: + type: string + enum: + [movie, tv, person, collection, album, artist, book, author, comic] + id: + oneOf: + - type: number + - type: string + title: { type: string } + year: { type: string } + posterPath: { type: string } + subtitle: { type: string } + owned: { type: boolean } + source: + type: string + enum: [library, learned, popular] + score: { type: number } Keyword: type: object properties: @@ -21021,8 +21110,20 @@ paths: partial: type: boolean description: One or more search providers failed or timed out. + failedSources: + type: array + items: { type: string } + description: Present with partial. Plain names of the sources that did not answer, such as Music or Books. + intent: + $ref: '#/components/schemas/SearchIntent' + topResult: + $ref: '#/components/schemas/SearchTopResult' + correctedQuery: + type: string + description: Nothing matched the query as typed, so these results are for this spelling correction. results: type: array + description: Each result carries matchScore (0-100). Within each media type, results are ordered by it. items: anyOf: - $ref: '#/components/schemas/MovieResult' @@ -21035,6 +21136,112 @@ paths: - $ref: '#/components/schemas/AuthorResult' - $ref: '#/components/schemas/ComicResult' - $ref: '#/components/schemas/MagazineResult' + /search/stream: + get: + summary: Search everything, streamed as each source answers + description: >- + The global search, streamed as newline-delimited JSON. The first line is + {"type":"intent"} with how the query was understood. Each provider group + (video, music, books, authors, comics, magazines) then answers on its own + line ({"type":"results","group":...} with the same fields as GET /search, + or {"type":"error","group":...}) as soon as it finishes, so fast sources + are never held back by slow ones. The last line is {"type":"done"} with + failedSources naming the sources that did not answer. + tags: + - search + parameters: + - in: query + name: query + required: true + schema: { type: string, maxLength: 256 } + - in: query + name: page + schema: { type: number, default: 1 } + - in: query + name: language + schema: { type: string } + - in: query + name: type + schema: + type: string + enum: + [ + movie, + tv, + person, + album, + artist, + book, + author, + music, + comic, + magazine, + ] + - in: query + name: groups + description: Comma-separated provider groups to search (video, music, books, authors, comics, magazines). All when omitted. + schema: { type: string, maxLength: 64 } + - in: query + name: includeCredits + schema: + type: string + enum: ['false'] + - in: query + name: format + schema: + type: string + enum: [ebook, audiobook] + responses: + '200': + description: Newline-delimited JSON events + content: + application/x-ndjson: + schema: + type: string + /search/suggest: + get: + summary: Search suggestions while typing + description: >- + Fast suggestions for a partial query from an in-memory index of the + library, recent search answers and trending titles: titles, people, + query suggestions such as "Nate Bargatze stand-up specials", and a + spelling correction (didYouMean). Answers within about 150 ms. + tags: + - search + parameters: + - in: query + name: q + required: true + schema: { type: string, maxLength: 100 } + - in: query + name: language + schema: { type: string } + responses: + '200': + description: Suggestions + content: + application/json: + schema: + type: object + properties: + query: { type: string } + didYouMean: { type: string } + elapsedMs: { type: number } + queries: + type: array + items: + type: object + properties: + text: { type: string } + kind: { type: string, enum: [intent, correction] } + titles: + type: array + items: + $ref: '#/components/schemas/SearchSuggestion' + people: + type: array + items: + $ref: '#/components/schemas/SearchSuggestion' /search/keyword: get: summary: Search for keywords diff --git a/server/api/themoviedb/index.ts b/server/api/themoviedb/index.ts index 452fecbc04..7d5449d9e7 100644 --- a/server/api/themoviedb/index.ts +++ b/server/api/themoviedb/index.ts @@ -30,6 +30,7 @@ import type { TmdbSearchCollectionResponse, TmdbSearchMovieResponse, TmdbSearchMultiResponse, + TmdbSearchPersonResponse, TmdbSearchTvResponse, TmdbSeasonWithEpisodes, TmdbTvDetails, @@ -865,6 +866,8 @@ interface DiscoverMovieOptions { certificationGte?: string; certificationLte?: string; certificationCountry?: string; + /** Comma-separated TMDB person ids credited in cast or crew. */ + people?: string; } interface DiscoverTvOptions { @@ -1155,6 +1158,41 @@ class TheMovieDb extends ExternalAPI implements TvShowProvider { } }; + public searchPeople = async ({ + query, + page = 1, + includeAdult = this.includeAdult, + language = this.locale, + }: SearchOptions): Promise => { + const data = await this.get('/search/person', { + params: { + query, + page, + include_adult: this.contentRestriction ? false : includeAdult, + language, + }, + }); + const response = sanitizeTmdbPagedResponse( + data, + page + ); + return { + ...response, + results: response.results + .filter( + (person) => + !!person && + Number.isSafeInteger(person.id) && + typeof person.name === 'string' && + (!person.adult || (includeAdult && !this.contentRestriction)) + ) + .map((person) => ({ + ...person, + known_for: Array.isArray(person.known_for) ? person.known_for : [], + })), + }; + }; + public getPerson = async ({ personId, language = this.locale, @@ -1621,6 +1659,7 @@ class TheMovieDb extends ExternalAPI implements TvShowProvider { certificationGte, certificationLte, certificationCountry, + people, }: DiscoverMovieOptions = {}): Promise => { if (this.contentRestriction) { includeAdult = false; @@ -1671,6 +1710,7 @@ class TheMovieDb extends ExternalAPI implements TvShowProvider { with_origin_country: country, with_keywords: keywords, without_keywords: excludeKeywords, + with_people: people, 'with_runtime.gte': withRuntimeGte, 'with_runtime.lte': withRuntimeLte, 'vote_average.gte': voteAverageGte, diff --git a/server/lib/searchIntent.test.ts b/server/lib/searchIntent.test.ts new file mode 100644 index 0000000000..b5d06bbd15 --- /dev/null +++ b/server/lib/searchIntent.test.ts @@ -0,0 +1,146 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + STANDUP_KEYWORD_ID, + parseSearchIntent, + publicSearchIntent, + sectionOrderForIntent, +} from '@server/lib/searchIntent'; + +describe('parseSearchIntent', () => { + it('splits a person from stand-up intent words', () => { + for (const query of [ + 'nate standup', + 'Nate stand-up', + 'nate stand up', + 'nate stand up comedy', + 'nate comedy specials', + 'Nate Bargatze stand-up specials', + ]) { + const intent = parseSearchIntent(query); + assert.equal(intent.format, 'standup', query); + assert.equal(intent.kind, 'person-works', query); + assert.equal(intent.keywordId, STANDUP_KEYWORD_ID, query); + assert.equal(intent.genre?.movieGenreId, 35, query); + assert.match(intent.entity, /^nate( bargatze)?$/, query); + assert.equal(intent.label, 'Stand-up specials'); + } + }); + + it('treats a trailing "specials" after a name as stand-up', () => { + const intent = parseSearchIntent('nate bargatze specials'); + assert.equal(intent.format, 'standup'); + assert.equal(intent.entity, 'nate bargatze'); + }); + + it('keeps a bare intent phrase searchable as typed', () => { + for (const query of ['standup', 'stand up', 'horror']) { + const intent = parseSearchIntent(query); + assert.equal(intent.kind, 'discover', query); + assert.equal(intent.entity, intent.normalized, query); + } + assert.equal(parseSearchIntent('specials').format, undefined); + }); + + it('recognizes live albums, audiobooks and seasons', () => { + const live = parseSearchIntent('metallica live'); + assert.deepEqual( + [live.entity, live.format, live.mediaType, live.kind], + ['metallica', 'live', 'music', 'person-works'] + ); + + const audiobook = parseSearchIntent('Brandon Sanderson audiobook'); + assert.deepEqual( + [audiobook.entity, audiobook.format, audiobook.mediaType], + ['brandon sanderson', 'audiobook', 'book'] + ); + + for (const query of [ + 'the bear season 3', + 'the bear s3', + 'The Bear S03E02', + ]) { + const season = parseSearchIntent(query); + assert.equal(season.kind, 'show-season', query); + assert.equal(season.entity, 'the bear', query); + assert.equal(season.season, 3, query); + assert.equal(season.mediaType, 'tv', query); + } + assert.equal(parseSearchIntent('The Bear S03E02').episode, 2); + }); + + it('turns a year or decade plus genre into a discover search', () => { + const horror = parseSearchIntent('2015 horror'); + assert.deepEqual( + [horror.kind, horror.year, horror.genre?.movieGenreId, horror.entity], + ['discover', 2015, 27, ''] + ); + const eighties = parseSearchIntent("80's action movies"); + assert.equal(eighties.kind, 'discover'); + assert.deepEqual(eighties.decade, { start: 1980, end: 1989 }); + assert.equal(eighties.genre?.name, 'Action'); + assert.equal(eighties.mediaType, 'movie'); + assert.deepEqual(parseSearchIntent('1990s sci-fi').decade, { + start: 1990, + end: 1999, + }); + }); + + it('leaves titles that merely contain intent words alone', () => { + // a lone year is a title ("1917"), genre words inside a title stay + assert.equal(parseSearchIntent('1917').year, undefined); + assert.equal(parseSearchIntent('1917').kind, 'title'); + const comedy = parseSearchIntent('the comedy of errors'); + assert.equal(comedy.genre, undefined); + assert.equal(comedy.entity, 'the comedy of errors'); + const standBy = parseSearchIntent('stand by me'); + assert.equal(standBy.creator, undefined); + assert.equal(standBy.kind, 'title'); + const liveFree = parseSearchIntent('live free or die hard'); + assert.equal(liveFree.format, undefined); + }); + + it('reads creators and roles', () => { + const dune = parseSearchIntent('dune by frank herbert'); + assert.equal(dune.entity, 'dune'); + assert.equal(dune.creator, 'frank herbert'); + const directed = parseSearchIntent('movies directed by greta gerwig'); + assert.equal(directed.role, 'director'); + assert.equal(directed.creator, 'greta gerwig'); + assert.equal(directed.mediaType, 'movie'); + const narrated = parseSearchIntent('narrated by Michael Kramer'); + assert.equal(narrated.format, 'audiobook'); + assert.equal(narrated.role, 'narrator'); + }); + + it('orders result sections by what was asked for', () => { + assert.deepEqual( + sectionOrderForIntent(parseSearchIntent('nate standup')).slice(0, 3), + ['movie', 'tv', 'person'] + ); + assert.deepEqual( + sectionOrderForIntent(parseSearchIntent('metallica live')).slice(0, 2), + ['album', 'artist'] + ); + assert.deepEqual( + sectionOrderForIntent(parseSearchIntent('sanderson audiobooks')).slice( + 0, + 2 + ), + ['book', 'author'] + ); + const all = sectionOrderForIntent(parseSearchIntent('dune')); + assert.equal(new Set(all).size, all.length); + assert.equal(all[0], 'movie'); + }); + + it('exposes only client-facing fields', () => { + const intent = publicSearchIntent(parseSearchIntent('nate standup')); + assert.equal(intent.kind, 'person-works'); + assert.equal(intent.format, 'standup'); + assert.equal(intent.genre, 'Comedy'); + assert.equal('keywordId' in intent, false); + assert.ok(Array.isArray(intent.sections)); + }); +}); diff --git a/server/lib/searchIntent.ts b/server/lib/searchIntent.ts new file mode 100644 index 0000000000..5908beb2c0 --- /dev/null +++ b/server/lib/searchIntent.ts @@ -0,0 +1,716 @@ +/** + * Query understanding for global search. + * + * Splits what was typed into the thing being looked for (the "entity": a + * title, a person, an artist) and the words that only describe it (intent + * words: a format such as "standup" or "audiobook", a genre, a media type, + * a season, a year or decade, a role such as "director"). + * + * "nate standup" entity "nate", format standup + * "metallica live" entity "metallica", format live (music) + * "brandon sanderson audiobook" entity "brandon sanderson", format audiobook + * "the bear season 3" entity "the bear", season 3 + * "2015 horror" no entity, year 2015, genre Horror + * "80s action movies" no entity, decade 1980s, genre Action, movies + * + * The parse is a hint, never a filter: global search still runs the query + * exactly as typed, and adds what the intent finds on top. A wrong guess + * ("live" in a title) therefore costs nothing but a slightly different order. + */ +import { normalizeSearchText } from '@server/lib/searchRanking'; + +export type SearchFormat = + | 'standup' + | 'documentary' + | 'anime' + | 'live' + | 'audiobook' + | 'ebook' + | 'album' + | 'soundtrack' + | 'manga'; + +export type SearchMediaHint = + 'movie' | 'tv' | 'book' | 'music' | 'podcast' | 'comic' | 'person'; + +export type SearchPersonRole = + 'actor' | 'director' | 'author' | 'artist' | 'comedian' | 'narrator'; + +export type SearchGenre = { + /** English display name, e.g. "Horror". */ + name: string; + movieGenreId?: number; + tvGenreId?: number; +}; + +export type SearchIntentKind = + /** A plain title or name search. */ + | 'title' + /** Find a person, then the works of theirs that fit ("nate standup"). */ + | 'person-works' + /** No entity: browse by genre, format, year or decade ("2015 horror"). */ + | 'discover' + /** A series and a season ("the bear season 3"). */ + | 'show-season'; + +export type SearchIntent = { + query: string; + normalized: string; + /** Query words that are not intent words, in normalized form. */ + entity: string; + entityWords: string[]; + /** The intent phrases that were recognized, in normalized form. */ + matched: string[]; + kind: SearchIntentKind; + format?: SearchFormat; + mediaType?: SearchMediaHint; + genre?: SearchGenre; + /** TMDB keyword to look for, e.g. 9716 "stand-up comedy". */ + keywordId?: number; + /** Original language, e.g. "ja" for anime. */ + originalLanguage?: string; + year?: number; + decade?: { start: number; end: number }; + season?: number; + episode?: number; + role?: SearchPersonRole; + /** "dune by frank herbert": the part after "by". */ + creator?: string; + /** Short English label for the intent, e.g. "Stand-up specials". */ + label?: string; +}; + +/** TMDB keyword "stand-up comedy". */ +export const STANDUP_KEYWORD_ID = 9716; +const COMEDY: SearchGenre = { name: 'Comedy', movieGenreId: 35, tvGenreId: 35 }; +const DOCUMENTARY: SearchGenre = { + name: 'Documentary', + movieGenreId: 99, + tvGenreId: 99, +}; +const ANIMATION: SearchGenre = { + name: 'Animation', + movieGenreId: 16, + tvGenreId: 16, +}; + +type Rule = { + words: string[]; + /** Only at the start or end of the query, where descriptors usually go. */ + edge?: boolean; + /** Only at the very end of the query. */ + end?: boolean; + /** Only when other words remain to search for. */ + needsEntity?: boolean; + apply: (intent: SearchIntent) => void; +}; + +const genre = + (name: string, movieGenreId?: number, tvGenreId?: number) => + (intent: SearchIntent) => { + intent.genre ??= { name, movieGenreId, tvGenreId }; + }; +const media = (type: SearchMediaHint) => (intent: SearchIntent) => { + intent.mediaType ??= type; +}; +const role = (value: SearchPersonRole) => (intent: SearchIntent) => { + intent.role ??= value; +}; +const standup = (intent: SearchIntent) => { + intent.format = 'standup'; + intent.genre = COMEDY; + intent.keywordId = STANDUP_KEYWORD_ID; +}; + +const forms = (...words: string[]) => words.map((word) => word.split(' ')); +const rules: Rule[] = [ + // stand-up comedy ("stand-up" and "stand up" normalize to the same words) + ...forms( + 'stand up comedy specials', + 'stand up comedy special', + 'stand up specials', + 'stand up special', + 'standup specials', + 'standup special', + 'stand up comedy', + 'standup comedy', + 'comedy specials', + 'comedy special', + 'stand up', + 'standup', + 'standups' + ).map((words) => ({ words, apply: standup })), + { words: ['comedian'], edge: true, apply: role('comedian') }, + { words: ['comedians'], edge: true, apply: role('comedian') }, + // "nate bargatze specials": a trailing "special(s)" after a name + { words: ['specials'], end: true, needsEntity: true, apply: standup }, + { words: ['special'], end: true, needsEntity: true, apply: standup }, + + // formats + ...forms('documentary', 'documentaries', 'docuseries', 'docu series').map( + (words) => ({ + words, + edge: true, + apply: (intent: SearchIntent) => { + intent.format = 'documentary'; + intent.genre = DOCUMENTARY; + }, + }) + ), + { + words: ['doc'], + end: true, + needsEntity: true, + apply: (intent) => { + intent.format = 'documentary'; + intent.genre = DOCUMENTARY; + }, + }, + { + words: ['anime'], + edge: true, + apply: (intent) => { + intent.format = 'anime'; + intent.genre = ANIMATION; + intent.originalLanguage = 'ja'; + }, + }, + ...forms('live albums', 'live album', 'in concert', 'live').map((words) => ({ + words, + end: true, + needsEntity: true, + apply: (intent: SearchIntent) => { + intent.format = 'live'; + intent.mediaType ??= 'music'; + }, + })), + ...forms('audiobooks', 'audiobook', 'audio books', 'audio book').map( + (words) => ({ + words, + edge: true, + apply: (intent: SearchIntent) => { + intent.format = 'audiobook'; + intent.mediaType = 'book'; + }, + }) + ), + ...forms('ebooks', 'ebook', 'e books', 'e book').map((words) => ({ + words, + edge: true, + apply: (intent: SearchIntent) => { + intent.format = 'ebook'; + intent.mediaType = 'book'; + }, + })), + ...forms('soundtrack', 'original soundtrack', 'ost', 'score').map( + (words) => ({ + words, + end: true, + needsEntity: true, + apply: (intent: SearchIntent) => { + intent.format = 'soundtrack'; + intent.mediaType = 'music'; + }, + }) + ), + ...forms('albums', 'album', 'discography', 'lp').map((words) => ({ + words, + edge: true, + apply: (intent: SearchIntent) => { + intent.format ??= 'album'; + intent.mediaType = 'music'; + }, + })), + ...forms('manga', 'manhwa', 'manhua').map((words) => ({ + words, + edge: true, + apply: (intent: SearchIntent) => { + intent.format = 'manga'; + intent.mediaType = 'comic'; + }, + })), + + // media types + ...forms( + 'tv shows', + 'tv show', + 'tv series', + 'miniseries', + 'series', + 'shows', + 'show', + 'tv' + ).map((words) => ({ words, edge: true, apply: media('tv') })), + ...forms('movies', 'movie', 'films', 'film').map((words) => ({ + words, + edge: true, + apply: media('movie'), + })), + ...forms('books', 'book', 'novels', 'novel').map((words) => ({ + words, + edge: true, + apply: media('book'), + })), + ...forms('songs', 'song', 'tracks', 'music').map((words) => ({ + words, + edge: true, + apply: media('music'), + })), + ...forms('podcasts', 'podcast').map((words) => ({ + words, + edge: true, + apply: media('podcast'), + })), + ...forms('graphic novels', 'graphic novel', 'comics', 'comic').map( + (words) => ({ words, edge: true, apply: media('comic') }) + ), + + // roles + ...forms('actor', 'actress').map((words) => ({ + words, + edge: true, + apply: role('actor'), + })), + { words: ['director'], edge: true, apply: role('director') }, + { words: ['author'], edge: true, apply: role('author') }, + { words: ['narrator'], edge: true, apply: role('narrator') }, + ...forms('band', 'artist', 'singer', 'rapper').map((words) => ({ + words, + edge: true, + apply: role('artist'), + })), + + // genres: only at the edges ("the comedy of errors" stays a title) + ...forms('action').map((words) => ({ + words, + edge: true, + apply: genre('Action', 28, 10759), + })), + ...forms('adventure').map((words) => ({ + words, + edge: true, + apply: genre('Adventure', 12, 10759), + })), + ...forms('animated', 'animation', 'cartoon', 'cartoons').map((words) => ({ + words, + edge: true, + apply: genre('Animation', 16, 16), + })), + ...forms('comedy', 'comedies').map((words) => ({ + words, + edge: true, + apply: genre('Comedy', 35, 35), + })), + ...forms('true crime').map((words) => ({ + words, + edge: true, + apply: (intent: SearchIntent) => { + intent.genre ??= DOCUMENTARY; + intent.format ??= 'documentary'; + }, + })), + ...forms('crime').map((words) => ({ + words, + edge: true, + apply: genre('Crime', 80, 80), + })), + ...forms('drama', 'dramas').map((words) => ({ + words, + edge: true, + apply: genre('Drama', 18, 18), + })), + ...forms('family', 'kids').map((words) => ({ + words, + edge: true, + apply: genre('Family', 10751, 10751), + })), + ...forms('fantasy').map((words) => ({ + words, + edge: true, + apply: genre('Fantasy', 14, 10765), + })), + ...forms('historical').map((words) => ({ + words, + edge: true, + apply: genre('History', 36), + })), + ...forms('horror', 'scary').map((words) => ({ + words, + edge: true, + apply: genre('Horror', 27), + })), + ...forms('musical', 'musicals').map((words) => ({ + words, + edge: true, + apply: genre('Music', 10402), + })), + ...forms('mystery', 'mysteries').map((words) => ({ + words, + edge: true, + apply: genre('Mystery', 9648, 9648), + })), + ...forms('romance', 'romantic', 'romcom', 'rom com').map((words) => ({ + words, + edge: true, + apply: genre('Romance', 10749), + })), + ...forms('science fiction', 'sci fi', 'scifi').map((words) => ({ + words, + edge: true, + apply: genre('Science Fiction', 878, 10765), + })), + ...forms('thriller', 'thrillers').map((words) => ({ + words, + edge: true, + apply: genre('Thriller', 53), + })), + ...forms('war').map((words) => ({ + words, + edge: true, + apply: genre('War', 10752, 10768), + })), + ...forms('western', 'westerns').map((words) => ({ + words, + edge: true, + apply: genre('Western', 37, 37), + })), +]; +// longest phrases first so "stand up comedy" wins over "stand up" +rules.sort((left, right) => right.words.length - left.words.length); + +const DECADE_WORDS: Record = { + twenties: 1920, + thirties: 1930, + forties: 1940, + fifties: 1950, + sixties: 1960, + seventies: 1970, + eighties: 1980, + nineties: 1990, +}; + +const parseDecade = (word: string): number | undefined => { + if (DECADE_WORDS[word]) return DECADE_WORDS[word]; + const full = /^(19|20)(\d)0s$/.exec(word); + if (full) return Number(`${full[1]}${full[2]}0`); + const short = /^(\d)0s$/.exec(word); + if (short) { + const digit = Number(short[1]); + return digit <= 2 ? 2000 + digit * 10 : 1900 + digit * 10; + } + return undefined; +}; + +const LABELS: Record = { + standup: 'Stand-up specials', + documentary: 'Documentaries', + anime: 'Anime', + live: 'Live albums', + audiobook: 'Audiobooks', + ebook: 'Books', + album: 'Albums', + soundtrack: 'Soundtracks', + manga: 'Manga', +}; + +/** Parses a search query into an entity and intent hints. Pure and fast. */ +export const parseSearchIntent = (query: string): SearchIntent => { + const normalized = normalizeSearchText(query); + const words = normalized ? normalized.split(' ') : []; + const intent: SearchIntent = { + query, + normalized, + entity: normalized, + entityWords: words, + matched: [], + kind: 'title', + }; + if (words.length < 2) { + // A single word is always a title or a name: "horror" and "anime" are + // still searched as typed, and only hint the genre. + const rule = rules.find( + (candidate) => + candidate.words.length === 1 && + candidate.words[0] === words[0] && + !candidate.needsEntity + ); + if (rule) { + rule.apply(intent); + intent.matched.push(words[0]); + if (intent.format || intent.genre) intent.kind = 'discover'; + } + intent.label = intent.format ? LABELS[intent.format] : intent.genre?.name; + return intent; + } + + const removed = new Array(words.length).fill(false); + const currentYear = new Date().getFullYear(); + + // "dune by frank herbert", "movies directed by greta gerwig" + const byIndex = words.indexOf('by'); + const before = byIndex > 0 ? words[byIndex - 1] : ''; + const creatorWords = byIndex > 0 ? words.slice(byIndex + 1) : []; + // "stand by me" is a title: a bare "by" needs a two-word name after it + if ( + byIndex > 0 && + creatorWords.length > 0 && + (creatorWords.length >= 2 || + before === 'directed' || + before === 'narrated' || + before === 'written') + ) { + if (before === 'directed') { + intent.role = 'director'; + removed[byIndex - 1] = true; + } else if (before === 'narrated' || before === 'read') { + intent.role = 'narrator'; + intent.format ??= 'audiobook'; + intent.mediaType ??= 'book'; + removed[byIndex - 1] = true; + } else if (before === 'written') { + intent.role = 'author'; + removed[byIndex - 1] = true; + } + intent.creator = creatorWords.join(' '); + for (let index = byIndex; index < words.length; index++) { + removed[index] = true; + } + intent.matched.push('by'); + } + + // seasons and episodes: "season 3", "s3", "s03e04", "episode 2" + for (let index = 0; index < words.length; index++) { + if (removed[index]) continue; + const word = words[index]; + const next = words[index + 1]; + const compact = /^s(\d{1,2})(?:e(\d{1,3}))?$/.exec(word); + if (compact && index > 0) { + intent.season = Number(compact[1]); + if (compact[2]) intent.episode = Number(compact[2]); + removed[index] = true; + intent.matched.push(word); + } else if ( + (word === 'season' || word === 'series') && + next && + /^\d{1,2}$/.test(next) && + index > 0 + ) { + intent.season = Number(next); + removed[index] = removed[index + 1] = true; + intent.matched.push(`${word} ${next}`); + } else if ( + (word === 'episode' || word === 'ep') && + next && + /^\d{1,3}$/.test(next) && + index > 0 + ) { + intent.episode = Number(next); + removed[index] = removed[index + 1] = true; + intent.matched.push(`${word} ${next}`); + } + } + if (intent.season !== undefined || intent.episode !== undefined) { + intent.mediaType = 'tv'; + } + + // years and decades (a lone year stays a title: "1917") + for (let index = 0; index < words.length; index++) { + if (removed[index]) continue; + const word = words[index]; + const year = /^(19|20)\d{2}$/.test(word) ? Number(word) : undefined; + if (year && year <= currentYear + 2 && intent.year === undefined) { + intent.year = year; + removed[index] = true; + intent.matched.push(word); + continue; + } + const decade = parseDecade(word); + if (decade && !intent.decade) { + intent.decade = { start: decade, end: decade + 9 }; + removed[index] = true; + intent.matched.push(word); + } + } + + // phrase rules, longest first, on the words still left + const remaining = () => removed.filter((value) => !value).length; + const isEdge = (start: number, length: number) => { + const live = words + .map((_, index) => index) + .filter((index) => !removed[index]); + return live[0] === start || live[live.length - 1] === start + length - 1; + }; + const isEnd = (start: number, length: number) => { + const live = words + .map((_, index) => index) + .filter((index) => !removed[index]); + return live[live.length - 1] === start + length - 1; + }; + let changed = true; + let hintOnly = false; + while (changed && !hintOnly) { + changed = false; + for (const rule of rules) { + const length = rule.words.length; + for (let start = 0; start + length <= words.length; start++) { + let fits = true; + for (let offset = 0; offset < length; offset++) { + if ( + removed[start + offset] || + words[start + offset] !== rule.words[offset] + ) { + fits = false; + break; + } + } + if (!fits) continue; + // never strip every word: something must be left, or a year/decade + // or another intent must already describe the search + const leftAfter = remaining() - length; + const describedElsewhere = + intent.year !== undefined || + intent.decade !== undefined || + intent.matched.length > 0; + if (rule.needsEntity && leftAfter <= 0) continue; + if (leftAfter <= 0 && !describedElsewhere) { + // the whole query is an intent phrase ("stand up", "sci fi"): + // use it as a hint and still search the words as typed + rule.apply(intent); + intent.matched.push(rule.words.join(' ')); + hintOnly = true; + break; + } + if (rule.edge && !isEdge(start, length)) continue; + if (rule.end && !isEnd(start, length)) continue; + rule.apply(intent); + for (let offset = 0; offset < length; offset++) { + removed[start + offset] = true; + } + intent.matched.push(rule.words.join(' ')); + changed = true; + break; + } + if (changed || hintOnly) break; + } + } + + intent.entityWords = words.filter((_, index) => !removed[index]); + intent.entity = intent.entityWords.join(' '); + + const hasEntity = intent.entity.length > 0 || !!intent.creator; + if (hintOnly) { + intent.kind = intent.format || intent.genre ? 'discover' : 'title'; + } else if (intent.season !== undefined && intent.entity) { + intent.kind = 'show-season'; + } else if ( + hasEntity && + (intent.format === 'standup' || + intent.format === 'live' || + intent.format === 'audiobook' || + intent.format === 'documentary' || + intent.role !== undefined || + intent.creator !== undefined || + (intent.genre !== undefined && intent.mediaType === undefined)) + ) { + intent.kind = 'person-works'; + } else if ( + !hasEntity && + (intent.genre !== undefined || + intent.format !== undefined || + intent.year !== undefined || + intent.decade !== undefined) + ) { + intent.kind = 'discover'; + } + intent.label = intent.format + ? LABELS[intent.format] + : intent.genre + ? intent.genre.name + : undefined; + return intent; +}; + +/** Result mediaTypes that answer a media hint. */ +export const mediaTypesForHint = ( + hint?: SearchMediaHint +): string[] | undefined => { + switch (hint) { + case 'movie': + return ['movie', 'collection']; + case 'tv': + return ['tv']; + case 'book': + return ['book', 'author']; + case 'music': + return ['album', 'artist']; + case 'comic': + return ['comic']; + case 'person': + return ['person']; + default: + return undefined; + } +}; + +const DEFAULT_SECTION_ORDER = [ + 'movie', + 'tv', + 'person', + 'collection', + 'album', + 'artist', + 'book', + 'author', + 'comic', + 'magazine', +]; + +/** + * The order result sections should be shown in. What the query asked for + * comes first; everything else keeps the usual order. + */ +export const sectionOrderForIntent = (intent: SearchIntent): string[] => { + const first: string[] = []; + if (intent.format === 'standup') first.push('movie', 'tv', 'person'); + else if (intent.format === 'live' || intent.format === 'soundtrack') + first.push('album', 'artist'); + else if (intent.format === 'audiobook' || intent.format === 'ebook') + first.push('book', 'author'); + else if (intent.format === 'manga') first.push('comic'); + if (intent.role === 'author' || intent.role === 'narrator') + first.push('author', 'book'); + if (intent.role === 'artist') first.push('artist', 'album'); + if ( + intent.role === 'actor' || + intent.role === 'director' || + intent.role === 'comedian' + ) + first.push('person'); + first.push(...(mediaTypesForHint(intent.mediaType) ?? [])); + if (intent.mediaType === 'podcast') first.push('podcast'); + const seen = new Set(); + return [...first, ...DEFAULT_SECTION_ORDER].filter((type) => { + if (seen.has(type)) return false; + seen.add(type); + return true; + }); +}; + +/** The parts of an intent clients need, without internal fields. */ +export const publicSearchIntent = (intent: SearchIntent) => ({ + kind: intent.kind, + entity: intent.entity, + ...(intent.format && { format: intent.format }), + ...(intent.mediaType && { mediaType: intent.mediaType }), + ...(intent.genre && { genre: intent.genre.name }), + ...(intent.year !== undefined && { year: intent.year }), + ...(intent.decade && { decade: intent.decade }), + ...(intent.season !== undefined && { season: intent.season }), + ...(intent.episode !== undefined && { episode: intent.episode }), + ...(intent.role && { role: intent.role }), + ...(intent.creator && { creator: intent.creator }), + ...(intent.label && { label: intent.label }), + matched: intent.matched, + sections: sectionOrderForIntent(intent), +}); +export type PublicSearchIntent = ReturnType; diff --git a/server/lib/searchIntentResolver.ts b/server/lib/searchIntentResolver.ts new file mode 100644 index 0000000000..adfb9a675c --- /dev/null +++ b/server/lib/searchIntentResolver.ts @@ -0,0 +1,567 @@ +/** + * Turns a parsed search intent into extra TMDB results. + * + * person-works "nate standup": find the person the entity names (ranking + * comedians higher for stand-up), then their credits that fit + * the intent. For stand-up that is their comedy credits where + * they play themselves, plus TMDB's "stand-up comedy" keyword + * (9716) films they are credited in, plus comedy titles that + * carry their name. When no person fits, the entity is + * searched as a title and filtered by the intent instead. + * show-season "the bear season 3": the best matching series, with the + * season the client should open. + * discover "2015 horror", "80s action movies", "anime": TMDB discover + * by genre, keyword, language, year or decade. + * + * Every lookup is cached by ExternalAPI, and the whole resolver runs inside + * the TMDB provider's own deadline, so it can only add results, never delay + * or remove the plain search. + */ +import type TheMovieDb from '@server/api/themoviedb'; +import type { + TmdbMovieResult, + TmdbPersonCredit, + TmdbPersonResult, + TmdbTvResult, +} from '@server/api/themoviedb/interfaces'; +import type { SearchIntent } from '@server/lib/searchIntent'; +import { + normalizeSearchText, + textMatchScore, + tokenizeSearchText, +} from '@server/lib/searchRanking'; + +export type IntentVideoResult = (TmdbMovieResult | TmdbTvResult) & { + intentMatch: true; +}; + +export type IntentTopResult = + | { + kind: 'person'; + label?: string; + person: TmdbPersonResult; + /** Keys ("movie:123") of the person's works that fit the intent. */ + works: string[]; + } + | { + kind: 'title'; + label?: string; + mediaType: 'movie' | 'tv'; + id: number; + season?: number; + episode?: number; + }; + +export type IntentResolution = { + results: IntentVideoResult[]; + people: TmdbPersonResult[]; + topResult?: IntentTopResult; +}; + +const SELF_CHARACTER = /\b(?:him|her|them)?self\b|\bthemselves\b|^narrator$/i; + +/** + * Whether a title carries the person's whole name ("Nate Bargatze: Hello + * World" for Nate Bargatze). The surname alone is not enough: a relative's + * special ("Stephen Bargatze: Out in a Minute") shares it. + */ +const titleNamesPerson = (title: string | undefined, name: string) => { + const words = new Set(tokenizeSearchText(title ?? '')); + const parts = tokenizeSearchText(name).filter((part) => part.length > 1); + return parts.length > 0 && parts.every((part) => words.has(part)); +}; +const MIN_PERSON_MATCH = 0.6; +const MAX_WORKS = 20; + +const keyOf = (result: { media_type?: string; id: number }) => + `${result.media_type}:${result.id}`; + +const yearOf = (value?: string) => { + const year = Number(String(value ?? '').slice(0, 4)); + return Number.isInteger(year) && year > 1800 ? year : undefined; +}; + +const fitsYear = (intent: SearchIntent, date?: string) => { + if (intent.year === undefined && !intent.decade) return true; + const year = yearOf(date); + if (!year) return false; + return intent.year !== undefined + ? year === intent.year + : year >= (intent.decade as { start: number }).start && + year <= (intent.decade as { end: number }).end; +}; + +const genreIdsFor = (intent: SearchIntent) => + [intent.genre?.movieGenreId, intent.genre?.tvGenreId].filter( + (id): id is number => typeof id === 'number' + ); + +const creditToResult = ( + credit: TmdbPersonCredit +): IntentVideoResult | undefined => { + if (credit.media_type === 'movie') { + return { + id: credit.id, + media_type: 'movie', + title: credit.title, + original_title: credit.original_title ?? credit.title, + release_date: credit.release_date, + overview: credit.overview ?? '', + poster_path: credit.poster_path, + backdrop_path: credit.backdrop_path, + genre_ids: credit.genre_ids ?? [], + popularity: credit.popularity ?? 0, + vote_average: credit.vote_average ?? 0, + vote_count: credit.vote_count ?? 0, + original_language: credit.original_language ?? '', + adult: credit.adult === true, + video: credit.video === true, + intentMatch: true, + } as IntentVideoResult; + } + if (credit.media_type === 'tv') { + return { + id: credit.id, + media_type: 'tv', + name: credit.name, + original_name: credit.original_name ?? credit.name, + first_air_date: credit.first_air_date, + origin_country: credit.origin_country ?? [], + overview: credit.overview ?? '', + poster_path: credit.poster_path, + backdrop_path: credit.backdrop_path, + genre_ids: credit.genre_ids ?? [], + popularity: credit.popularity ?? 0, + vote_average: credit.vote_average ?? 0, + vote_count: credit.vote_count ?? 0, + original_language: credit.original_language ?? '', + intentMatch: true, + } as IntentVideoResult; + } + return undefined; +}; + +const looksLikeComedian = (person: TmdbPersonResult) => + (person.known_for ?? []).some( + (work) => + work.genre_ids?.includes(35) || + /stand.?up|special/i.test( + ('title' in work ? work.title : work.name) ?? '' + ) + ); + +/** + * Picks the person the entity most likely names. + * + * name fit textMatchScore of the entity against the name, 0..1; must + * reach 0.6 ("nate" fits "Nate Bargatze" at 0.875) + * comedian +0.25 for stand-up searches when their known-for titles + * include comedy or stand-up specials + * named titles +0.25 when comedy titles found for the entity carry the + * person's surname ("Nate Bargatze: Hello World") + * role +0.1 when their department fits the asked role + * fame up to +0.15 for TMDB popularity (log scale) + */ +export const pickIntentPerson = ( + entity: string, + people: readonly TmdbPersonResult[], + intent: SearchIntent, + namedTitles: readonly string[] = [] +): TmdbPersonResult | undefined => { + let best: { person: TmdbPersonResult; score: number } | undefined; + const titleWords = new Set(namedTitles.flatMap(tokenizeSearchText)); + for (const person of people) { + const nameFit = textMatchScore(entity, person.name); + if (nameFit < MIN_PERSON_MATCH) continue; + let score = nameFit; + if ( + (intent.format === 'standup' || intent.role === 'comedian') && + looksLikeComedian(person) + ) { + score += 0.25; + } + const surname = tokenizeSearchText(person.name).slice(-1)[0]; + if (surname && surname.length > 2 && titleWords.has(surname)) score += 0.25; + const department = person.known_for_department?.toLowerCase(); + if ( + (intent.role === 'director' && department === 'directing') || + ((intent.role === 'actor' || intent.role === 'comedian') && + department === 'acting') || + (intent.role === 'author' && department === 'writing') + ) { + score += 0.1; + } + score += Math.min(0.15, Math.log10(1 + (person.popularity ?? 0)) * 0.075); + if (!best || score > best.score) best = { person, score }; + } + return best?.person; +}; + +const filterCreditsForIntent = ( + intent: SearchIntent, + person: TmdbPersonResult, + credits: Awaited> +): IntentVideoResult[] => { + const genres = genreIdsFor(intent); + const isStandup = intent.format === 'standup'; + const crewJobs = + intent.role === 'director' + ? /^director$/i + : intent.role === 'author' + ? /writer|screenplay|novel|author/i + : undefined; + const pool: TmdbPersonCredit[] = [ + ...(crewJobs ? [] : credits.cast), + ...credits.crew.filter((credit) => + crewJobs + ? crewJobs.test(credit.job) + : isStandup && /writer/i.test(credit.job) + ), + ]; + const results: IntentVideoResult[] = []; + for (const credit of pool) { + if (credit.media_type !== 'movie' && credit.media_type !== 'tv') continue; + if (intent.mediaType === 'movie' && credit.media_type !== 'movie') continue; + if (intent.mediaType === 'tv' && credit.media_type !== 'tv') continue; + const date = + credit.media_type === 'movie' + ? credit.release_date + : credit.first_air_date; + if (!fitsYear(intent, date)) continue; + if (genres.length && !credit.genre_ids?.some((id) => genres.includes(id))) + continue; + if (isStandup) { + const title = normalizeSearchText(credit.title ?? credit.name); + const character = + 'character' in credit ? String(credit.character ?? '') : ''; + const order = + 'order' in credit ? (credit as { order?: number }).order : undefined; + const named = titleNamesPerson(title, person.name); + // their own special: the name is in the title, or they play themselves + // and are billed first. A guest spot in someone else's special ("Self", + // billed lower), or one they only wrote, is not theirs. A long-running + // sitcom they appear in as "Self" once is not a special either, so TV + // needs the name in the title. + const headlines = SELF_CHARACTER.test(character) && order === 0; + if ( + credit.media_type === 'tv' || !('character' in credit) + ? !named + : !(named || headlines) + ) + continue; + } + const result = creditToResult(credit); + if (result) results.push(result); + } + return results; +}; + +const byNewest = (left: IntentVideoResult, right: IntentVideoResult) => { + const leftDate = + 'release_date' in left ? left.release_date : left.first_air_date; + const rightDate = + 'release_date' in right ? right.release_date : right.first_air_date; + return String(rightDate ?? '').localeCompare(String(leftDate ?? '')); +}; + +const byPopularity = (left: IntentVideoResult, right: IntentVideoResult) => + (right.popularity ?? 0) - (left.popularity ?? 0); + +const dedupe = (results: IntentVideoResult[]) => { + const seen = new Set(); + return results.filter((result) => { + const key = keyOf(result); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +}; + +const settle = async (promise: Promise, fallback: T): Promise => { + try { + return await promise; + } catch { + return fallback; + } +}; + +const emptyPage = { page: 1, total_pages: 1, total_results: 0, results: [] }; + +type ResolveOptions = { + language?: string; + moviesEnabled: boolean; + seriesEnabled: boolean; +}; + +const resolvePersonWorks = async ( + tmdb: TheMovieDb, + intent: SearchIntent, + { language, moviesEnabled, seriesEnabled }: ResolveOptions +): Promise => { + const name = intent.creator ?? intent.entity; + const isStandup = intent.format === 'standup'; + const [people, titleSearch] = await Promise.all([ + settle(tmdb.searchPeople({ query: name, language }), emptyPage), + // for stand-up the specials usually carry the comedian's name, so a + // title search for the entity finds them even when the person search + // ranks someone else first + isStandup && moviesEnabled + ? settle(tmdb.searchMovies({ query: name, language }), emptyPage) + : intent.creator + ? Promise.resolve(emptyPage) + : settle( + tmdb.searchMulti({ query: intent.entity, language }), + emptyPage + ), + ]); + const genres = genreIdsFor(intent); + const namedComedy = isStandup + ? (titleSearch.results as TmdbMovieResult[]).filter( + (movie) => + movie.genre_ids?.includes(35) && + textMatchScore(name, movie.title) >= 0.5 + ) + : []; + const person = pickIntentPerson( + name, + people.results, + intent, + namedComedy.map((movie) => movie.title) + ); + + if (!person) { + // no person fits: search the entity as a title and keep what fits + const titles = ( + titleSearch.results as (TmdbMovieResult | TmdbTvResult)[] + ).filter( + (result) => + (result.media_type === 'movie' || + result.media_type === 'tv' || + isStandup) && + (!genres.length || + result.genre_ids?.some((id) => genres.includes(id))) && + fitsYear( + intent, + 'release_date' in result ? result.release_date : result.first_air_date + ) + ); + return { + results: titles.map( + (result) => + ({ + ...result, + media_type: result.media_type ?? 'movie', + intentMatch: true, + }) as IntentVideoResult + ), + people: [], + }; + } + + const [credits, keywordFilms] = await Promise.all([ + settle(tmdb.getPersonCombinedCredits({ personId: person.id, language }), { + id: person.id, + cast: [], + crew: [], + }), + isStandup && moviesEnabled && intent.keywordId + ? settle( + tmdb.getDiscoverMovies({ + keywords: String(intent.keywordId), + people: String(person.id), + language, + }), + emptyPage + ) + : Promise.resolve(emptyPage), + ]); + const works = dedupe([ + ...filterCreditsForIntent(intent, person, credits), + // TMDB's people filter also matches crew (a special they produced for + // another comedian), so keyword films need their name in the title + ...(keywordFilms.results as TmdbMovieResult[]) + .filter((movie) => titleNamesPerson(movie.title, person.name)) + .map( + (movie) => + ({ + ...movie, + media_type: 'movie', + intentMatch: true, + }) as IntentVideoResult + ), + ...namedComedy + .filter((movie) => titleNamesPerson(movie.title, person.name)) + .map( + (movie) => + ({ + ...movie, + media_type: 'movie', + intentMatch: true, + }) as IntentVideoResult + ), + ]) + .filter( + (result) => + (result.media_type !== 'movie' || moviesEnabled) && + (result.media_type !== 'tv' || seriesEnabled) + ) + .sort(isStandup ? byNewest : byPopularity) + .slice(0, MAX_WORKS); + + return { + results: works, + people: [person], + topResult: { + kind: 'person', + label: intent.label, + person, + works: works.map(keyOf), + }, + }; +}; + +const resolveShowSeason = async ( + tmdb: TheMovieDb, + intent: SearchIntent, + { language }: ResolveOptions +): Promise => { + const shows = await settle( + tmdb.searchTvShows({ query: intent.entity, language }), + emptyPage + ); + const show = [...(shows.results as TmdbTvResult[])] + .map((result, index) => ({ + result, + score: + textMatchScore(intent.entity, result.name) * 10 + + Math.log10(1 + (result.popularity ?? 0)) - + index * 0.1, + })) + .sort((left, right) => right.score - left.score)[0]?.result; + if (!show || textMatchScore(intent.entity, show.name) < 0.6) { + return { results: [], people: [] }; + } + return { + results: [{ ...show, media_type: 'tv', intentMatch: true }], + people: [], + topResult: { + kind: 'title', + label: + intent.season !== undefined ? `Season ${intent.season}` : undefined, + mediaType: 'tv', + id: show.id, + season: intent.season, + episode: intent.episode, + }, + }; +}; + +const resolveDiscover = async ( + tmdb: TheMovieDb, + intent: SearchIntent, + { language, moviesEnabled, seriesEnabled }: ResolveOptions +): Promise => { + const yearStart = intent.year ?? intent.decade?.start; + const yearEnd = intent.year ?? intent.decade?.end; + const wantsMovies = + moviesEnabled && + intent.mediaType !== 'tv' && + !!(intent.genre?.movieGenreId || intent.keywordId || yearStart); + const wantsTv = + seriesEnabled && + intent.mediaType !== 'movie' && + intent.format !== 'standup' && + !!intent.genre?.tvGenreId; + if (!wantsMovies && !wantsTv) return { results: [], people: [] }; + const [movies, shows] = await Promise.all([ + wantsMovies + ? settle( + tmdb.getDiscoverMovies({ + genre: intent.genre?.movieGenreId + ? String(intent.genre.movieGenreId) + : undefined, + keywords: intent.keywordId ? String(intent.keywordId) : undefined, + originalLanguage: intent.originalLanguage, + primaryReleaseDateGte: yearStart ? `${yearStart}-01-01` : undefined, + primaryReleaseDateLte: yearEnd ? `${yearEnd}-12-31` : undefined, + voteCountGte: '20', + language, + }), + emptyPage + ) + : Promise.resolve(emptyPage), + wantsTv + ? settle( + tmdb.getDiscoverTv({ + genre: String(intent.genre?.tvGenreId), + originalLanguage: intent.originalLanguage, + firstAirDateGte: yearStart ? `${yearStart}-01-01` : undefined, + firstAirDateLte: yearEnd ? `${yearEnd}-12-31` : undefined, + voteCountGte: '20', + language, + }), + emptyPage + ) + : Promise.resolve(emptyPage), + ]); + return { + results: [ + ...(movies.results as TmdbMovieResult[]).map( + (movie) => + ({ + ...movie, + media_type: 'movie', + intentMatch: true, + }) as IntentVideoResult + ), + ...(shows.results as TmdbTvResult[]).map( + (show) => + ({ + ...show, + media_type: 'tv', + intentMatch: true, + }) as IntentVideoResult + ), + ] + .sort(byPopularity) + .slice(0, MAX_WORKS), + people: [], + }; +}; + +/** Whether the intent needs any TMDB lookups beyond the plain search. */ +export const intentNeedsVideoLookup = (intent: SearchIntent) => + (intent.kind === 'person-works' && + intent.format !== 'live' && + intent.format !== 'audiobook' && + intent.format !== 'ebook' && + intent.format !== 'soundtrack' && + intent.format !== 'album' && + intent.role !== 'author' && + intent.role !== 'narrator' && + intent.role !== 'artist' && + intent.mediaType !== 'book' && + intent.mediaType !== 'music' && + intent.mediaType !== 'comic' && + intent.mediaType !== 'podcast') || + intent.kind === 'show-season' || + (intent.kind === 'discover' && + intent.mediaType !== 'book' && + intent.mediaType !== 'music' && + intent.mediaType !== 'comic' && + intent.mediaType !== 'podcast'); + +export const resolveVideoIntent = async ( + tmdb: TheMovieDb, + intent: SearchIntent, + options: ResolveOptions +): Promise => { + if (!intentNeedsVideoLookup(intent)) return { results: [], people: [] }; + if (intent.kind === 'show-season') { + return options.seriesEnabled + ? resolveShowSeason(tmdb, intent, options) + : { results: [], people: [] }; + } + if (intent.kind === 'discover') return resolveDiscover(tmdb, intent, options); + return resolvePersonWorks(tmdb, intent, options); +}; diff --git a/server/lib/searchProviderCache.ts b/server/lib/searchProviderCache.ts new file mode 100644 index 0000000000..dc05801c70 --- /dev/null +++ b/server/lib/searchProviderCache.ts @@ -0,0 +1,72 @@ +/** + * Short-lived cache for search provider answers. + * + * TMDB, MusicBrainz and Open Library already cache through ExternalAPI. The + * local catalogs (Bookshelf, LazyLibrarian) and ComicVine/Metron do not, and + * they are the slow ones: a busy Bookshelf can take 5 s or more per lookup. + * + * - Answers are kept for a short time (2 minutes by default), so the streamed + * search, the classic search and a Retry right after share one lookup. + * - Concurrent identical lookups share one in-flight promise. + * - A lookup that outlives the search that started it keeps running and its + * answer still lands here, so the next keystroke or Retry gets it at once. + * - Failures are not cached. + */ +import { createHash } from 'node:crypto'; + +export const SEARCH_PROVIDER_CACHE_TTL_MS = 2 * 60 * 1000; +const MAX_ENTRIES = 500; + +type Entry = { expiresAt: number; value: unknown }; + +const settled = new Map(); +const inFlight = new Map>(); + +const keyFor = (provider: string, args: unknown) => + `${provider}:${createHash('sha256').update(JSON.stringify(args)).digest('hex')}`; + +const prune = (now: number) => { + for (const [key, entry] of settled) { + if (entry.expiresAt <= now) settled.delete(key); + } + // Map keeps insertion order: drop the oldest when still over the cap + while (settled.size > MAX_ENTRIES) { + const oldest = settled.keys().next().value; + if (oldest === undefined) break; + settled.delete(oldest); + } +}; + +export const cachedSearchProvider = ( + provider: string, + args: unknown, + lookup: () => Promise, + ttlMs = SEARCH_PROVIDER_CACHE_TTL_MS +): Promise => { + const key = keyFor(provider, args); + const now = Date.now(); + const hit = settled.get(key); + if (hit && hit.expiresAt > now) return Promise.resolve(hit.value as T); + const pending = inFlight.get(key); + if (pending) return pending as Promise; + const promise = lookup().then( + (value) => { + inFlight.delete(key); + settled.set(key, { value, expiresAt: Date.now() + ttlMs }); + prune(Date.now()); + return value; + }, + (error: unknown) => { + inFlight.delete(key); + throw error; + } + ); + inFlight.set(key, promise); + return promise; +}; + +/** For tests. */ +export const clearSearchProviderCache = () => { + settled.clear(); + inFlight.clear(); +}; diff --git a/server/lib/searchRanking.test.ts b/server/lib/searchRanking.test.ts new file mode 100644 index 0000000000..ab597ac32e --- /dev/null +++ b/server/lib/searchRanking.test.ts @@ -0,0 +1,167 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + dedupeSearchResults, + editDistance, + normalizeSearchText, + rankSearchResults, + scoreSearchResult, + textMatchScore, + wordMatchScore, +} from '@server/lib/searchRanking'; + +describe('search text matching', () => { + it('normalizes accents, apostrophes and punctuation', () => { + assert.equal( + normalizeSearchText(' Pokémon: Bargatze’s Stand-Up! '), + 'pokemon bargatzes stand up' + ); + assert.equal(normalizeSearchText('Tom & Jerry'), 'tom and jerry'); + }); + + it('counts adjacent swaps as one edit and stops early', () => { + assert.equal(editDistance('bargatze', 'bargatze'), 0); + assert.equal(editDistance('bergatze', 'bargatze'), 1); + assert.equal(editDistance('bragatze', 'bargatze'), 1); + assert.equal(editDistance('nate', 'bargatze', 2), 3); + }); + + it('scores words by exact, prefix and typo matches', () => { + assert.equal(wordMatchScore('nate', 'nate'), 1); + assert.equal(wordMatchScore('barg', 'bargatze'), 0.9); + assert.equal(wordMatchScore('bergatze', 'bargatze'), 0.8); + assert.equal(wordMatchScore('bergat', 'bargatze'), 0.65); + assert.equal(wordMatchScore('cat', 'cut'), 0, 'short words need exact'); + }); + + it('finds a name from a partial, misspelled or reordered query', () => { + const name = 'Nate Bargatze'; + for (const query of [ + 'bargatze', + 'nate barg', + 'bergatze', + 'Bargatze Nate', + ]) { + assert.ok( + textMatchScore(query, name) >= 0.7, + `${query} → ${textMatchScore(query, name)}` + ); + } + assert.equal(textMatchScore('nate bargatze', name), 1); + assert.ok( + textMatchScore('nate barg', name) > + textMatchScore('nate barg', 'Nate Diaz') + ); + assert.ok(textMatchScore('bergatze', 'Nate Diaz') < 0.3); + }); + + it('prefers an exact title over a longer one and ignores articles', () => { + assert.equal(textMatchScore('office', 'The Office'), 0.97); + assert.ok( + textMatchScore('the office', 'The Office') > + textMatchScore('the office', 'The Office Christmas Party') + ); + assert.ok(textMatchScore('the off', 'The Office') >= 0.9); + }); +}); + +describe('search result ranking', () => { + it('puts exact titles first, then owned, then popular', () => { + const context = { query: 'dune' }; + const exact = scoreSearchResult( + { mediaType: 'movie', title: 'Dune', popularity: 5 }, + context, + 3 + ); + const popular = scoreSearchResult( + { mediaType: 'movie', title: 'Dune: Part Two', popularity: 400 }, + context, + 0 + ); + assert.ok(exact > popular, `${exact} vs ${popular}`); + + const owned = scoreSearchResult( + { mediaType: 'movie', title: 'Dune', mediaInfo: { status: 5 } }, + context, + 1 + ); + const notOwned = scoreSearchResult( + { mediaType: 'movie', title: 'Dune' }, + context, + 0 + ); + assert.ok(owned > notOwned); + }); + + it('boosts results the intent lookup found and that fit the genre or year', () => { + const context = { + query: 'nate standup', + entity: 'nate', + genreIds: [35], + }; + const special = scoreSearchResult( + { + mediaType: 'movie', + title: 'Nate Bargatze: Hello World', + genreIds: [35], + intentMatch: true, + }, + context, + 5 + ); + const other = scoreSearchResult( + { mediaType: 'movie', title: 'Nate', genreIds: [18] }, + context, + 0 + ); + assert.ok(special > other, `${special} vs ${other}`); + const horror = { query: 'horror', genreIds: [27], year: 2015 }; + assert.ok( + scoreSearchResult( + { + mediaType: 'movie', + title: 'It Follows', + genreIds: [27], + releaseDate: '2015-02-01', + }, + horror + ) > + scoreSearchResult( + { + mediaType: 'movie', + title: 'It Follows', + genreIds: [27], + releaseDate: '2014-02-01', + }, + horror + ) + ); + }); + + it('sorts within each media type and keeps the type slots', () => { + const ranked = rankSearchResults( + [ + { id: 1, mediaType: 'movie', title: 'Dune: Part Two' }, + { id: 2, mediaType: 'person', name: 'Dune Person' }, + { id: 3, mediaType: 'movie', title: 'Dune' }, + ], + { query: 'dune' } + ); + assert.deepEqual( + ranked.map((result) => `${result.mediaType}:${result.id}`), + ['movie:3', 'person:2', 'movie:1'] + ); + assert.ok(ranked.every((result) => typeof result.matchScore === 'number')); + }); + + it('dedupes across providers and keeps the intent flag', () => { + const deduped = dedupeSearchResults([ + { id: 1, mediaType: 'movie', title: 'A' }, + { id: 1, mediaType: 'tv', title: 'A show' }, + { id: 1, mediaType: 'movie', title: 'A', intentMatch: true }, + ]); + assert.equal(deduped.length, 2); + assert.equal(deduped[0].intentMatch, true); + }); +}); diff --git a/server/lib/searchRanking.ts b/server/lib/searchRanking.ts new file mode 100644 index 0000000000..1640485d77 --- /dev/null +++ b/server/lib/searchRanking.ts @@ -0,0 +1,425 @@ +/** + * Text matching and result ranking for global search. + * + * Providers (TMDB, MusicBrainz, Open Library, Bookshelf, ComicVine) each rank + * their own answers, but they disagree about what a good match is and none of + * them knows what the household already owns. This module gives every result + * one comparable score so the server can order each section and pick a "Top + * result" card. + * + * Everything here is synchronous and allocation-light: it runs on every search + * response and on every autocomplete keystroke. + */ + +/** Lowercase, strip accents and punctuation, collapse whitespace. */ +export const normalizeSearchText = (value: unknown): string => + typeof value !== 'string' && typeof value !== 'number' + ? '' + : String(value) + .normalize('NFKD') + .replace(/\p{M}/gu, '') + .toLocaleLowerCase() + // "Bargatze's" and "Bargatze’s" both become "bargatzes" + .replace(/['‘’ʼ]/gu, '') + .replace(/&/g, ' and ') + .replace(/[^\p{L}\p{N}]+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(); + +export const tokenizeSearchText = (value: unknown): string[] => { + const normalized = normalizeSearchText(value); + return normalized ? normalized.split(' ') : []; +}; + +const LEADING_ARTICLE = /^(?:the|a|an) /; + +/** + * Optimal string alignment distance (Levenshtein plus adjacent swaps, so + * "bragatze" is one edit from "bargatze"). Stops early and returns + * `max + 1` once the distance is known to exceed `max`. + */ +export const editDistance = (left: string, right: string, max = 2): number => { + if (left === right) return 0; + if (Math.abs(left.length - right.length) > max) return max + 1; + if (!left.length) return right.length; + if (!right.length) return left.length; + let previousPrevious: number[] = []; + let previous = Array.from({ length: right.length + 1 }, (_, i) => i); + for (let i = 1; i <= left.length; i++) { + const current = [i]; + let rowMin = i; + for (let j = 1; j <= right.length; j++) { + const cost = left[i - 1] === right[j - 1] ? 0 : 1; + let value = Math.min( + previous[j] + 1, + current[j - 1] + 1, + previous[j - 1] + cost + ); + if ( + i > 1 && + j > 1 && + left[i - 1] === right[j - 2] && + left[i - 2] === right[j - 1] + ) { + value = Math.min(value, previousPrevious[j - 2] + 1); + } + current[j] = value; + if (value < rowMin) rowMin = value; + } + if (rowMin > max) return max + 1; + previousPrevious = previous; + previous = current; + } + return previous[right.length]; +}; + +/** How many typos a word of this length may carry and still count. */ +export const allowedTypos = (length: number): number => + length <= 3 ? 0 : length <= 6 ? 1 : 2; + +/** + * Scores one query word against one candidate word, 0..1. + * + * - 1.00 the same word + * - 0.90 the candidate starts with the query word ("barg" → "bargatze"), so a + * name can be found while it is still being typed + * - 0.80 / 0.70 one or two typos ("bergatze" → "bargatze") + * - 0.65 a typo inside a prefix ("bergat" → "bargatze") + * - 0 otherwise + */ +export const wordMatchScore = (query: string, candidate: string): number => { + if (!query || !candidate) return 0; + if (query === candidate) return 1; + if (query.length >= 2 && candidate.startsWith(query)) return 0.9; + // a short query word may also be a plural or possessive of the candidate + if ( + candidate.length >= 3 && + query.startsWith(candidate) && + query.length - candidate.length <= 2 + ) { + return 0.85; + } + const typos = allowedTypos(query.length); + if (!typos) return 0; + const distance = editDistance(query, candidate, typos); + if (distance <= typos) return distance === 1 ? 0.8 : 0.7; + if (query.length >= 5 && candidate.length > query.length) { + const prefix = candidate.slice(0, query.length); + if (editDistance(query, prefix, 1) <= 1) return 0.65; + } + return 0; +}; + +/** + * Scores how well a candidate title or name answers a query, 0..1. + * + * - 1.00 exact (after normalization) + * - 0.97 exact once a leading "The/A/An" is ignored on either side + * - 0.92 the title starts with the whole query ("the off" → "The Office") + * - 0.50–0.90 every query word is found in the title (exactly, as a prefix, + * or with a typo); the average word score drives it, a small bonus is given + * when the words appear in order, and a small penalty for each title word + * the query did not mention ("nate" fits "Nate Bargatze" better than + * "Nate Bargatze: The Tennessee Kid") + * - up to 0.45 only some query words are found + * - 0.60 the query appears inside the title without word boundaries + */ +export const textMatchScore = (query: unknown, candidate: unknown): number => { + const q = normalizeSearchText(query); + const c = normalizeSearchText(candidate); + if (!q || !c) return 0; + if (q === c) return 1; + const qBare = q.replace(LEADING_ARTICLE, ''); + const cBare = c.replace(LEADING_ARTICLE, ''); + if (qBare && qBare === cBare) return 0.97; + let best = 0; + if (c.startsWith(q) || (qBare.length >= 3 && cBare.startsWith(qBare))) { + best = 0.92; + } + + const queryWords = q.split(' '); + const candidateWords = c.split(' '); + const used = new Set(); + let total = 0; + let matched = 0; + let inOrder = true; + let lastIndex = -1; + for (const word of queryWords) { + let wordBest = 0; + let wordIndex = -1; + for (let index = 0; index < candidateWords.length; index++) { + if (used.has(index)) continue; + const score = wordMatchScore(word, candidateWords[index]); + if (score > wordBest) { + wordBest = score; + wordIndex = index; + if (score === 1) break; + } + } + if (wordIndex >= 0) { + used.add(wordIndex); + matched++; + total += wordBest; + if (wordIndex < lastIndex) inOrder = false; + lastIndex = wordIndex; + } + } + if (matched === queryWords.length) { + const average = total / queryWords.length; + const extraWords = Math.max(0, candidateWords.length - queryWords.length); + const score = + 0.5 + + 0.4 * average + + (inOrder && queryWords.length > 1 ? 0.03 : 0) - + Math.min(0.12, 0.03 * extraWords); + best = Math.max(best, Math.min(0.9, score)); + } else if (matched > 0) { + best = Math.max( + best, + 0.45 * (matched / queryWords.length) * (total / matched) + ); + } + if (q.length >= 3 && c.includes(q)) best = Math.max(best, 0.6); + return best; +}; + +/** Best score of the query against any of the candidate's names. */ +export const bestTextMatch = ( + queries: readonly string[], + names: readonly unknown[] +): number => { + let best = 0; + for (const query of queries) { + if (!query) continue; + for (const name of names) { + const score = textMatchScore(query, name); + if (score > best) best = score; + if (best === 1) return 1; + } + } + return best; +}; + +/** Fields every ranked result may carry (search results are loosely typed). */ +export type RankableResult = { + id?: string | number; + mediaType?: string; + title?: string; + name?: string; + originalTitle?: string; + originalName?: string; + author?: string; + releaseDate?: string; + firstAirDate?: string; + 'first-release-date'?: string; + firstPublishYear?: number; + genreIds?: number[]; + popularity?: number; + score?: number; + mediaInfo?: { status?: number; status4k?: number } | null; + ownedTrackCount?: number; + owned?: boolean; + intentMatch?: boolean; +}; + +export type RankingContext = { + /** The query as typed. */ + query: string; + /** The query without its intent words ("nate" for "nate standup"). */ + entity?: string; + /** Media type the query asked for, as a result mediaType list. */ + mediaTypes?: readonly string[]; + /** TMDB genre ids the query asked for (movie and TV ids). */ + genreIds?: readonly number[]; + year?: number; + decade?: { start: number; end: number }; +}; + +// MediaStatus values, repeated here so this module stays dependency free +const STATUS_AVAILABLE = 5; +const STATUS_PARTIALLY_AVAILABLE = 4; +const STATUS_PROCESSING = 3; +const STATUS_PENDING = 2; + +const resultNames = (result: RankableResult): unknown[] => [ + result.title, + result.name, + result.originalTitle, + result.originalName, +]; + +const resultYear = (result: RankableResult): number | undefined => { + const raw = + result.releaseDate ?? + result.firstAirDate ?? + result['first-release-date'] ?? + result.firstPublishYear; + const year = Number(String(raw ?? '').slice(0, 4)); + return Number.isInteger(year) && year > 1800 ? year : undefined; +}; + +const availabilityScore = (result: RankableResult): number => { + const status = Math.max( + result.mediaInfo?.status ?? 0, + result.mediaInfo?.status4k ?? 0 + ); + if (status === STATUS_AVAILABLE || result.owned) return 1; + if ( + status === STATUS_PARTIALLY_AVAILABLE || + (result.ownedTrackCount ?? 0) > 0 + ) + return 0.7; + if (status === STATUS_PROCESSING || status === STATUS_PENDING) return 0.3; + return 0; +}; + +const popularityScore = (result: RankableResult): number => { + if (typeof result.popularity === 'number' && result.popularity > 0) { + // TMDB popularity is open ended: 1 is obscure, 10 known, 100+ a hit. + return Math.min(1, Math.log10(1 + result.popularity) / 2); + } + if (typeof result.score === 'number' && result.score > 0) { + // MusicBrainz search score, 0..100; it measures text fit, not fame, so + // it counts for half. + return Math.min(1, result.score / 100) * 0.5; + } + return 0; +}; + +const intentFitScore = ( + result: RankableResult, + context: RankingContext +): number => { + let fit = result.intentMatch ? 1 : 0; + if (context.mediaTypes?.length && result.mediaType) { + if (context.mediaTypes.includes(result.mediaType)) fit += 0.4; + } + if (context.genreIds?.length && result.genreIds?.length) { + if (result.genreIds.some((id) => context.genreIds?.includes(id))) + fit += 0.4; + } + if (context.year || context.decade) { + const year = resultYear(result); + if ( + year && + (year === context.year || + (context.decade && + year >= context.decade.start && + year <= context.decade.end)) + ) { + fit += 0.4; + } + } + return Math.min(1, fit); +}; + +/** + * One comparable score per result, 0..100. + * + * text fit 55 points (45 when the query carries intent words): best of + * the typed query and the intent-free entity against title / + * name / original title. It dominates so a good title match + * beats a merely popular one. + * exact 8 bonus points when the title is exactly what was typed, so + * "dune" puts Dune above the more popular Dune: Part Two. + * intent fit 15 points (25 with intent words): the result came from the + * intent lookup (a comedian's stand-up specials for "nate + * standup"), or matches the media type, genre, year or decade + * the query asked for. With intent words the typed query fits + * nothing well, so fitting the intent has to count for more + * than a title that happens to equal the entity ("Nate"). + * owned 10 points: already in the library (available > partly + * available > requested), so what can be played now rises. + * popularity 7 points: TMDB popularity on a log scale, or half the + * MusicBrainz score when that is all there is. + * provider 5 points: the provider's own order, as a tie breaker; + * position 0 earns all 5, position 40 and later nothing. + */ +export const scoreSearchResult = ( + result: RankableResult, + context: RankingContext, + providerPosition = 0 +): number => { + const typed = normalizeSearchText(context.query); + const hasIntentWords = !!context.entity && context.entity !== typed; + const names = resultNames(result); + const typedFit = bestTextMatch([typed], names); + const text = hasIntentWords + ? Math.max(typedFit, bestTextMatch([context.entity as string], names)) + : typedFit; + const prior = Math.max(0, 1 - providerPosition / 40); + return ( + (hasIntentWords ? 45 : 55) * text + + (typedFit >= 0.97 ? 8 : 0) + + (hasIntentWords ? 25 : 15) * intentFitScore(result, context) + + 10 * availabilityScore(result) + + 7 * popularityScore(result) + + 5 * prior + ); +}; + +const resultKey = (result: RankableResult) => + `${result.mediaType ?? ''}:${String(result.id ?? '')}`; + +/** + * Removes repeated results (the same TMDB title found by the plain search and + * by the intent lookup, for example). The first copy wins, but it inherits + * `intentMatch` from a later copy. + */ +export const dedupeSearchResults = ( + results: readonly T[] +): T[] => { + const byKey = new Map(); + const ordered: T[] = []; + for (const result of results) { + const key = resultKey(result); + const existing = byKey.get(key); + if (!existing) { + byKey.set(key, result); + ordered.push(result); + } else if (result.intentMatch && !existing.intentMatch) { + existing.intentMatch = true; + } + } + return ordered; +}; + +/** + * Orders each media type's results by score while keeping the slots each type + * occupies, so clients that render the list in order see the same mix of + * types as before but the best movie first among movies, the best album first + * among albums, and so on. Adds `matchScore` (0..100, rounded) to each result. + */ +export const rankSearchResults = ( + results: readonly T[], + context: RankingContext +): (T & { matchScore: number })[] => { + const positions = new Map(); + const scored = results.map((result) => { + const type = result.mediaType ?? ''; + const position = positions.get(type) ?? 0; + positions.set(type, position + 1); + return { + ...result, + matchScore: Math.round(scoreSearchResult(result, context, position)), + }; + }); + const byType = new Map(); + for (const result of scored) { + const type = result.mediaType ?? ''; + const list = byType.get(type) ?? []; + list.push(result); + byType.set(type, list); + } + for (const list of byType.values()) { + // Array.prototype.sort is stable: equal scores keep the provider order + list.sort((left, right) => right.matchScore - left.matchScore); + } + const cursor = new Map(); + return scored.map((result) => { + const type = result.mediaType ?? ''; + const index = cursor.get(type) ?? 0; + cursor.set(type, index + 1); + return (byType.get(type) as (T & { matchScore: number })[])[index]; + }); +}; diff --git a/server/lib/searchSuggest.ts b/server/lib/searchSuggest.ts new file mode 100644 index 0000000000..f84722c900 --- /dev/null +++ b/server/lib/searchSuggest.ts @@ -0,0 +1,427 @@ +/** + * In-memory index behind search suggestions (autocomplete) and "did you + * mean" corrections. Answers come from memory only, so they are fast enough + * to run on every keystroke. + * + * Sources, best first: + * library titles the household has (MediaSearchMetadata joined to Media): + * their titles, creators, artists and authors. Loaded on first + * use and refreshed every 15 minutes in the background. + * learned titles and people seen in recent search answers (TMDB, + * MusicBrainz, books, authors). What anyone searched for recently + * becomes suggestable, typos included. Capped, oldest dropped. + * popular TMDB trending titles and people, refreshed hourly. + * + * The vocabulary of every indexed word doubles as the dictionary for "did + * you mean": a query word the index does not know is replaced by the closest + * known word within the allowed typos ("bergatze" → "bargatze"). + */ +import { MediaStatus, MediaType } from '@server/constants/media'; +import { getRepository } from '@server/datasource'; +import { MediaSearchMetadata } from '@server/entity/MediaSearchMetadata'; +import { + allowedTypos, + editDistance, + normalizeSearchText, + textMatchScore, + tokenizeSearchText, +} from '@server/lib/searchRanking'; +import logger from '@server/logger'; + +export type SuggestMediaType = + | 'movie' + | 'tv' + | 'person' + | 'collection' + | 'album' + | 'artist' + | 'book' + | 'author' + | 'comic'; + +export type SuggestEntry = { + mediaType: SuggestMediaType; + id: string | number; + title: string; + year?: string; + posterPath?: string; + subtitle?: string; + popularity: number; + owned: boolean; + source: 'library' | 'learned' | 'popular'; + /** People: their department ("Acting") and whether they do comedy. */ + department?: string; + comedian?: boolean; + /** TMDB maturity: never suggested. */ + adult?: boolean; +}; + +type IndexedEntry = SuggestEntry & { + key: string; + norm: string; + words: string[]; + seenAt: number; +}; + +const LIBRARY_REFRESH_MS = 15 * 60 * 1000; +const POPULAR_REFRESH_MS = 60 * 60 * 1000; +const MAX_LEARNED = 5_000; +const MAX_LIBRARY = 25_000; + +const library = new Map(); +const learned = new Map(); +const popular = new Map(); +// first letter of each word → entries, so a lookup scores a few hundred +// entries instead of every one +const buckets = new Map>(); +const vocabulary = new Map(); +let libraryLoadedAt = 0; +let libraryLoading: Promise | undefined; +let popularLoadedAt = 0; + +const keyOf = (entry: Pick) => + `${entry.mediaType}:${entry.id}`; + +const addToBuckets = (entry: IndexedEntry) => { + for (const word of new Set(entry.words)) { + const letter = word[0]; + if (!letter) continue; + let bucket = buckets.get(letter); + if (!bucket) { + bucket = new Set(); + buckets.set(letter, bucket); + } + bucket.add(entry); + vocabulary.set(word, (vocabulary.get(word) ?? 0) + 1); + } +}; + +const removeFromBuckets = (entry: IndexedEntry) => { + for (const word of new Set(entry.words)) { + buckets.get(word[0])?.delete(entry); + const count = (vocabulary.get(word) ?? 1) - 1; + if (count <= 0) vocabulary.delete(word); + else vocabulary.set(word, count); + } +}; + +const index = ( + store: Map, + entry: SuggestEntry, + extraWords: string[] = [] +) => { + const title = entry.title?.trim(); + if (!title || entry.adult) return; + const key = keyOf(entry); + const existing = store.get(key); + if (existing) removeFromBuckets(existing); + const norm = normalizeSearchText(title); + if (!norm) return; + const indexed: IndexedEntry = { + ...entry, + title, + key, + norm, + words: [...norm.split(' '), ...extraWords.flatMap(tokenizeSearchText)], + seenAt: Date.now(), + // keep what an earlier sighting knew + owned: entry.owned || !!existing?.owned, + comedian: entry.comedian || existing?.comedian, + }; + store.delete(key); + store.set(key, indexed); + addToBuckets(indexed); +}; + +/** Remembers titles and people from a search answer. */ +export const learnSearchResults = ( + results: readonly Record[] +) => { + for (const result of results) { + const mediaType = result.mediaType as SuggestMediaType | undefined; + if (!mediaType || result.adult === true) continue; + const id = result.id as string | number | undefined; + if (id === undefined || id === null || id === '') continue; + const title = String(result.title ?? result.name ?? ''); + if (!title) continue; + const date = String( + result.releaseDate ?? + result.firstAirDate ?? + result['first-release-date'] ?? + result.firstPublishYear ?? + '' + ); + const mediaInfo = result.mediaInfo as { status?: number } | undefined; + const knownFor = Array.isArray(result.knownFor) + ? (result.knownFor as { + genreIds?: number[]; + title?: string; + name?: string; + }[]) + : []; + const artistCredit = Array.isArray(result['artist-credit']) + ? (result['artist-credit'] as { name?: string }[]) + .map((credit) => credit.name) + .filter(Boolean) + .join(', ') + : undefined; + index(learned, { + mediaType, + id, + title, + year: /^\d{4}/.test(date) ? date.slice(0, 4) : undefined, + posterPath: (result.posterPath ?? result.profilePath) as + string | undefined, + subtitle: + mediaType === 'person' + ? knownFor + .slice(0, 2) + .map((work) => work.title ?? work.name) + .filter(Boolean) + .join(', ') || undefined + : ((result.author as string | undefined) ?? artistCredit), + popularity: Number(result.popularity ?? 0) || 0, + owned: + mediaInfo?.status === MediaStatus.AVAILABLE || + mediaInfo?.status === MediaStatus.PARTIALLY_AVAILABLE || + result.owned === true, + source: 'learned', + department: result.knownForDepartment as string | undefined, + comedian: + mediaType === 'person' && + knownFor.some( + (work) => + work.genreIds?.includes(35) || + /stand.?up|special/i.test(work.title ?? work.name ?? '') + ), + }); + while (learned.size > MAX_LEARNED) { + const oldest = learned.values().next().value; + if (!oldest) break; + learned.delete(oldest.key); + removeFromBuckets(oldest); + } + } +}; + +/** Seeds trending titles and people (called with TMDB trending results). */ +export const setPopularEntries = (entries: readonly SuggestEntry[]) => { + for (const entry of popular.values()) removeFromBuckets(entry); + popular.clear(); + for (const entry of entries) index(popular, { ...entry, source: 'popular' }); + popularLoadedAt = Date.now(); +}; + +export const popularEntriesStale = () => + Date.now() - popularLoadedAt > POPULAR_REFRESH_MS; + +const MEDIA_TYPE_NAMES: Partial> = { + [MediaType.MOVIE]: 'movie', + [MediaType.TV]: 'tv', + [MediaType.MUSIC]: 'album', + [MediaType.BOOK]: 'book', + [MediaType.COMIC]: 'comic', +}; + +const loadLibrary = async () => { + const rows = await getRepository(MediaSearchMetadata) + .createQueryBuilder('metadata') + .innerJoin('metadata.media', 'media') + .select([ + 'metadata.mediaId', + 'metadata.title', + 'metadata.alternateTitle', + 'metadata.releaseDate', + 'metadata.posterPath', + 'metadata.creator', + 'metadata.director', + 'metadata.artist', + 'metadata.author', + 'media.id', + 'media.mediaType', + 'media.tmdbId', + 'media.mbId', + 'media.status', + ]) + .where('metadata.title IS NOT NULL') + .orderBy('metadata.refreshedAt', 'DESC') + .take(MAX_LIBRARY) + .getMany(); + for (const entry of library.values()) removeFromBuckets(entry); + library.clear(); + for (const row of rows) { + const media = row.media; + const mediaType = media ? MEDIA_TYPE_NAMES[media.mediaType] : undefined; + if (!media || !mediaType || !row.title) continue; + const id = + mediaType === 'movie' || mediaType === 'tv' + ? media.tmdbId + : mediaType === 'album' + ? media.mbId + : undefined; + // books and comics have no single public id here; they still feed the + // vocabulary for corrections through their words + const people = [row.creator, row.director, row.artist, row.author].filter( + (value): value is string => !!value + ); + index( + library, + { + mediaType, + id: id ?? `media-${media.id}`, + title: row.title, + year: row.releaseDate?.slice(0, 4), + posterPath: row.posterPath ?? undefined, + subtitle: row.artist ?? row.author ?? row.creator ?? undefined, + popularity: 0, + owned: + media.status === MediaStatus.AVAILABLE || + media.status === MediaStatus.PARTIALLY_AVAILABLE, + source: 'library', + }, + [row.alternateTitle ?? '', ...people] + ); + } + libraryLoadedAt = Date.now(); +}; + +/** + * Loads the library index when it is missing or stale. Never throws; the + * first caller may await it, later refreshes happen in the background. + */ +export const ensureLibraryIndex = (): Promise => { + if (libraryLoading) return libraryLoading; + if (libraryLoadedAt && Date.now() - libraryLoadedAt < LIBRARY_REFRESH_MS) { + return Promise.resolve(); + } + libraryLoading = loadLibrary() + .catch((error: unknown) => { + logger.debug('Search suggestion library index failed to load', { + label: 'Search', + errorMessage: error instanceof Error ? error.message : String(error), + }); + // try again on a later request, not on every keystroke + libraryLoadedAt = Date.now() - LIBRARY_REFRESH_MS + 60_000; + }) + .finally(() => { + libraryLoading = undefined; + }); + return libraryLoading; +}; + +/** + * "Did you mean": replaces each query word the index does not know with the + * most common known word within the allowed typos. Returns undefined when + * nothing changes. + */ +export const correctSearchQuery = (query: string): string | undefined => { + const words = tokenizeSearchText(query); + if (!words.length) return undefined; + let changed = false; + const corrected = words.map((word) => { + if (word.length < 4 || vocabulary.has(word) || /^\d+$/.test(word)) + return word; + const typos = allowedTypos(word.length); + let best: { word: string; distance: number; count: number } | undefined; + // typos rarely hit the first letter; check its bucket and the second + // letter's so a swapped first pair is still found + const letters = new Set([word[0], word[1]]); + for (const [candidate, count] of vocabulary) { + if (!letters.has(candidate[0]) || candidate.length < 3) continue; + if (Math.abs(candidate.length - word.length) > typos) continue; + const distance = editDistance(word, candidate, typos); + if (distance > typos) continue; + if ( + !best || + distance < best.distance || + (distance === best.distance && count > best.count) + ) { + best = { word: candidate, distance, count }; + } + } + if (best) { + changed = true; + return best.word; + } + return word; + }); + return changed ? corrected.join(' ') : undefined; +}; + +export type SuggestionMatch = SuggestEntry & { score: number }; + +/** + * Index entries matching a partial query, best first. + * + * text textMatchScore, where the last word counts as a prefix (it is + * still being typed); must reach 0.55 + * source library +0.08 (owned +0.07 more), popular +0.03 + * fame up to +0.08 for popularity (log scale) + */ +export const matchSuggestions = ( + query: string, + { + limit = 8, + allow = () => true, + }: { limit?: number; allow?: (entry: SuggestEntry) => boolean } = {} +): SuggestionMatch[] => { + const words = tokenizeSearchText(query); + if (!words.length) return []; + const candidates = new Set(); + for (const word of words) { + for (const entry of buckets.get(word[0]) ?? []) candidates.add(entry); + } + const best = new Map(); + for (const entry of candidates) { + if (!allow(entry)) continue; + const text = Math.max( + textMatchScore(query, entry.title), + // "nate standup" still finds Nate Bargatze through his words + entry.words.length > entry.norm.split(' ').length + ? textMatchScore(query, entry.words.join(' ')) * 0.9 + : 0 + ); + if (text < 0.55) continue; + const score = + text + + (entry.source === 'library' + ? 0.08 + : entry.source === 'popular' + ? 0.03 + : 0) + + (entry.owned ? 0.07 : 0) + + Math.min(0.08, Math.log10(1 + entry.popularity) * 0.04); + const existing = best.get(entry.key); + if (!existing || existing.score < score) { + best.set(entry.key, { + mediaType: entry.mediaType, + id: entry.id, + title: entry.title, + year: entry.year, + posterPath: entry.posterPath, + subtitle: entry.subtitle, + popularity: entry.popularity, + owned: entry.owned, + source: entry.source, + department: entry.department, + comedian: entry.comedian, + score, + }); + } + } + return [...best.values()] + .sort((left, right) => right.score - left.score) + .slice(0, limit); +}; + +/** For tests. */ +export const resetSearchSuggestIndex = () => { + library.clear(); + learned.clear(); + popular.clear(); + buckets.clear(); + vocabulary.clear(); + libraryLoadedAt = 0; + popularLoadedAt = 0; + libraryLoading = undefined; +}; diff --git a/server/routes/search.test.ts b/server/routes/search.test.ts index 85aa144db8..8b72702642 100644 --- a/server/routes/search.test.ts +++ b/server/routes/search.test.ts @@ -24,6 +24,8 @@ import MetadataAlbum from '@server/entity/MetadataAlbum'; import MetadataArtist from '@server/entity/MetadataArtist'; import { User } from '@server/entity/User'; import { UserSettings } from '@server/entity/UserSettings'; +import { clearSearchProviderCache } from '@server/lib/searchProviderCache'; +import { resetSearchSuggestIndex } from '@server/lib/searchSuggest'; import { getSettings, type LazyLibrarianSettings, @@ -152,6 +154,8 @@ beforeEach(() => { afterEach(async () => { await waitForBackgroundTasks(); mock.restoreAll(); + clearSearchProviderCache(); + resetSearchSuggestIndex(); getSettings().lidarr = []; getSettings().readarr = []; getSettings().lazylibrarian = []; diff --git a/server/routes/search.ts b/server/routes/search.ts index e4062034c2..9dbb9afe6b 100644 --- a/server/routes/search.ts +++ b/server/routes/search.ts @@ -43,6 +43,33 @@ import { type CombinedSearchResponse, } from '@server/lib/search'; import { enrichSearchCredits } from '@server/lib/searchCredits'; +import { + mediaTypesForHint, + parseSearchIntent, + publicSearchIntent, + type SearchIntent, +} from '@server/lib/searchIntent'; +import { + intentNeedsVideoLookup, + resolveVideoIntent, + type IntentTopResult, +} from '@server/lib/searchIntentResolver'; +import { cachedSearchProvider } from '@server/lib/searchProviderCache'; +import { + rankSearchResults, + textMatchScore, + type RankableResult, +} from '@server/lib/searchRanking'; +import { + correctSearchQuery, + ensureLibraryIndex, + learnSearchResults, + matchSuggestions, + popularEntriesStale, + setPopularEntries, + type SuggestEntry, + type SuggestionMatch, +} from '@server/lib/searchSuggest'; import { runWithServarrServiceSnapshot } from '@server/lib/serviceAdmission'; import { getSettings } from '@server/lib/settings'; import { isUserMediaCategoryEnabled } from '@server/lib/userMediaCategories'; @@ -59,7 +86,11 @@ import { } from '@server/models/Book'; import { mapComicVineVolumeResult } from '@server/models/Comic'; import { mapLazyLibrarianMagazine } from '@server/models/Magazine'; -import { mapArtistResult, mapSearchResults } from '@server/models/Search'; +import { + mapArtistResult, + mapPersonResult, + mapSearchResults, +} from '@server/models/Search'; import { trackBackgroundTask } from '@server/utils/backgroundTasks'; import { searchBookshelfAuthors, @@ -85,6 +116,7 @@ import { parseOptionalBoundedString, parseOptionalLanguage, } from '@server/utils/validation'; +import type { Request, Response } from 'express'; import { Router } from 'express'; import rateLimit from 'express-rate-limit'; import { In } from 'typeorm'; @@ -140,6 +172,248 @@ export const BOOK_SEARCH_PROVIDER_TIMEOUT_MS = 15_000; export const ALL_SEARCH_GRACE_MS = 1_500; // TMDB, Bookshelf books, Bookshelf authors, LazyLibrarian, TMDB collections const ALL_SEARCH_PRIMARY_PROVIDERS = [0, 4, 6, 8, 9]; + +/** + * Provider groups of the streamed search. Each group is searched on its own + * and answers as soon as its providers do, so slow catalogs (books, music, + * comics) never hold back the fast ones (TMDB). + */ +export const SEARCH_GROUPS = [ + 'video', + 'music', + 'books', + 'authors', + 'comics', + 'magazines', +] as const; +export type SearchGroup = (typeof SEARCH_GROUPS)[number]; +// the group of each entry in the provider list below, by index +const PROVIDER_GROUPS: SearchGroup[] = [ + 'video', + 'music', + 'music', + 'books', + 'books', + 'authors', + 'authors', + 'comics', + 'magazines', + 'video', +]; +/** Names a person understands, for "X didn't answer" notes. */ +export const SEARCH_SOURCE_NAMES: Record = { + video: 'Movies & TV', + music: 'Music', + books: 'Books', + authors: 'Authors', + comics: 'Comics', + magazines: 'Magazines', +}; +const groupsForType = (type?: string): SearchGroup[] => { + switch (type) { + case 'movie': + case 'tv': + case 'person': + return ['video']; + case 'album': + case 'artist': + case 'music': + return ['music']; + case 'book': + return ['books']; + case 'author': + return ['authors']; + case 'comic': + return ['comics']; + case 'magazine': + return ['magazines']; + default: + return [...SEARCH_GROUPS]; + } +}; + +type SearchOutcome = + | { status: number; body: Record; noStore?: boolean } + | { error: { status: number; message: string } }; +type RunSearchOptions = { + /** Search only these provider groups (the streamed search). */ + groups?: ReadonlySet; +}; +const jsonOutcome = (status: number, body: unknown): SearchOutcome => ({ + status, + body: body as Record, +}); +const errorOutcome = (error: { + status: number; + message: string; +}): SearchOutcome => ({ error }); + +type TmdbMultiResults = Awaited>; +type VideoSearchWithIntent = TmdbMultiResults & { + intentKeys: string[]; + intentTop?: IntentTopResult; + correctedQuery?: string; +}; + +/** + * The TMDB "All" search plus what the query's intent adds: a comedian's + * specials for "nate standup", a series for "the bear season 3", a genre + * browse for "2015 horror". Both run at once; the intent lookup can only add + * results, and its failure is ignored. When neither finds anything, a "did + * you mean" correction from the suggestion index is tried once. + */ +const searchVideoWithIntent = async ({ + tmdb, + query, + page, + language, + intent, + moviesEnabled, + seriesEnabled, +}: { + tmdb: TheMovieDb; + query: string; + page: number; + language?: string; + intent: SearchIntent; + moviesEnabled: boolean; + seriesEnabled: boolean; +}): Promise => { + const useIntent = page === 1 && intentNeedsVideoLookup(intent); + const [plain, resolution] = await Promise.all([ + tmdb.searchMulti({ query, page, language, throwOnError: true }), + useIntent + ? resolveVideoIntent(tmdb, intent, { + language, + moviesEnabled, + seriesEnabled, + }).catch(() => undefined) + : Promise.resolve(undefined), + ]); + let base = plain; + let correctedQuery: string | undefined; + if (page === 1 && plain.results.length === 0 && !resolution?.results.length) { + const correction = correctSearchQuery(query); + if (correction) { + const retry = await tmdb + .searchMulti({ query: correction, page, language }) + .catch(() => undefined); + if (retry?.results.length) { + base = retry; + correctedQuery = correction; + } + } + } + const seen = new Set( + base.results.map((result) => `${result.media_type}:${result.id}`) + ); + const additions = [ + ...(resolution?.people ?? []).map((person) => ({ + ...person, + media_type: 'person' as const, + })), + ...(resolution?.results ?? []), + ].filter((result) => { + const key = `${result.media_type}:${result.id}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + return { + ...base, + results: [ + ...base.results.slice(0, MAX_SEARCH_RESULTS_PER_PROVIDER), + ...(additions as TmdbMultiResults['results']), + ], + intentKeys: (resolution?.results ?? []).map( + (result) => `${result.media_type}:${result.id}` + ), + intentTop: resolution?.topResult, + correctedQuery, + }; +}; + +type RankedResult = RankableResult & { + matchScore: number; + id: string | number; + mediaType: string; + knownFor?: unknown[]; +}; + +/** + * The card shown above the sections when the intent is clear. + * + * - From the intent lookup: the person and their fitting works ("Nate + * Bargatze" with his stand-up specials), or the series and season. + * - Otherwise the best result when its title or name fits the query at 0.9 + * or better (an exact or near-exact title, a full name); a person comes + * with the titles they are known for. + */ +const buildTopResult = ( + results: readonly RankedResult[], + intent: SearchIntent, + intentTop?: IntentTopResult, + query = intent.query +) => { + const byKey = new Map( + results.map((result) => [`${result.mediaType}:${result.id}`, result]) + ); + if (intentTop?.kind === 'person') { + const works = intentTop.works + .map((key) => byKey.get(key)) + .filter((result): result is RankedResult => !!result); + if (works.length) { + return { + kind: 'person' as const, + label: intentTop.label, + reason: 'intent' as const, + item: byKey.get(`person:${intentTop.person.id}`) ?? { + ...mapPersonResult(intentTop.person), + knownFor: [], + }, + works, + }; + } + } + if (intentTop?.kind === 'title') { + const item = byKey.get(`${intentTop.mediaType}:${intentTop.id}`); + if (item) { + return { + kind: 'title' as const, + label: intentTop.label, + reason: 'intent' as const, + item, + ...(intentTop.season !== undefined && { season: intentTop.season }), + ...(intentTop.episode !== undefined && { episode: intentTop.episode }), + works: [], + }; + } + } + let best: { result: RankedResult; fit: number } | undefined; + for (const result of results) { + const fit = Math.max( + textMatchScore(query, result.title ?? result.name), + textMatchScore(query, result.originalTitle ?? result.originalName) + ); + if (fit < 0.9) continue; + if (!best || result.matchScore > best.result.matchScore) { + best = { result, fit }; + } + } + if (!best) return undefined; + const item = best.result; + return { + kind: + item.mediaType === 'person' ? ('person' as const) : ('title' as const), + reason: 'match' as const, + item, + works: + item.mediaType === 'person' && Array.isArray(item.knownFor) + ? item.knownFor + : [], + }; +}; + const searchRateLimit = rateLimit({ ...SEARCH_RATE_LIMIT, standardHeaders: true, @@ -149,6 +423,342 @@ const searchRateLimit = rateLimit({ keyGenerator: (req) => `user:${req.user?.id ?? 'anonymous'}`, }); +/** + * Suggestions answer from memory within this budget; a TMDB lookup that is + * still running when it ends keeps going and teaches the index for the next + * keystroke. + */ +export const SUGGEST_BUDGET_MS = 120; +const MAX_SUGGEST_QUERY_LENGTH = 100; +// suggestions run on keystrokes, so they get their own, roomier limit +const suggestRateLimit = rateLimit({ + windowMs: 60 * 1000, + limit: 300, + standardHeaders: true, + legacyHeaders: false, + skip: () => + process.env.NODE_ENV === 'test' || process.env.E2E_TESTS === 'true', + keyGenerator: (req) => `suggest:${req.user?.id ?? 'anonymous'}`, +}); + +const waitAtMost = (promise: Promise, ms: number) => + new Promise((resolve) => { + const timer = setTimeout(() => resolve(undefined), Math.max(0, ms)); + promise.then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + () => { + clearTimeout(timer); + resolve(undefined); + } + ); + }); + +let popularLoading = false; +const refreshPopularSuggestions = () => { + if (popularLoading || !popularEntriesStale()) return; + popularLoading = true; + trackBackgroundTask('search suggestion trending titles', async () => { + try { + const trending = await new TheMovieDb().getAllTrending({ + timeWindow: 'week', + }); + const mapped = await mapSearchResults(trending.results); + setPopularEntries( + mapped.flatMap((result): SuggestEntry[] => { + const item = result as unknown as Record; + if (item.adult === true) return []; + const mediaType = item.mediaType; + if ( + mediaType !== 'movie' && + mediaType !== 'tv' && + mediaType !== 'person' + ) + return []; + const date = String(item.releaseDate ?? item.firstAirDate ?? ''); + return [ + { + mediaType, + id: item.id as number, + title: String(item.title ?? item.name ?? ''), + year: /^\d{4}/.test(date) ? date.slice(0, 4) : undefined, + posterPath: (item.posterPath ?? item.profilePath) as + string | undefined, + popularity: Number(item.popularity ?? 0) || 0, + owned: false, + source: 'popular', + }, + ]; + }) + ); + } finally { + popularLoading = false; + } + }); +}; + +// last words that are still being typed into an intent ("nate st…") +const INTENT_COMPLETIONS: { + words: string[]; + phrase: string; + types: string[]; +}[] = [ + { + words: ['standup', 'stand', 'specials', 'comedy'], + phrase: 'stand-up specials', + types: ['person'], + }, + { words: ['live'], phrase: 'live albums', types: ['artist'] }, + { + words: ['audiobooks', 'audio'], + phrase: 'audiobooks', + types: ['author'], + }, + { words: ['documentaries'], phrase: 'documentaries', types: ['person'] }, + { words: ['season'], phrase: 'season 1', types: ['tv'] }, +]; + +async function handleSuggest(req: Request, res: Response) { + const startedAt = Date.now(); + const parsed = parseOptionalBoundedString(req.query.q, { + fieldName: 'Query', + maxLength: MAX_SUGGEST_QUERY_LENGTH, + }); + if ('error' in parsed) { + return res.status(400).json({ status: 400, message: parsed.error }); + } + const query = (parsed.value ?? '').trim(); + const empty = { + query, + queries: [], + titles: [], + people: [], + elapsedMs: 0, + }; + if (query.length < 2) { + return res.status(200).json(empty); + } + const parsedLanguage = parseOptionalLanguage(req.query.language); + const language = + ('value' in parsedLanguage && parsedLanguage.value) || req.metadataLocale; + const user = req.user; + const moviesEnabled = isUserMediaCategoryEnabled(user, 'movie'); + const seriesEnabled = isUserMediaCategoryEnabled(user, 'tv'); + const runtime = getExternalRuntimeConfig(); + const musicEnabled = + (runtime.lidarr.length > 0 || runtime.aurral.length > 0) && + isUserMediaCategoryEnabled(user, 'music'); + const booksEnabled = + runtime.readarr.length > 0 && + (isUserMediaCategoryEnabled(user, 'ebook') || + isUserMediaCategoryEnabled(user, 'audiobook')); + const comicsEnabled = + !!getSettings().main.comicVineApiKey && + isUserMediaCategoryEnabled(user, 'comic'); + const allow = (entry: SuggestEntry) => + !entry.adult && + ((entry.mediaType === 'movie' || entry.mediaType === 'collection' + ? moviesEnabled + : entry.mediaType === 'tv' + ? seriesEnabled + : entry.mediaType === 'person' + ? moviesEnabled || seriesEnabled + : entry.mediaType === 'album' || entry.mediaType === 'artist' + ? musicEnabled + : entry.mediaType === 'book' || entry.mediaType === 'author' + ? booksEnabled + : entry.mediaType === 'comic' + ? comicsEnabled + : false) as boolean); + + const remaining = () => SUGGEST_BUDGET_MS - (Date.now() - startedAt); + const maturityPolicyPromise = user + ? getUserVideoMaturityPolicy(user.id).catch( + () => + ({ + movie: 'G', + tv: 'TV-Y', + }) as unknown as UserVideoMaturityPolicy + ) + : Promise.resolve({ movie: null, tv: null } as UserVideoMaturityPolicy); + await waitAtMost(ensureLibraryIndex(), Math.min(60, remaining())); + refreshPopularSuggestions(); + + const intent = parseSearchIntent(query); + const words = intent.normalized.split(' '); + const lastWord = words[words.length - 1] ?? ''; + const completion = + words.length > 1 && lastWord.length >= 2 + ? INTENT_COMPLETIONS.find((candidate) => + candidate.words.some((word) => word.startsWith(lastWord)) + ) + : undefined; + // the words that name the thing: "nate" for "nate standup" and "nate st" + const base = + intent.entity && intent.entity !== intent.normalized + ? intent.entity + : completion + ? words.slice(0, -1).join(' ') + : query; + + const find = () => { + const direct = matchSuggestions(query, { limit: 12, allow }); + const byBase = + base !== query ? matchSuggestions(base, { limit: 12, allow }) : []; + const merged = new Map(); + for (const match of [...direct, ...byBase]) { + const key = `${match.mediaType}:${match.id}`; + const existing = merged.get(key); + if (!existing || existing.score < match.score) merged.set(key, match); + } + return [...merged.values()].sort((left, right) => right.score - left.score); + }; + let matches = find(); + + // little known about this query: ask TMDB. With no good match yet the + // answer is awaited within the budget; otherwise it only teaches the index + // for the next keystroke. A late answer always lands in the index. + if ( + (moviesEnabled || seriesEnabled) && + query.length >= 3 && + matches.filter((match) => match.score >= 0.8).length < 3 && + remaining() > 10 + ) { + const wait = !matches.some((match) => match.score >= 0.8); + const lookup = new TheMovieDb() + .searchMulti({ query: base, language }) + .then(async (response) => { + learnSearchResults( + (await mapSearchResults( + response.results.slice(0, 10) + )) as unknown as Record[] + ); + return true; + }); + trackBackgroundTask('search suggestion lookup', () => + lookup.catch(() => false) + ); + if (wait && (await waitAtMost(lookup, remaining()))) matches = find(); + } + + // a maturity limit applies to suggestions too: titles that cannot be + // checked within the budget are left out rather than shown unchecked + const policy = await waitAtMost(maturityPolicyPromise, remaining()); + const restricted = !policy || policy.movie !== null || policy.tv !== null; + if (restricted) { + const tmdb = new TheMovieDb(); + const videoMatches = matches.filter( + (match) => + (match.mediaType === 'movie' || match.mediaType === 'tv') && + typeof match.id === 'number' + ) as (SuggestionMatch & { id: number })[]; + const allowedKeys = new Set(); + if (policy) { + const checked = await waitAtMost( + Promise.all([ + filterVideoResultsByMaturityPolicy( + tmdb, + policy, + MediaType.MOVIE, + videoMatches + .filter((match) => match.mediaType === 'movie') + .slice(0, 6), + language + ), + filterVideoResultsByMaturityPolicy( + tmdb, + policy, + MediaType.TV, + videoMatches + .filter((match) => match.mediaType === 'tv') + .slice(0, 6), + language + ), + ]), + Math.max(remaining(), 30) + ); + for (const match of checked?.flat() ?? []) { + allowedKeys.add(`${match.mediaType}:${match.id}`); + } + } + matches = matches.filter( + (match) => + (match.mediaType !== 'movie' && + match.mediaType !== 'tv' && + match.mediaType !== 'collection') || + allowedKeys.has(`${match.mediaType}:${match.id}`) + ); + } + + const toItem = (match: SuggestionMatch) => ({ + mediaType: match.mediaType, + id: match.id, + title: match.title, + ...(match.year && { year: match.year }), + ...(match.posterPath && { posterPath: match.posterPath }), + ...(match.subtitle && { subtitle: match.subtitle }), + owned: match.owned, + source: match.source, + score: Math.round(match.score * 100), + }); + const isPersonLike = (match: SuggestionMatch) => + match.mediaType === 'person' || + match.mediaType === 'artist' || + match.mediaType === 'author'; + // library-only rows for books and comics have no page to open + const openable = (match: SuggestionMatch) => + typeof match.id === 'number' || !String(match.id).startsWith('media-'); + const people = matches.filter(isPersonLike).slice(0, 3); + const titles = matches + .filter((match) => !isPersonLike(match) && openable(match)) + .slice(0, 6); + + const queries: { text: string; kind: 'intent' | 'correction' }[] = []; + const didYouMean = correctSearchQuery(query); + if (didYouMean && didYouMean !== intent.normalized) { + queries.push({ text: didYouMean, kind: 'correction' }); + } + const phrase = + intent.format === 'standup' + ? 'stand-up specials' + : intent.format === 'live' + ? 'live albums' + : intent.format === 'audiobook' + ? 'audiobooks' + : intent.format === 'documentary' + ? 'documentaries' + : intent.season !== undefined + ? `season ${intent.season}` + : completion?.phrase; + const lead = matches.find((match) => match.score >= 0.75); + if (lead) { + if (phrase) { + queries.push({ text: `${lead.title} ${phrase}`, kind: 'intent' }); + } else if (lead.mediaType === 'person' && lead.comedian) { + queries.push({ text: `${lead.title} stand-up specials`, kind: 'intent' }); + } else if (lead.mediaType === 'artist') { + queries.push({ text: `${lead.title} live albums`, kind: 'intent' }); + } else if (lead.mediaType === 'author') { + queries.push({ text: `${lead.title} audiobooks`, kind: 'intent' }); + } + } + + return res.status(200).json({ + query, + queries: queries.slice(0, 3), + titles: titles.map(toItem), + people: people.map(toItem), + ...(didYouMean && { didYouMean }), + elapsedMs: Date.now() - startedAt, + }); +} + +searchRoutes.get('/suggest', suggestRateLimit, (req, res, next) => { + handleSuggest(req, res).catch(next); +}); + searchRoutes.use(searchRateLimit); export const capSearchProviderResults = ( @@ -339,20 +949,30 @@ const dedupeBookSearchDocs = < }); }; -searchRoutes.get('/', async (req, res, next) => { +const runGlobalSearch = async ( + req: Request, + options: RunSearchOptions = {} +): Promise => { const parsedQuery = parseSearchQuery(req.query.query); if ('error' in parsedQuery) { - return res.status(400).json({ status: 400, message: parsedQuery.error }); + return jsonOutcome(400, { status: 400, message: parsedQuery.error }); } const queryString = parsedQuery.value; + const intent = parseSearchIntent(queryString); + const groupOn = (group: SearchGroup) => + !options.groups || options.groups.has(group); let typeSpecificTotalResults: number | undefined; let typeSpecificTotalPages: number | undefined; let partial = false; + let failedSources: string[] = []; + let videoIntentKeys: string[] = []; + let videoIntentTop: IntentTopResult | undefined; + let correctedQuery: string | undefined; const page = parsePositiveInt(req.query.page, 1, 500); const parsedLanguage = parseOptionalLanguage(req.query.language); if ('error' in parsedLanguage) { - return res.status(400).json({ status: 400, message: parsedLanguage.error }); + return jsonOutcome(400, { status: 400, message: parsedLanguage.error }); } const language = parsedLanguage.value ?? req.metadataLocale; @@ -364,18 +984,16 @@ searchRoutes.get('/', async (req, res, next) => { }) : ({ value: undefined } as { value?: SearchType }); if ('error' in parsedType) { - return res.status(400).json({ status: 400, message: parsedType.error }); + return jsonOutcome(400, { status: 400, message: parsedType.error }); } const typeFilter = parsedType.value; const parsedMusicFilters = parseMusicSearchFilters(req.query); if ('error' in parsedMusicFilters) - return res - .status(400) - .json({ status: 400, message: parsedMusicFilters.error }); + return jsonOutcome(400, { status: 400, message: parsedMusicFilters.error }); const musicFilters = parsedMusicFilters.value; const hasMusicFilters = Object.keys(musicFilters).length > 0; if (hasMusicFilters && typeFilter !== 'music' && typeFilter !== 'album') - return res.status(400).json({ + return jsonOutcome(400, { status: 400, message: 'Music filters require the Music media type.', }); @@ -387,9 +1005,7 @@ searchRoutes.get('/', async (req, res, next) => { } ); if ('error' in parsedResultFilter) { - return res - .status(400) - .json({ status: 400, message: parsedResultFilter.error }); + return jsonOutcome(400, { status: 400, message: parsedResultFilter.error }); } const resultFilter = parsedResultFilter.value; const parsedFormat = req.query.format @@ -400,11 +1016,11 @@ searchRoutes.get('/', async (req, res, next) => { }) : ({ value: undefined } as { value?: BookFormat }); if ('error' in parsedFormat) { - return res.status(400).json({ status: 400, message: parsedFormat.error }); + return jsonOutcome(400, { status: 400, message: parsedFormat.error }); } const bookFormat = parsedFormat.value; if (bookFormat && typeFilter !== 'book') { - return res.status(400).json({ + return jsonOutcome(400, { status: 400, message: 'Format can only be used with book searches.', }); @@ -453,7 +1069,7 @@ searchRoutes.get('/', async (req, res, next) => { typeFilter === 'music') && !musicEnabled) ) { - return res.status(200).json({ + return jsonOutcome(200, { page, totalPages: 1, totalResults: 0, @@ -462,7 +1078,7 @@ searchRoutes.get('/', async (req, res, next) => { } if ((typeFilter === 'book' || typeFilter === 'author') && !booksEnabled) { - return res.status(200).json({ + return jsonOutcome(200, { page, totalPages: 1, totalResults: 0, @@ -471,7 +1087,7 @@ searchRoutes.get('/', async (req, res, next) => { } if (typeFilter === 'comic' && !comicsEnabled) { - return res.status(200).json({ + return jsonOutcome(200, { page, totalPages: 1, totalResults: 0, @@ -480,7 +1096,7 @@ searchRoutes.get('/', async (req, res, next) => { } if (typeFilter === 'magazine' && !magazinesEnabled) { - return res.status(200).json({ + return jsonOutcome(200, { page, totalPages: 1, totalResults: 0, @@ -521,22 +1137,65 @@ searchRoutes.get('/', async (req, res, next) => { : undefined; const shouldSearchVideo = - ((!typeFilter || typeFilter === 'movie' || typeFilter === 'tv') && + groupOn('video') && + (((!typeFilter || typeFilter === 'movie' || typeFilter === 'tv') && (moviesEnabled || seriesEnabled)) || - (typeFilter === 'person' && (moviesEnabled || seriesEnabled)); + (typeFilter === 'person' && (moviesEnabled || seriesEnabled))); const shouldSearchCollections = + groupOn('video') && !typeFilter && moviesEnabled && (!req.user || maturityPolicyForSearch?.movie === null); const shouldSearchMusic = - !typeFilter || - typeFilter === 'album' || - typeFilter === 'artist' || - typeFilter === 'music'; - const shouldSearchBooks = !typeFilter || typeFilter === 'book'; - const shouldSearchAuthors = !typeFilter || typeFilter === 'author'; - const shouldSearchComics = !typeFilter || typeFilter === 'comic'; - const shouldSearchMagazines = !typeFilter || typeFilter === 'magazine'; + groupOn('music') && + (!typeFilter || + typeFilter === 'album' || + typeFilter === 'artist' || + typeFilter === 'music'); + const shouldSearchBooks = + groupOn('books') && (!typeFilter || typeFilter === 'book'); + const shouldSearchAuthors = + groupOn('authors') && (!typeFilter || typeFilter === 'author'); + const shouldSearchComics = + groupOn('comics') && (!typeFilter || typeFilter === 'comic'); + const shouldSearchMagazines = + groupOn('magazines') && (!typeFilter || typeFilter === 'magazine'); + // In the "All" search the intent narrows what the slower catalogs are + // asked: "metallica live" asks MusicBrainz for Metallica's live + // albums, "sanderson audiobook" asks the audiobook catalog for + // "sanderson". Scoped searches (a type chip) keep the query as typed. + const allSearch = !typeFilter; + const intentEntity = intent.entity || queryString; + const musicIntentQuery = + allSearch && intent.format === 'live' && intent.entity + ? `(artist:(${escapeMusicBrainzQuery(intent.entity)}) OR releasegroup:(${escapeMusicBrainzQuery(intent.entity)})) AND secondarytype:live` + : allSearch && intent.format === 'soundtrack' && intent.entity + ? `releasegroup:(${escapeMusicBrainzQuery(intent.entity)}) AND secondarytype:soundtrack` + : undefined; + const musicArtistQuery = + allSearch && + intent.entity && + (intent.mediaType === 'music' || intent.role === 'artist') + ? intent.entity + : queryString; + const bookIntent = + allSearch && + (intent.mediaType === 'book' || + intent.role === 'author' || + intent.role === 'narrator'); + const bookQuery = bookIntent + ? [intent.entity, intent.creator].filter(Boolean).join(' ') || + queryString + : queryString; + const authorQuery = bookIntent + ? (intent.creator ?? intentEntity) + : queryString; + const bookshelfFormat = + bookIntent && + (intent.format === 'audiobook' || intent.format === 'ebook') && + bookFormatEnabled(intent.format) + ? intent.format + : bookFormatForProviderSearch; const providerNames = [ 'TMDB', 'MusicBrainz albums', @@ -581,11 +1240,19 @@ searchRoutes.get('/', async (req, res, next) => { media_type: 'tv' as const, })), })) - : tmdb.searchMulti({ + : searchVideoWithIntent({ + tmdb, query: queryString, page, language, - throwOnError: true, + intent, + moviesEnabled, + seriesEnabled, + }).then((response) => { + videoIntentKeys = response.intentKeys; + videoIntentTop = response.intentTop; + correctedQuery = response.correctedQuery; + return response; }) : Promise.resolve({ page, @@ -603,7 +1270,7 @@ searchRoutes.get('/', async (req, res, next) => { ) : typeFilter === 'music' && resultFilter ? toMusicAlbumRefinementQuery(queryString, resultFilter) - : escapeMusicBrainzQuery(queryString), + : (musicIntentQuery ?? escapeMusicBrainzQuery(queryString)), limit: 20, offset: musicOffset, }) @@ -613,7 +1280,7 @@ searchRoutes.get('/', async (req, res, next) => { query: typeFilter === 'artist' ? buildArtistAutocompleteQuery(queryString) - : escapeMusicBrainzQuery(queryString), + : escapeMusicBrainzQuery(musicArtistQuery), limit: 20, offset: musicOffset, }) @@ -621,7 +1288,7 @@ searchRoutes.get('/', async (req, res, next) => { shouldSearchBooks && ebookEnabled && bookFormat !== 'audiobook' ? openLibrary.searchBooks({ query: [ - toFieldedBooleanAndQuery(queryString, [ + toFieldedBooleanAndQuery(bookQuery, [ 'title', 'author', 'subject', @@ -635,11 +1302,21 @@ searchRoutes.get('/', async (req, res, next) => { }) : Promise.resolve({ numFound: 0, start: 0, docs: [] }), shouldSearchBooks && booksEnabled - ? searchBookshelfCatalogs( - getSettings().readarr, - queryString, - bookFormatForProviderSearch, - { failOnAllUnavailable: typeFilter === 'book' } + ? cachedSearchProvider( + 'bookshelf-books', + [ + getSettings().readarr.map((server) => server.id), + bookQuery, + bookshelfFormat, + typeFilter === 'book', + ], + () => + searchBookshelfCatalogs( + getSettings().readarr, + bookQuery, + bookshelfFormat, + { failOnAllUnavailable: typeFilter === 'book' } + ) ) : Promise.resolve([]), // Choosing a validated search type selects a provider; it does not @@ -647,7 +1324,7 @@ searchRoutes.get('/', async (req, res, next) => { // codeql[js/user-controlled-bypass] shouldSearchAuthors && booksEnabled ? openLibrary.searchAuthors({ - query: queryString, + query: authorQuery, page, limit: 20, }) @@ -656,10 +1333,21 @@ searchRoutes.get('/', async (req, res, next) => { // bypass provider authorization or transport policy. // codeql[js/user-controlled-bypass] shouldSearchAuthors && booksEnabled - ? searchBookshelfAuthors(getSettings().readarr, queryString) + ? cachedSearchProvider( + 'bookshelf-authors', + [getSettings().readarr.map((server) => server.id), authorQuery], + () => searchBookshelfAuthors(getSettings().readarr, authorQuery) + ) : Promise.resolve([]), shouldSearchComics && comicsEnabled && comicVine - ? searchComicVolumes({ comicVine, metron, query: queryString, page }) + ? cachedSearchProvider('comicvine', [queryString, page], () => + searchComicVolumes({ + comicVine, + metron, + query: queryString, + page, + }) + ) : Promise.resolve({ error: 'OK', limit: 20, @@ -757,13 +1445,20 @@ searchRoutes.get('/', async (req, res, next) => { const failedProviders = providerNames.flatMap((provider, index) => { const response = providerResults.get(index); if (response?.status === 'rejected') { - return [{ provider, ...getHttpErrorDetails(response.reason) }]; + return [ + { + provider, + group: PROVIDER_GROUPS[index], + ...getHttpErrorDetails(response.reason), + }, + ]; } return !response && providerResponses.timedOut ? [ { provider, + group: PROVIDER_GROUPS[index], timedOut: true, timeoutMs: SEARCH_PROVIDER_TIMEOUT_MS, errorCode: 'SEARCH_PROVIDER_TIMEOUT', @@ -775,6 +1470,11 @@ searchRoutes.get('/', async (req, res, next) => { }); if (failedProviders.length > 0) { partial = true; + failedSources = [ + ...new Set( + failedProviders.map(({ group }) => SEARCH_SOURCE_NAMES[group]) + ), + ]; logger.warn('One or more global search providers failed', { label: 'API', failedProviders, @@ -799,7 +1499,7 @@ searchRoutes.get('/', async (req, res, next) => { (!artistProviderResponse || artistProviderResponse.status === 'rejected') ) - return next({ + return errorOutcome({ status: 503, message: 'Artist search is temporarily unavailable. Please try again.', @@ -809,7 +1509,7 @@ searchRoutes.get('/', async (req, res, next) => { musicEnabled && (!albumProviderResponse || albumProviderResponse.status === 'rejected') ) { - return res.status(503).json({ + return jsonOutcome(503, { message: 'MusicBrainz, the service used for music searches, timed out or is unavailable. Please try again.', }); @@ -838,7 +1538,7 @@ searchRoutes.get('/', async (req, res, next) => { booksEnabled && bookSearchFailed ) { - return res.status(503).json({ + return jsonOutcome(503, { status: 503, message: bookFormat === 'audiobook' @@ -855,7 +1555,7 @@ searchRoutes.get('/', async (req, res, next) => { (!bookshelfAuthorProviderResponse || bookshelfAuthorProviderResponse.status === 'rejected') ) { - return next({ + return errorOutcome({ status: 503, message: 'The author catalogs timed out or are unavailable. Please try again.', @@ -868,7 +1568,7 @@ searchRoutes.get('/', async (req, res, next) => { comicsEnabled && (!comicProviderResponse || comicProviderResponse.status === 'rejected') ) { - return next({ + return errorOutcome({ status: 503, message: 'ComicVine, the service used for comic searches, timed out or is unavailable. Please try again.', @@ -882,7 +1582,7 @@ searchRoutes.get('/', async (req, res, next) => { (!magazineProviderResponse || magazineProviderResponse.status === 'rejected') ) { - return next({ + return errorOutcome({ status: 503, message: 'LazyLibrarian, the service used for magazine searches, is unavailable. Please try again.', @@ -956,7 +1656,12 @@ searchRoutes.get('/', async (req, res, next) => { total_results: rawTmdbResults.total_results + rawCollectionResults.total_results, results: [ - ...rawTmdbResults.results.slice(0, MAX_SEARCH_RESULTS_PER_PROVIDER), + // a TMDB page holds 20; the intent lookup may add a person and up + // to 20 of their works after them + ...rawTmdbResults.results.slice( + 0, + MAX_SEARCH_RESULTS_PER_PROVIDER * 2 + 1 + ), ...collectionResults, ], }; @@ -977,7 +1682,7 @@ searchRoutes.get('/', async (req, res, next) => { // Artist selection needs exact MusicBrainz IDs, including artists linked // to TMDB people. It does not need slower poster/person enrichment. if (typeFilter === 'artist') { - return res.status(200).json({ + return jsonOutcome(200, { page, totalPages: Math.max( 1, @@ -1054,7 +1759,7 @@ searchRoutes.get('/', async (req, res, next) => { (doc) => matchesAllSearchTerms( [doc.title, ...(doc.author_name ?? []), ...(doc.subject ?? [])], - queryString + bookQuery ) ); const dedupedAuthors = new Map(); @@ -1477,29 +2182,215 @@ searchRoutes.get('/', async (req, res, next) => { capabilityResults.length !== creditEnrichedResults.length || maturityFilteredResults.length !== capabilityResults.length; - if (partial) res.set('Cache-Control', 'no-store'); - return res.status(200).json({ - page: results.page, - totalPages: typeSpecificTotalPages ?? results.total_pages, - totalResults: - typeSpecificTotalResults ?? - ((typeFilter || capabilityFiltered) && !hasMusicFilters - ? filteredResults.length - : results.total_results), - results: filteredResults, - ...(partial && { partial: true }), - }); + // Results the intent lookup found keep that mark through mapping, so the + // ranking can lift them ("nate standup" → his specials first). + const intentKeys = new Set(videoIntentKeys); + const rankingInput = filteredResults.map((result) => + intentKeys.has(`${result.mediaType}:${result.id}`) + ? { ...result, intentMatch: true } + : result + ); + const rankedResults = (hasMusicFilters || resultFilter + ? rankingInput.map((result) => ({ ...result, matchScore: 0 })) + : rankSearchResults(rankingInput as RankableResult[], { + query: correctedQuery ?? queryString, + entity: intent.entity, + mediaTypes: mediaTypesForHint(intent.mediaType), + genreIds: [ + intent.genre?.movieGenreId, + intent.genre?.tvGenreId, + ].filter((id): id is number => typeof id === 'number'), + year: intent.year, + decade: intent.decade, + })) as unknown as RankedResult[]; + const topResult = + page === 1 && !hasMusicFilters && !resultFilter + ? buildTopResult( + rankedResults, + intent, + videoIntentTop, + correctedQuery ?? queryString + ) + : undefined; + // what was found becomes suggestable and correctable + learnSearchResults(rankedResults as unknown as Record[]); + + return { + status: 200, + noStore: partial, + body: { + page: results.page, + totalPages: typeSpecificTotalPages ?? results.total_pages, + totalResults: + typeSpecificTotalResults ?? + ((typeFilter || capabilityFiltered) && !hasMusicFilters + ? filteredResults.length + : results.total_results), + results: rankedResults, + ...(partial && { partial: true, failedSources }), + intent: publicSearchIntent(intent), + ...(topResult && { topResult }), + ...(correctedQuery && { correctedQuery }), + }, + }; } catch (e) { logger.debug('Something went wrong retrieving search results', { label: 'API', errorMessage: e instanceof Error ? e.message : 'Unknown error', query: queryString, }); - return next({ + return errorOutcome({ status: 500, message: 'Unable to retrieve search results.', }); } +}; + +searchRoutes.get('/', async (req, res, next) => { + const outcome = await runGlobalSearch(req); + if ('error' in outcome) return next(outcome.error); + if (outcome.noStore) res.set('Cache-Control', 'no-store'); + return res.status(outcome.status).json(outcome.body); +}); + +/** Deadline for one group of the streamed search. */ +const STREAM_GROUP_TIMEOUT_MS = SEARCH_PROVIDER_TIMEOUT_MS + 1_000; + +/** + * Streamed global search (newline-delimited JSON). + * + * The provider groups (video, music, books, authors, comics, magazines) are + * searched side by side, each with its own deadline, and each answers on its + * own line the moment it is done, so TMDB results show in a few hundred + * milliseconds while a slow Bookshelf or MusicBrainz fills in later or not at + * all. Lines, in order of arrival: + * + * {"type":"intent", intent, didYouMean?} at once + * {"type":"results", group, results, totalPages, totalResults, + * topResult?, correctedQuery?, partial?, failedSources?} per group + * {"type":"error", group, status, message} a group that failed + * {"type":"done", totalPages, failedSources, partial, elapsedMs} last + * + * `groups` (comma separated) limits the search to some groups; Lumen leaves + * out books and comics, which it reads from their own endpoints. A closed + * connection stops the stream; lookups still running finish into the + * provider caches so the next search gets them at once. + */ +searchRoutes.get('/stream', async (req, res) => { + const parsedQuery = parseSearchQuery(req.query.query); + if ('error' in parsedQuery) { + return res.status(400).json({ status: 400, message: parsedQuery.error }); + } + const requested = + typeof req.query.groups === 'string' && req.query.groups.trim() + ? req.query.groups.split(',').map((group) => group.trim()) + : undefined; + if ( + requested?.some( + (group) => !(SEARCH_GROUPS as readonly string[]).includes(group) + ) + ) { + return res.status(400).json({ status: 400, message: 'Unknown group.' }); + } + const type = typeof req.query.type === 'string' ? req.query.type : undefined; + // a provider id ("tmdb:603", an ISBN) is one lookup, not one per group + const groups: SearchGroup[] = findSearchProvider( + parsedQuery.value.toLowerCase() + ) + ? ['video'] + : groupsForType(type).filter( + (group) => !requested || requested.includes(group) + ); + const startedAt = Date.now(); + const intent = parseSearchIntent(parsedQuery.value); + let closed = false; + res.on('close', () => { + closed = true; + }); + res.status(200); + res.set({ + 'Content-Type': 'application/x-ndjson; charset=utf-8', + // no-transform keeps compression from buffering the stream + 'Cache-Control': 'no-store, no-transform', + 'X-Accel-Buffering': 'no', + }); + res.flushHeaders(); + const send = (event: Record) => { + if (closed) return; + res.write(`${JSON.stringify(event)}\n`); + (res as unknown as { flush?: () => void }).flush?.(); + }; + const didYouMean = correctSearchQuery(parsedQuery.value); + send({ + type: 'intent', + query: parsedQuery.value, + intent: publicSearchIntent(intent), + ...(didYouMean && { didYouMean }), + }); + + let totalPages = 1; + const failedSources = new Set(); + await Promise.all( + groups.map(async (group) => { + let timer: ReturnType | undefined; + const outcome = await Promise.race([ + runGlobalSearch(req, { groups: new Set([group]) }).catch(() => + errorOutcome({ status: 500, message: 'Search failed.' }) + ), + new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), STREAM_GROUP_TIMEOUT_MS); + }), + ]).finally(() => clearTimeout(timer)); + if (!outcome) { + failedSources.add(SEARCH_SOURCE_NAMES[group]); + send({ + type: 'error', + group, + status: 504, + message: `${SEARCH_SOURCE_NAMES[group]} did not answer in time.`, + }); + return; + } + if ('error' in outcome || outcome.status !== 200) { + failedSources.add(SEARCH_SOURCE_NAMES[group]); + const error = + 'error' in outcome + ? outcome.error + : { + status: outcome.status, + message: String(outcome.body.message ?? 'Search failed.'), + }; + send({ type: 'error', group, ...error }); + return; + } + const body = outcome.body; + for (const source of (body.failedSources as string[] | undefined) ?? []) { + failedSources.add(source); + } + totalPages = Math.max(totalPages, Number(body.totalPages) || 1); + send({ + type: 'results', + group, + page: body.page, + totalPages: body.totalPages, + totalResults: body.totalResults, + results: body.results, + ...(body.topResult ? { topResult: body.topResult } : {}), + ...(body.correctedQuery ? { correctedQuery: body.correctedQuery } : {}), + ...(body.partial + ? { partial: true, failedSources: body.failedSources } + : {}), + }); + }) + ); + send({ + type: 'done', + totalPages, + partial: failedSources.size > 0, + failedSources: [...failedSources], + elapsedMs: Date.now() - startedAt, + }); + res.end(); }); searchRoutes.get('/keyword', async (req, res, next) => { diff --git a/server/routes/searchSmart.test.ts b/server/routes/searchSmart.test.ts new file mode 100644 index 0000000000..6747b2cb5d --- /dev/null +++ b/server/routes/searchSmart.test.ts @@ -0,0 +1,727 @@ +/** + * Smarter global search: intent lookups, the top result, ranking, the + * streamed search and suggestions. + */ +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import type { Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import path from 'node:path'; +import { + after, + afterEach, + before, + beforeEach, + describe, + it, + mock, +} from 'node:test'; + +import ExternalAPI from '@server/api/externalapi'; +import MusicBrainz from '@server/api/musicbrainz'; +import OpenLibraryAPI from '@server/api/openlibrary'; +import ReadarrAPI from '@server/api/servarr/readarr'; +import TheAudioDb from '@server/api/theaudiodb'; +import TmdbPersonMapper from '@server/api/themoviedb/personMapper'; +import { clearSearchProviderCache } from '@server/lib/searchProviderCache'; +import { resetSearchSuggestIndex } from '@server/lib/searchSuggest'; +import { + getSettings, + type LidarrSettings, + type ReadarrSettings, +} from '@server/lib/settings'; +import { checkUser } from '@server/middleware/auth'; +import { setupTestDb } from '@server/test/db'; +import { waitForBackgroundTasks } from '@server/utils/backgroundTasks'; +import express from 'express'; +import * as OpenApiValidator from 'express-openapi-validator'; +import rateLimit from 'express-rate-limit'; +import session from 'express-session'; +import request from 'supertest'; +import authRoutes from './auth'; +import searchRoutes, { SUGGEST_BUDGET_MS } from './search'; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +const NATE = { + id: 1_000_001, + media_type: 'person', + name: 'Nate Bargatze', + known_for_department: 'Acting', + popularity: 9, + profile_path: '/nate.jpg', + adult: false, + known_for: [ + { + id: 2_000_001, + media_type: 'movie', + title: 'Nate Bargatze: Hello World', + genre_ids: [35], + }, + ], +}; +const NATE_DIAZ = { + id: 1_000_002, + media_type: 'person', + name: 'Nate Diaz', + known_for_department: 'Acting', + popularity: 14, + adult: false, + known_for: [ + { id: 3_000_001, media_type: 'movie', title: 'UFC 196', genre_ids: [99] }, + ], +}; +const movie = (id: number, title: string, date: string, extra = {}) => ({ + id, + media_type: 'movie', + title, + original_title: title, + release_date: date, + genre_ids: [35], + popularity: 5, + vote_average: 7.4, + vote_count: 120, + poster_path: `/${id}.jpg`, + overview: '', + adult: false, + original_language: 'en', + video: false, + ...extra, +}); +const SPECIALS = [ + movie(2_000_001, 'Nate Bargatze: Hello World', '2023-01-31', { + character: 'Himself', + }), + movie( + 2_000_002, + 'Nate Bargatze: The Greatest Average American', + '2021-04-27', + { + character: 'Himself', + } + ), + movie(2_000_003, 'Nate Bargatze: The Tennessee Kid', '2019-01-29', { + character: 'Himself', + }), +]; +// a film he acted in: not a special, must not land in the specials +const ACTING_ROLE = movie(2_000_009, 'The Underdoggs', '2024-01-26', { + character: 'Coach', + genre_ids: [35], +}); +const NATE_FILM = movie(4_000_001, 'Nate', '2017-05-05', { + genre_ids: [18], + popularity: 30, +}); + +type TmdbHandler = (path: string, params: Record) => unknown; +let tmdbCalls: { path: string; params: Record }[] = []; +const mockTmdb = (handler: TmdbHandler, delayMs = 0) => { + ( + mock.method as unknown as ( + object: object, + name: string, + implementation: (...args: unknown[]) => unknown + ) => void + ).call( + mock, + ExternalAPI.prototype, + 'get', + async (endpoint: unknown, config: unknown) => { + const params = ((config as { params?: Record }) + ?.params ?? {}) as Record; + const path = String(endpoint); + tmdbCalls.push({ path, params }); + if (delayMs) await sleep(delayMs); + const answer = handler(path, params); + if (answer !== undefined) return answer; + if (path === '/search.json') return { numFound: 0, start: 0, docs: [] }; + return { page: 1, total_pages: 1, total_results: 0, results: [] }; + } + ); +}; + +const nateHandler: TmdbHandler = (path, params) => { + if (path === '/search/multi') { + return { + page: 1, + total_pages: 1, + total_results: 2, + results: [ + NATE_FILM, + // TMDB's own multi search for "nate standup" finds next to nothing + ].filter(() => String(params.query) !== 'nate standup'), + }; + } + if (path === '/search/person') + return { + page: 1, + total_pages: 1, + total_results: 2, + results: [NATE_DIAZ, NATE], + }; + if (path === '/search/movie') + return { + page: 1, + total_pages: 1, + total_results: 2, + results: [NATE_FILM, SPECIALS[0]], + }; + if (path === `/person/${NATE.id}/combined_credits`) + return { id: NATE.id, cast: [...SPECIALS, ACTING_ROLE], crew: [] }; + if (path === '/discover/movie') + return { + page: 1, + total_pages: 1, + total_results: 1, + results: [SPECIALS[2]], + }; + return undefined; +}; + +const quietProviders = () => { + mock.method(MusicBrainz.prototype, 'searchAlbumWithTotal', async () => ({ + results: [], + totalResults: 0, + })); + mock.method(MusicBrainz.prototype, 'searchArtistWithTotal', async () => ({ + results: [], + totalResults: 0, + })); + mock.method(TmdbPersonMapper.prototype, 'batchGetMappings', async () => ({})); + mock.method(TheAudioDb.prototype, 'batchGetArtistImages', async () => ({})); +}; + +let app: express.Express; +let server: Server; +let baseUrl = ''; + +const createApp = () => { + const created = express(); + created.use(express.json()); + created.use( + session({ + secret: randomBytes(32).toString('hex'), + cookie: { secure: 'auto' }, + resave: false, + saveUninitialized: false, + }) + ); + created.use(rateLimit({ windowMs: 60_000, limit: 10_000 }), checkUser); + created.use('/auth', authRoutes); + created.use('/search', searchRoutes); + created.use( + ( + err: { status?: number; message?: string }, + _req: express.Request, + res: express.Response, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _next: express.NextFunction + ) => { + res + .status(err.status ?? 500) + .json({ status: err.status ?? 500, message: err.message }); + } + ); + return created; +}; + +const login = async () => { + const settings = getSettings(); + const prior = settings.main.localLogin; + settings.main.localLogin = true; + try { + const agent = request.agent(app); + const res = await agent + .post('/auth/local') + .send({ email: 'friend@seerr.dev', password: 'test1234' }); + assert.equal(res.status, 200); + return { + agent, + cookie: String(res.headers['set-cookie']?.[0] ?? '').split(';')[0], + }; + } finally { + settings.main.localLogin = prior; + } +}; + +type StreamEvent = { + type: string; + group?: string; + results?: { + mediaType: string; + id: number | string; + title?: string; + name?: string; + }[]; + topResult?: { + kind: string; + item: { id: number; name?: string }; + works: { id: number }[]; + }; + failedSources?: string[]; + intent?: { kind: string; entity: string }; + at: number; +}; +const readStream = async (query: Record, cookie: string) => { + const started = performance.now(); + const response = await fetch( + `${baseUrl}/search/stream?${new URLSearchParams(query)}`, + { + headers: { cookie }, + } + ); + assert.equal(response.status, 200); + assert.match(response.headers.get('content-type') ?? '', /ndjson/); + const reader = (response.body as ReadableStream).getReader(); + const decoder = new TextDecoder(); + const events: StreamEvent[] = []; + let buffer = ''; + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let newline = buffer.indexOf('\n'); + while (newline >= 0) { + const line = buffer.slice(0, newline).trim(); + buffer = buffer.slice(newline + 1); + newline = buffer.indexOf('\n'); + if (line) + events.push({ ...JSON.parse(line), at: performance.now() - started }); + } + } + return events; +}; + +setupTestDb(); + +before(() => { + app = createApp(); + server = app.listen(0); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); +after(() => { + server.close(); + server.closeAllConnections?.(); +}); +beforeEach(() => { + tmdbCalls = []; + getSettings().lidarr = [{ id: 0, name: 'Lidarr' } as LidarrSettings]; + getSettings().readarr = []; +}); +afterEach(async () => { + await waitForBackgroundTasks(); + mock.restoreAll(); + clearSearchProviderCache(); + resetSearchSuggestIndex(); + getSettings().lidarr = []; + getSettings().readarr = []; +}); + +describe('intent-aware global search', () => { + it('answers "nate standup" with Nate Bargatze and his specials on top', async () => { + mockTmdb(nateHandler); + quietProviders(); + const { agent } = await login(); + const res = await agent.get('/search').query({ query: 'nate standup' }); + assert.equal(res.status, 200); + assert.equal(res.body.intent.kind, 'person-works'); + assert.equal(res.body.intent.format, 'standup'); + assert.equal(res.body.topResult.kind, 'person'); + assert.equal(res.body.topResult.item.name, 'Nate Bargatze'); + assert.equal(res.body.topResult.label, 'Stand-up specials'); + const workIds = res.body.topResult.works.map( + (work: { id: number }) => work.id + ); + assert.deepEqual( + workIds, + [2_000_001, 2_000_002, 2_000_003], + 'newest special first' + ); + assert.ok( + !workIds.includes(ACTING_ROLE.id), + 'an acting role is not a special' + ); + const movies = res.body.results.filter( + (result: { mediaType: string }) => result.mediaType === 'movie' + ); + assert.equal(movies[0].title, 'Nate Bargatze: Hello World'); + assert.ok( + movies[0].matchScore > + (movies.find((m: { id: number }) => m.id === NATE_FILM.id) + ?.matchScore ?? 0) + ); + const keywordCall = tmdbCalls.find( + (call) => call.path === '/discover/movie' + ); + assert.equal(keywordCall?.params.with_keywords, '9716'); + assert.equal(keywordCall?.params.with_people, String(NATE.id)); + }); + + it('opens a series at the asked season', async () => { + mockTmdb((path) => + path === '/search/tv' + ? { + page: 1, + total_pages: 1, + total_results: 1, + results: [ + { + id: 136_315, + media_type: 'tv', + name: 'The Bear', + original_name: 'The Bear', + first_air_date: '2022-06-23', + origin_country: ['US'], + genre_ids: [18, 35], + popularity: 80, + overview: '', + vote_average: 8, + vote_count: 1000, + original_language: 'en', + }, + ], + } + : undefined + ); + quietProviders(); + const { agent } = await login(); + const res = await agent + .get('/search') + .query({ query: 'the bear season 3' }); + assert.equal(res.status, 200); + assert.equal(res.body.topResult.kind, 'title'); + assert.equal(res.body.topResult.item.id, 136_315); + assert.equal(res.body.topResult.season, 3); + }); + + it('browses "2015 horror" by genre and year', async () => { + mockTmdb((path) => + path === '/discover/movie' + ? { + page: 1, + total_pages: 1, + total_results: 1, + results: [ + movie(270_303, 'It Follows', '2015-03-13', { + genre_ids: [27], + popularity: 40, + }), + ], + } + : undefined + ); + quietProviders(); + const { agent } = await login(); + const res = await agent.get('/search').query({ query: '2015 horror' }); + assert.equal(res.status, 200); + assert.equal(res.body.intent.kind, 'discover'); + const discover = tmdbCalls.find((call) => call.path === '/discover/movie'); + assert.equal(discover?.params.with_genres, '27'); + assert.equal(discover?.params['primary_release_date.gte'], '2015-01-01'); + assert.equal(discover?.params['primary_release_date.lte'], '2015-12-31'); + assert.equal(res.body.results[0].title, 'It Follows'); + }); + + it('asks MusicBrainz for live albums on " live"', async () => { + mockTmdb(() => undefined); + const albumSearch = mock.method( + MusicBrainz.prototype, + 'searchAlbumWithTotal', + async () => ({ + results: [], + totalResults: 0, + }) + ); + const artistSearch = mock.method( + MusicBrainz.prototype, + 'searchArtistWithTotal', + async () => ({ + results: [], + totalResults: 0, + }) + ); + mock.method( + TmdbPersonMapper.prototype, + 'batchGetMappings', + async () => ({}) + ); + mock.method(TheAudioDb.prototype, 'batchGetArtistImages', async () => ({})); + const { agent } = await login(); + const res = await agent.get('/search').query({ query: 'metallica live' }); + assert.equal(res.status, 200); + const albumQuery = ( + albumSearch.mock.calls[0].arguments[0] as { query: string } + ).query; + assert.match(albumQuery, /artist:\(metallica\)/); + assert.match(albumQuery, /secondarytype:live/); + assert.equal( + (artistSearch.mock.calls[0].arguments[0] as { query: string }).query, + 'metallica' + ); + }); + + it('falls back to a "did you mean" correction when nothing matches', async () => { + mockTmdb(nateHandler); + quietProviders(); + const { agent } = await login(); + // teach the index the name, as an earlier search would + await agent.get('/search').query({ query: 'nate standup' }); + mock.restoreAll(); + mockTmdb((path, params) => + path === '/search/multi' && params.query === 'nate bargatze' + ? { page: 1, total_pages: 1, total_results: 1, results: [NATE] } + : undefined + ); + quietProviders(); + const res = await agent.get('/search').query({ query: 'nate bergatze' }); + assert.equal(res.status, 200); + assert.equal(res.body.correctedQuery, 'nate bargatze'); + assert.equal(res.body.results[0].name, 'Nate Bargatze'); + assert.equal(res.body.topResult?.item.name, 'Nate Bargatze'); + }); +}); + +describe('stand-up specials of the person only', () => { + it("leaves out a relative's special, guest spots and specials they produced", async () => { + // his father's special shares the surname; he guests in another comedian's + // special; he produced a third, which TMDB's people filter also returns + const RELATIVE = movie( + 5_000_001, + 'Stephen Bargatze: Out in a Minute', + '2023-06-01', + { + character: 'Himself', + order: 2, + } + ); + const GUEST = movie(5_000_002, 'Are We Good?', '2024-02-01', { + character: 'Self', + order: 3, + }); + const PRODUCED = movie( + 5_000_003, + 'Ryan Hamilton: This Just Hit Me', + '2024-05-01', + { + job: 'Executive Producer', + department: 'Production', + } + ); + mockTmdb((path, params) => { + if (path === `/person/${NATE.id}/combined_credits`) + return { + id: NATE.id, + cast: [...SPECIALS, ACTING_ROLE, RELATIVE, GUEST], + crew: [{ ...PRODUCED, job: 'Writer', department: 'Writing' }], + }; + if (path === '/discover/movie') + return { + page: 1, + total_pages: 1, + total_results: 2, + results: [SPECIALS[2], PRODUCED], + }; + if (path === '/search/movie') + return { + page: 1, + total_pages: 1, + total_results: 3, + results: [NATE_FILM, SPECIALS[0], RELATIVE], + }; + return nateHandler(path, params); + }); + quietProviders(); + const { agent } = await login(); + const res = await agent.get('/search').query({ query: 'nate standup' }); + assert.equal(res.status, 200); + assert.deepEqual( + res.body.topResult.works.map((work: { id: number }) => work.id), + [2_000_001, 2_000_002, 2_000_003] + ); + }); +}); + +describe('GET /search/stream', () => { + it('streams fast results first while a slow catalog fills in later', async () => { + mockTmdb(nateHandler, 40); + quietProviders(); + getSettings().readarr = [ + { + id: 7, + hostname: 'bookshelf.test', + port: 8787, + apiKey: 'test', + useSsl: false, + baseUrl: '', + serviceType: 'ebook', + } as ReadarrSettings, + ]; + mock.method(ReadarrAPI.prototype, 'lookupAuthor', async () => { + await sleep(1_500); + return [{ foreignAuthorId: 'a-1', authorName: 'Nate Author' }]; + }); + mock.method(OpenLibraryAPI.prototype, 'searchAuthors', async () => ({ + numFound: 0, + start: 0, + docs: [], + })); + const { cookie } = await login(); + const events = await readStream( + { query: 'nate standup', groups: 'video,music,authors' }, + cookie + ); + assert.equal(events[0].type, 'intent'); + assert.equal(events[0].intent?.entity, 'nate'); + const video = events.find( + (event) => event.type === 'results' && event.group === 'video' + ); + const authors = events.find( + (event) => event.type === 'results' && event.group === 'authors' + ); + assert.ok(video && authors); + assert.equal(video.topResult?.item.name, 'Nate Bargatze'); + assert.ok(video.at < 700, `first results after ${Math.round(video.at)} ms`); + assert.ok(authors.at > video.at + 1_000, 'the slow catalog answered later'); + assert.equal(authors.results?.[0].name, 'Nate Author'); + const done = events[events.length - 1]; + assert.equal(done.type, 'done'); + assert.deepEqual(done.failedSources, []); + }); + + it('names the sources that did not answer and keeps the rest', async () => { + mockTmdb(nateHandler); + mock.method(MusicBrainz.prototype, 'searchAlbumWithTotal', async () => { + throw Object.assign(new Error('503 Service Unavailable'), { + response: { status: 503 }, + }); + }); + mock.method(MusicBrainz.prototype, 'searchArtistWithTotal', async () => { + throw new Error('503 Service Unavailable'); + }); + mock.method( + TmdbPersonMapper.prototype, + 'batchGetMappings', + async () => ({}) + ); + mock.method(TheAudioDb.prototype, 'batchGetArtistImages', async () => ({})); + const { cookie } = await login(); + const events = await readStream( + { query: 'nate standup', groups: 'video,music' }, + cookie + ); + const video = events.find( + (event) => event.type === 'results' && event.group === 'video' + ); + assert.ok(video?.results?.length); + const done = events[events.length - 1]; + assert.equal(done.type, 'done'); + assert.deepEqual(done.failedSources, ['Music']); + }); + + it('rejects unknown groups', async () => { + const { agent } = await login(); + const res = await agent + .get('/search/stream') + .query({ query: 'x', groups: 'video,nope' }); + assert.equal(res.status, 400); + }); +}); + +describe('GET /search/suggest', () => { + it('suggests people, titles and intent queries from what search learned', async () => { + mockTmdb(nateHandler); + quietProviders(); + const { agent } = await login(); + await agent.get('/search').query({ query: 'nate standup' }); + + const partial = await agent + .get('/search/suggest') + .query({ q: 'nate barg' }); + assert.equal(partial.status, 200); + assert.equal(partial.body.people[0].title, 'Nate Bargatze'); + assert.ok(partial.body.elapsedMs <= SUGGEST_BUDGET_MS + 50); + + const typing = await agent.get('/search/suggest').query({ q: 'nate st' }); + assert.ok( + typing.body.queries.some( + (entry: { text: string; kind: string }) => + entry.text === 'Nate Bargatze stand-up specials' && + entry.kind === 'intent' + ), + JSON.stringify(typing.body.queries) + ); + assert.ok( + typing.body.titles.some((title: { title: string }) => + title.title.startsWith('Nate Bargatze:') + ) + ); + + const typo = await agent.get('/search/suggest').query({ q: 'bergatze' }); + assert.equal(typo.body.didYouMean, 'bargatze'); + assert.equal(typo.body.people[0]?.title, 'Nate Bargatze'); + }); + + it('answers within the budget from TMDB when the index knows nothing yet', async () => { + mockTmdb(nateHandler, 20); + const { agent } = await login(); + const res = await agent.get('/search/suggest').query({ q: 'nate' }); + assert.equal(res.status, 200); + assert.ok( + res.body.elapsedMs <= SUGGEST_BUDGET_MS + 50, + `${res.body.elapsedMs} ms` + ); + assert.ok( + res.body.titles.some((title: { title: string }) => title.title === 'Nate') + ); + }); + + it('leaves out categories the account cannot use and short queries', async () => { + const { agent } = await login(); + const short = await agent.get('/search/suggest').query({ q: 'n' }); + assert.deepEqual(short.body.titles, []); + const oversized = await agent + .get('/search/suggest') + .query({ q: 'x'.repeat(101) }); + assert.equal(oversized.status, 400); + }); +}); + +describe('search endpoints behind the OpenAPI validator', () => { + it('admits the stream and suggest parameters', async () => { + const validated = express(); + validated.use( + OpenApiValidator.middleware({ + apiSpec: path.join(process.cwd(), 'seerr-api.yml'), + validateRequests: true, + validateSecurity: false, + }) + ); + validated.get('/api/v1/search/stream', (_req, res) => + res.status(200).json({}) + ); + validated.get('/api/v1/search/suggest', (_req, res) => + res.status(200).json({}) + ); + validated.use( + ( + error: { status?: number; message?: string }, + _req: express.Request, + res: express.Response, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _next: express.NextFunction + ) => res.status(error.status ?? 500).json({ message: error.message }) + ); + const stream = await request(validated).get('/api/v1/search/stream').query({ + query: 'nate standup', + page: 1, + groups: 'video,music', + language: 'en', + }); + assert.equal(stream.status, 200, JSON.stringify(stream.body)); + const suggest = await request(validated) + .get('/api/v1/search/suggest') + .query({ q: 'nate barg', language: 'en' }); + assert.equal(suggest.status, 200, JSON.stringify(suggest.body)); + }); +}); diff --git a/server/routes/searchTiming.bench.ts b/server/routes/searchTiming.bench.ts new file mode 100644 index 0000000000..bf6e289220 --- /dev/null +++ b/server/routes/searchTiming.bench.ts @@ -0,0 +1,354 @@ +/** + * Search timing benchmark with mocked providers. + * + * Run it on demand (the default test glob skips *.bench.ts): + * node server/test/index.mts server/routes/searchTiming.bench.ts + * Each provider answers after a fixed, realistic + * delay (or hangs, like a busy Bookshelf or a 503-ing MusicBrainz), and the + * bench reports how long the classic GET /search takes, how long the streamed + * GET /search/stream takes to deliver its first results and to finish, and how + * long GET /search/suggest takes. + */ +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import type { AddressInfo } from 'node:net'; +import { after, afterEach, before, describe, it, mock } from 'node:test'; + +import ComicVineAPI from '@server/api/comicvine'; +import ExternalAPI from '@server/api/externalapi'; +import MusicBrainz from '@server/api/musicbrainz'; +import OpenLibraryAPI from '@server/api/openlibrary'; +import ReadarrAPI from '@server/api/servarr/readarr'; +import TheAudioDb from '@server/api/theaudiodb'; +import TmdbPersonMapper from '@server/api/themoviedb/personMapper'; +import { clearSearchProviderCache } from '@server/lib/searchProviderCache'; +import { resetSearchSuggestIndex } from '@server/lib/searchSuggest'; +import { + getSettings, + type LidarrSettings, + type ReadarrSettings, +} from '@server/lib/settings'; +import { checkUser } from '@server/middleware/auth'; +import { setupTestDb } from '@server/test/db'; +import { waitForBackgroundTasks } from '@server/utils/backgroundTasks'; +import express from 'express'; +import rateLimit from 'express-rate-limit'; +import session from 'express-session'; +import type { Server } from 'node:http'; +import authRoutes from './auth'; +import searchRoutes from './search'; + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +type Scenario = { + name: string; + tmdbMs: number; + musicBrainzMs: number | 'hang'; + openLibraryMs: number; + bookshelfMs: number | 'hang'; + comicVineMs: number; +}; +const scenarios: Scenario[] = [ + { + name: 'healthy', + tmdbMs: 250, + musicBrainzMs: 1_400, + openLibraryMs: 1_100, + bookshelfMs: 600, + comicVineMs: 800, + }, + { + name: 'busy (Bookshelf + MusicBrainz stall)', + tmdbMs: 250, + musicBrainzMs: 'hang', + openLibraryMs: 1_100, + bookshelfMs: 'hang', + comicVineMs: 800, + }, +]; + +const NATE = { + id: 1_000_001, + media_type: 'person', + name: 'Nate Bargatze', + known_for_department: 'Acting', + popularity: 12, + profile_path: '/nate.jpg', + known_for: [ + { + id: 2_000_001, + media_type: 'movie', + title: 'Nate Bargatze: Hello World', + genre_ids: [35], + }, + ], +}; +const specials = [ + ['Nate Bargatze: Hello World', '2023-01-31'], + ['Nate Bargatze: The Greatest Average American', '2021-04-27'], + ['Nate Bargatze: The Tennessee Kid', '2019-01-29'], + ['Your Friend, Nate Bargatze', '2024-12-24'], +].map(([title, date], index) => ({ + id: 2_000_001 + index, + media_type: 'movie', + title, + original_title: title, + release_date: date, + genre_ids: [35], + character: 'Himself', + popularity: 8 - index, + vote_average: 7.5, + vote_count: 100, + poster_path: `/special-${index}.jpg`, + overview: 'Stand-up special', + adult: false, + original_language: 'en', +})); + +let server: Server; +let baseUrl = ''; +let cookie = ''; + +const install = (s: Scenario) => { + const wait = async (value: number | 'hang') => { + if (value === 'hang') { + await sleep(16_000); + throw new Error('503 Service Unavailable'); + } + await sleep(value); + }; + ( + mock.method as unknown as ( + o: object, + m: string, + f: (...a: unknown[]) => unknown + ) => void + ).call(mock, ExternalAPI.prototype, 'get', async (endpoint: unknown) => { + const path = String(endpoint); + await sleep(s.tmdbMs); + if (path === '/search/multi') + return { + page: 1, + total_pages: 1, + total_results: 2, + results: [{ ...NATE }, { ...specials[0], character: undefined }], + }; + if (path === '/search/person') + return { page: 1, total_pages: 1, total_results: 1, results: [NATE] }; + if (path.startsWith('/person/') && path.endsWith('/combined_credits')) + return { id: NATE.id, cast: specials, crew: [] }; + if (path === '/discover/movie') + return { + page: 1, + total_pages: 1, + total_results: specials.length, + results: specials, + }; + if ( + path === '/search/collection' || + path === '/search/movie' || + path === '/search/tv' + ) + return { page: 1, total_pages: 1, total_results: 0, results: [] }; + if (path === '/search.json') { + return { numFound: 0, start: 0, docs: [] }; + } + if (path.startsWith('/movie/') || path.startsWith('/tv/')) + return { + id: 1, + release_dates: { results: [] }, + content_ratings: { results: [] }, + }; + return { page: 1, total_pages: 1, total_results: 0, results: [] }; + }); + mock.method(MusicBrainz.prototype, 'searchAlbumWithTotal', async () => { + await wait(s.musicBrainzMs); + return { results: [], totalResults: 0 }; + }); + mock.method(MusicBrainz.prototype, 'searchArtistWithTotal', async () => { + await wait(s.musicBrainzMs); + return { results: [], totalResults: 0 }; + }); + mock.method(OpenLibraryAPI.prototype, 'searchBooks', async () => { + await sleep(s.openLibraryMs); + return { numFound: 0, start: 0, docs: [] }; + }); + mock.method(OpenLibraryAPI.prototype, 'searchAuthors', async () => { + await sleep(s.openLibraryMs); + return { numFound: 0, start: 0, docs: [] }; + }); + mock.method(ReadarrAPI.prototype, 'lookupBook', async () => { + await wait(s.bookshelfMs); + return []; + }); + mock.method(ReadarrAPI.prototype, 'lookupAuthor', async () => { + await wait(s.bookshelfMs); + return []; + }); + mock.method(ComicVineAPI.prototype, 'searchVolumes', async () => { + await sleep(s.comicVineMs); + return { + error: 'OK', + limit: 20, + offset: 0, + number_of_page_results: 0, + number_of_total_results: 0, + status_code: 1, + results: [], + }; + }); + mock.method(TmdbPersonMapper.prototype, 'batchGetMappings', async () => ({})); + mock.method(TheAudioDb.prototype, 'batchGetArtistImages', async () => ({})); +}; + +const timeClassic = async (query: string) => { + const started = performance.now(); + const response = await fetch( + `${baseUrl}/search?${new URLSearchParams({ query })}`, + { headers: { cookie } } + ); + await response.json(); + return Math.round(performance.now() - started); +}; + +const timeStream = async (query: string) => { + const started = performance.now(); + const response = await fetch( + `${baseUrl}/search/stream?${new URLSearchParams({ query })}`, + { headers: { cookie } } + ); + if (response.status === 404) return undefined; + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + let first: number | undefined; + let topResult: number | undefined; + let video: number | undefined; + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + let newline = buffer.indexOf('\n'); + while (newline >= 0) { + const line = buffer.slice(0, newline); + buffer = buffer.slice(newline + 1); + newline = buffer.indexOf('\n'); + if (!line.trim()) continue; + const event = JSON.parse(line) as { + type: string; + group?: string; + results?: unknown[]; + topResult?: unknown; + }; + const now = Math.round(performance.now() - started); + if (event.type === 'results' && event.results?.length && !first) + first = now; + if (event.type === 'results' && event.group === 'video') video = now; + if (event.topResult && !topResult) topResult = now; + } + } + return { + firstResults: first, + video, + topResult, + complete: Math.round(performance.now() - started), + }; +}; + +const timeSuggest = async (query: string) => { + const started = performance.now(); + const response = await fetch( + `${baseUrl}/search/suggest?${new URLSearchParams({ q: query })}`, + { headers: { cookie } } + ); + if (response.status === 404) return undefined; + await response.json(); + return Math.round(performance.now() - started); +}; + +describe('search timing benchmark', () => { + setupTestDb(); + + before(async () => { + const app = express(); + app.use(express.json()); + app.use( + session({ + secret: randomBytes(32).toString('hex'), + cookie: { secure: 'auto' }, + resave: false, + saveUninitialized: false, + }) + ); + app.use(rateLimit({ windowMs: 60_000, limit: 10_000 }), checkUser); + app.use('/auth', authRoutes); + app.use('/search', searchRoutes); + server = app.listen(0); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + }); + after(() => { + server?.close(); + server?.closeAllConnections?.(); + }); + afterEach(async () => { + await waitForBackgroundTasks(); + mock.restoreAll(); + }); + + it('reports classic, streamed and suggest timings', async () => { + const settings = getSettings(); + settings.main.localLogin = true; + const login = await fetch(`${baseUrl}/auth/local`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'friend@seerr.dev', password: 'test1234' }), + }); + assert.equal(login.status, 200); + cookie = (login.headers.get('set-cookie') ?? '').split(';')[0]; + settings.main.comicVineApiKey = 'bench-key'; + settings.lidarr = [{ id: 0, name: 'Lidarr' } as LidarrSettings]; + settings.readarr = [ + { + id: 7, + hostname: 'bookshelf.test', + port: 8787, + apiKey: 'bench', + useSsl: false, + baseUrl: '', + serviceType: 'ebook', + } as ReadarrSettings, + ]; + + const rows: string[] = []; + for (const scenario of scenarios) { + install(scenario); + // every run starts with cold caches and an empty suggestion index + const cold = () => { + clearSearchProviderCache(); + resetSearchSuggestIndex(); + }; + cold(); + const suggestCold = await timeSuggest('nate barg'); + cold(); + const classic = await timeClassic('nate standup'); + cold(); + const stream = await timeStream('nate standup'); + // the stream taught the index "Nate Bargatze" + const suggest = await timeSuggest('nate barg'); + const suggestTypo = await timeSuggest('bergatze'); + rows.push( + `${scenario.name}: classic GET /search ${classic} ms` + + (stream + ? ` | stream: first results ${stream.firstResults} ms, video+top result ${stream.topResult} ms, all done ${stream.complete} ms` + : ' | stream n/a') + + (suggest !== undefined + ? ` | suggest: cold ${suggestCold} ms, warm ${suggest} ms, typo ${suggestTypo} ms` + : ' | suggest n/a') + ); + await waitForBackgroundTasks(); + mock.restoreAll(); + } + // eslint-disable-next-line no-console + console.log(`\nSEARCH BENCH\n${rows.join('\n')}\n`); + }); +}); diff --git a/src/i18n/apiMessages.ts b/src/i18n/apiMessages.ts index f59c0f17a1..ce501e6582 100644 --- a/src/i18n/apiMessages.ts +++ b/src/i18n/apiMessages.ts @@ -82,6 +82,7 @@ export const apiMessages: Record< m053d64cdb6bb108bb03d: 'Sportarr quality profile must be a positive integer', m056a1948099f9b30635e: 'This adult scene is blocklisted.', m058efc336f3cb16247d0: 'The AI provider did not find that model or URL.', + m059d378dcd252eadde7e: 'Unknown group.', m05be21b447e46cab5128: 'BookOrbit sets scope visibility when the scope is created. Change this grouping’s visibility in BookOrbit, or remove the SeerrNG-managed scope and create it again.', m05e26dcf8a5c67102cb4: 'Cannot refresh Trakt token without a refresh token', @@ -860,6 +861,7 @@ export const apiMessages: Record< m3a6b2cf84156fb6b9625: 'A valid service ID is required for service admission.', m3a869f82af3294e3b3be: 'Unable to retrieve movie watch providers.', + m3a871ad796606381cdbe: '{value0} did not answer in time.', m3a88700c18ea37a62b14: '{value0} must use one of the supported shadow values.', m3a8a8df9111bce9e1ca1: 'Bookshelf ebook server not configured', @@ -2084,6 +2086,7 @@ export const apiMessages: Record< m8b6b0d42f0707af0f39f: 'A request for this magazine already exists.', m8b7741e1aac03b859db0: '{value0} must be at most {value1} characters.', m8b83363faf5540e7fb69: 'Sportarr returned an invalid {value0} list.', + m8b930328dd402c0300db: 'Search failed.', m8ba020c75e047a8ef847: 'Unable to retrieve book details.', m8babbcacd4584f331250: 'You do not have permission to make comic requests.', m8bbbcb298e40333bd9ad: 'Library lookup failed.', @@ -2930,6 +2933,7 @@ export const apiMessages: Record< mc72069ca3d442af8ac8f: 'Settings path must be a regular file.', mc73fee6c5396519dd225: 'BookOrbit connection needs an account and password.', mc74896863adb52dfa21b: 'User settings body must be an object.', + mc76e7bca13022526f579: '503 Service Unavailable', mc7736058413ee241e5c4: 'Unable to submit request.', mc7a46d91ce09d577f6c1: 'Aurral artist MBID must be a valid UUID.', mc7c17d51f450414ddbc9: 'Kavita returned an unexpectedly large library.', diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 0be42fe622..d92a104805 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -7676,6 +7676,7 @@ "utils.ApiMessage.m053d64cdb6bb108bb03d": "Sportarr quality profile must be a positive integer", "utils.ApiMessage.m056a1948099f9b30635e": "This adult scene is blocklisted.", "utils.ApiMessage.m058efc336f3cb16247d0": "The AI provider did not find that model or URL.", + "utils.ApiMessage.m059d378dcd252eadde7e": "Unknown group.", "utils.ApiMessage.m05be21b447e46cab5128": "BookOrbit sets scope visibility when the scope is created. Change this grouping’s visibility in BookOrbit, or remove the SeerrNG-managed scope and create it again.", "utils.ApiMessage.m05e26dcf8a5c67102cb4": "Cannot refresh Trakt token without a refresh token", "utils.ApiMessage.m05f73fd10a09b2ff6f16": "You can have up to {value0} active recordings.", @@ -8300,6 +8301,7 @@ "utils.ApiMessage.m3a3c19b21d003f376119": "BookOrbit could not find the managed Kobo Collection. SeerrNG will try to recreate it on the next sync.", "utils.ApiMessage.m3a6b2cf84156fb6b9625": "A valid service ID is required for service admission.", "utils.ApiMessage.m3a869f82af3294e3b3be": "Unable to retrieve movie watch providers.", + "utils.ApiMessage.m3a871ad796606381cdbe": "{value0} did not answer in time.", "utils.ApiMessage.m3a88700c18ea37a62b14": "{value0} must use one of the supported shadow values.", "utils.ApiMessage.m3a8a8df9111bce9e1ca1": "Bookshelf ebook server not configured", "utils.ApiMessage.m3a92414194497eaed76e": "You have reached the maximum number of availability subscriptions.", @@ -9274,6 +9276,7 @@ "utils.ApiMessage.m8b6b0d42f0707af0f39f": "A request for this magazine already exists.", "utils.ApiMessage.m8b7741e1aac03b859db0": "{value0} must be at most {value1} characters.", "utils.ApiMessage.m8b83363faf5540e7fb69": "Sportarr returned an invalid {value0} list.", + "utils.ApiMessage.m8b930328dd402c0300db": "Search failed.", "utils.ApiMessage.m8ba020c75e047a8ef847": "Unable to retrieve book details.", "utils.ApiMessage.m8babbcacd4584f331250": "You do not have permission to make comic requests.", "utils.ApiMessage.m8bbbcb298e40333bd9ad": "Library lookup failed.", @@ -9948,6 +9951,7 @@ "utils.ApiMessage.mc72069ca3d442af8ac8f": "Settings path must be a regular file.", "utils.ApiMessage.mc73fee6c5396519dd225": "BookOrbit connection needs an account and password.", "utils.ApiMessage.mc74896863adb52dfa21b": "User settings body must be an object.", + "utils.ApiMessage.mc76e7bca13022526f579": "503 Service Unavailable", "utils.ApiMessage.mc7736058413ee241e5c4": "Unable to submit request.", "utils.ApiMessage.mc7a46d91ce09d577f6c1": "Aurral artist MBID must be a valid UUID.", "utils.ApiMessage.mc7c17d51f450414ddbc9": "Kavita returned an unexpectedly large library.", From 9c32f26ba00a7baa2fca6197f38c4ea64b9f1a8f Mon Sep 17 00:00:00 2001 From: Ncbudd Date: Fri, 27 Nov 2026 22:27:01 -0500 Subject: [PATCH 2/4] feat(search): seed the did-you-mean dictionary with popular people and specials Corrections only knew words from the library and earlier answers, so "bergatze" found nothing until someone had searched for Nate Bargatze. The suggestion index now also holds TMDB's popular people (5 pages) and popular stand-up specials (keyword 9716, 5 pages; their titles carry the comedians' names), refreshed daily and triggered by suggest and stream. Library people were already indexed through the library entries' words. Intent query suggestions now attach to the right kind of match: stand-up to a person, live albums to an artist, a season to a series. --- config/i18n/api-message-sources.json | 174 +++++++++++++-------------- server/api/themoviedb/index.ts | 34 ++++++ server/lib/searchSuggest.ts | 22 ++++ server/routes/search.ts | 171 ++++++++++++++++++++------ server/routes/searchSmart.test.ts | 42 +++++++ 5 files changed, 316 insertions(+), 127 deletions(-) diff --git a/config/i18n/api-message-sources.json b/config/i18n/api-message-sources.json index 7ece1fdf7a..dbde7732f0 100644 --- a/config/i18n/api-message-sources.json +++ b/config/i18n/api-message-sources.json @@ -1404,7 +1404,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 2293, + "line": 2382, "kind": "authored-message-field", "field": "message", "expression": "'Unknown group.'", @@ -5383,7 +5383,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2289, + "line": 2323, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB network response'", @@ -6004,7 +6004,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1588, + "line": 1677, "kind": "authored-message-field", "field": "message", "expression": "'LazyLibrarian, the service used for magazine searches, is unavailable. Please try again.'", @@ -6601,7 +6601,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1836, + "line": 1870, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover TV: ${e.message}`", @@ -6817,7 +6817,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2278, + "line": 2312, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie studio: ${e.message}`", @@ -7452,7 +7452,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2215, + "line": 2249, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch countries: ${e.message}`", @@ -8638,7 +8638,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1516, + "line": 1550, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover movies: ${e.message}`", @@ -8652,7 +8652,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1544, + "line": 1578, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover movies: ${e.message}`", @@ -8666,7 +8666,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1732, + "line": 1766, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch discover movies: ${e.message}`", @@ -9152,7 +9152,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1407, + "line": 1441, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV show details: ${e.message}`", @@ -9166,7 +9166,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1488, + "line": 1522, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV show details: ${e.message}`", @@ -12418,7 +12418,7 @@ }, { "path": "server/routes/search.ts", - "line": 2239, + "line": 2328, "kind": "authored-message-field", "field": "errorMessage", "expression": "e instanceof Error ? e.message : 'Unknown error'", @@ -13187,7 +13187,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 872, + "line": 961, "kind": "app-error-candidate", "field": "message", "expression": "'Magazine search timed out.'", @@ -13206,7 +13206,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1909, + "line": 1943, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB list ID must be a positive decimal ID'", @@ -14204,7 +14204,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2351, + "line": 2385, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie genres: ${e.message}`", @@ -15673,7 +15673,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2402, + "line": 2436, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV genres: ${e.message}`", @@ -15751,7 +15751,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2062, + "line": 2096, "kind": "app-error-candidate", "field": "message", "expression": "`No movie or show returned from API for ID ${imdbId}`", @@ -17170,7 +17170,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 2350, + "line": 2441, "kind": "authored-message-field", "field": "message", "expression": "`${SEARCH_SOURCE_NAMES[group]} did not answer in time.`", @@ -20395,7 +20395,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2094, + "line": 2128, "kind": "app-error-candidate", "field": "message", "expression": "`No show returned from API for ID ${tvdbId}`", @@ -21246,7 +21246,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1919, + "line": 1953, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch list ${listId}: ${e.message}`", @@ -22098,7 +22098,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1893, + "line": 1927, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch all trending: ${e.message}`", @@ -22112,7 +22112,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1947, + "line": 1981, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch all trending: ${e.message}`", @@ -22126,7 +22126,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 1975, + "line": 2009, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch all trending: ${e.message}`", @@ -23073,7 +23073,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1234, + "line": 1268, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch person combined credits: ${e.message}`", @@ -24257,7 +24257,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 2419, + "line": 2510, "kind": "authored-message-field", "field": "message", "expression": "'Unable to retrieve keyword search results.'", @@ -24301,7 +24301,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1864, + "line": 1898, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch upcoming movies: ${e.message}`", @@ -24899,7 +24899,7 @@ }, { "path": "server/routes/search.ts", - "line": 1352, + "line": 1441, "kind": "authored-message-field", "field": "error", "expression": "'OK'", @@ -24907,7 +24907,7 @@ }, { "path": "server/routes/search.ts", - "line": 1712, + "line": 1801, "kind": "authored-message-field", "field": "error", "expression": "'OK'", @@ -25969,7 +25969,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1544, + "line": 1633, "kind": "authored-message-field", "field": "message", "expression": "bookFormat === 'audiobook'\n ? 'The configured audiobook catalog is unavailable. Please try again.'\n : 'Open Library and configured book catalogs are unavailable. Please try again.'", @@ -26479,7 +26479,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2469, + "line": 2503, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch keyword: ${e.message}`", @@ -27083,7 +27083,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1514, + "line": 1603, "kind": "authored-message-field", "field": "message", "expression": "'MusicBrainz, the service used for music searches, timed out or is unavailable. Please try again.'", @@ -27188,7 +27188,7 @@ }, { "path": "server/routes/search.ts", - "line": 1574, + "line": 1663, "kind": "authored-message-field", "field": "message", "expression": "'ComicVine, the service used for comic searches, timed out or is unavailable. Please try again.'", @@ -27678,7 +27678,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2264, + "line": 2298, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid TMDB studio response'", @@ -28480,7 +28480,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2659, + "line": 2693, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV watch providers: ${e.message}`", @@ -28751,7 +28751,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1210, + "line": 1244, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch person details: ${e.message}`", @@ -28851,7 +28851,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2158, + "line": 2192, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB returned an invalid collection response.'", @@ -29040,7 +29040,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1602, + "line": 1636, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV recommendations: ${e.message}`", @@ -29138,7 +29138,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1305, + "line": 1339, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie details: ${e.message}`", @@ -32449,7 +32449,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1627, + "line": 1661, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV similar: ${e.message}`", @@ -39849,7 +39849,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 2338, + "line": 2429, "kind": "authored-message-field", "field": "message", "expression": "'Search failed.'", @@ -40562,7 +40562,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2523, + "line": 2557, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to search companies: ${e.message}`", @@ -40976,7 +40976,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2611, + "line": 2645, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie watch providers: ${e.message}`", @@ -42014,7 +42014,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2029, + "line": 2063, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to find by external ID: ${e.message}`", @@ -42329,7 +42329,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1430, + "line": 1464, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV show scan details: ${e.message}`", @@ -43325,7 +43325,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2563, + "line": 2597, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch available watch regions: ${e.message}`", @@ -43392,7 +43392,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1561, + "line": 1650, "kind": "authored-message-field", "field": "message", "expression": "'The author catalogs timed out or are unavailable. Please try again.'", @@ -44189,7 +44189,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 2447, + "line": 2538, "kind": "authored-message-field", "field": "message", "expression": "'Unable to retrieve company search results.'", @@ -48070,7 +48070,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 998, + "line": 1087, "kind": "authored-message-field", "field": "message", "expression": "'Music filters require the Music media type.'", @@ -48195,7 +48195,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1457, + "line": 1491, "kind": "app-error-candidate", "field": "message", "expression": "'TMDB returned an invalid season response.'", @@ -48911,7 +48911,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1466, + "line": 1555, "kind": "authored-message-field", "field": "errorMessage", "expression": "'Provider did not finish before the global search deadline.'", @@ -49073,7 +49073,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1544, + "line": 1633, "kind": "authored-message-field", "field": "message", "expression": "bookFormat === 'audiobook'\n ? 'The configured audiobook catalog is unavailable. Please try again.'\n : 'Open Library and configured book catalogs are unavailable. Please try again.'", @@ -49659,7 +49659,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2436, + "line": 2470, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV certifications: ${e.message}`", @@ -50707,7 +50707,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2496, + "line": 2530, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to search keyword: ${e.message}`", @@ -51628,7 +51628,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2181, + "line": 2215, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch collection: ${e.message}`", @@ -54348,7 +54348,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 2244, + "line": 2333, "kind": "authored-message-field", "field": "message", "expression": "'Unable to retrieve search results.'", @@ -55189,7 +55189,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1025, + "line": 1114, "kind": "authored-message-field", "field": "message", "expression": "'Format can only be used with book searches.'", @@ -56864,7 +56864,7 @@ "callsites": [ { "path": "server/routes/search.ts", - "line": 1505, + "line": 1594, "kind": "authored-message-field", "field": "message", "expression": "'Artist search is temporarily unavailable. Please try again.'", @@ -59519,7 +59519,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2300, + "line": 2334, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch TV network: ${e.message}`", @@ -59723,7 +59723,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 1573, + "line": 1607, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movies by keyword: ${e.message}`", @@ -63500,7 +63500,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2065, + "line": 2099, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to find media using external IMDb ID: ${e.message}`", @@ -64695,7 +64695,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2251, + "line": 2285, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch langauges: ${e.message}`", @@ -64891,7 +64891,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2114, + "line": 2148, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to get TV show using the external TVDB ID: ${e.message}`", @@ -64905,7 +64905,7 @@ }, { "path": "server/api/themoviedb/index.ts", - "line": 2134, + "line": 2168, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to get TV show using the external TVDB ID: ${e.message}`", @@ -67909,7 +67909,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2009, + "line": 2043, "kind": "app-error-candidate", "field": "message", "expression": "'Invalid external media ID'", @@ -70129,7 +70129,7 @@ "callsites": [ { "path": "server/api/themoviedb/index.ts", - "line": 2419, + "line": 2453, "kind": "app-error-candidate", "field": "message", "expression": "`[TMDB] Failed to fetch movie certifications: ${e}`", @@ -81443,7 +81443,7 @@ }, { "path": "server/lib/searchSuggest.ts", - "line": 301, + "line": 321, "kind": "authored-message-field", "field": "errorMessage", "expression": "error instanceof Error ? error.message : String(error)", @@ -81452,7 +81452,7 @@ }, { "path": "server/lib/searchSuggest.ts", - "line": 301, + "line": 321, "kind": "authored-message-field", "field": "errorMessage", "expression": "error instanceof Error ? error.message : String(error)", @@ -90146,7 +90146,7 @@ }, { "path": "server/routes/search.ts", - "line": 249, + "line": 251, "kind": "message-helper-expression", "field": "message", "expression": "({ error })", @@ -90155,7 +90155,7 @@ }, { "path": "server/routes/search.ts", - "line": 369, + "line": 371, "kind": "authored-message-field", "field": "reason", "expression": "'intent' as const", @@ -90164,7 +90164,7 @@ }, { "path": "server/routes/search.ts", - "line": 384, + "line": 386, "kind": "authored-message-field", "field": "reason", "expression": "'intent' as const", @@ -90173,7 +90173,7 @@ }, { "path": "server/routes/search.ts", - "line": 408, + "line": 410, "kind": "authored-message-field", "field": "reason", "expression": "'match' as const", @@ -90182,7 +90182,7 @@ }, { "path": "server/routes/search.ts", - "line": 530, + "line": 603, "kind": "authored-message-field", "field": "message", "expression": "parsed.error", @@ -90191,7 +90191,7 @@ }, { "path": "server/routes/search.ts", - "line": 958, + "line": 1047, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90200,7 +90200,7 @@ }, { "path": "server/routes/search.ts", - "line": 975, + "line": 1064, "kind": "authored-message-field", "field": "message", "expression": "parsedLanguage.error", @@ -90209,7 +90209,7 @@ }, { "path": "server/routes/search.ts", - "line": 987, + "line": 1076, "kind": "authored-message-field", "field": "message", "expression": "parsedType.error", @@ -90218,7 +90218,7 @@ }, { "path": "server/routes/search.ts", - "line": 992, + "line": 1081, "kind": "authored-message-field", "field": "message", "expression": "parsedMusicFilters.error", @@ -90227,7 +90227,7 @@ }, { "path": "server/routes/search.ts", - "line": 1008, + "line": 1097, "kind": "authored-message-field", "field": "message", "expression": "parsedResultFilter.error", @@ -90236,7 +90236,7 @@ }, { "path": "server/routes/search.ts", - "line": 1019, + "line": 1108, "kind": "authored-message-field", "field": "message", "expression": "parsedFormat.error", @@ -90245,7 +90245,7 @@ }, { "path": "server/routes/search.ts", - "line": 2239, + "line": 2328, "kind": "authored-message-field", "field": "errorMessage", "expression": "e instanceof Error ? e.message : 'Unknown error'", @@ -90254,7 +90254,7 @@ }, { "path": "server/routes/search.ts", - "line": 2282, + "line": 2371, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90263,7 +90263,7 @@ }, { "path": "server/routes/search.ts", - "line": 2357, + "line": 2448, "kind": "authored-message-variable", "field": "error", "expression": "'error' in outcome\n ? outcome.error\n : {\n status: outcome.status,\n message: String(outcome.body.message ?? 'Search failed.'),\n }", @@ -90272,7 +90272,7 @@ }, { "path": "server/routes/search.ts", - "line": 2357, + "line": 2448, "kind": "authored-message-variable", "field": "error", "expression": "'error' in outcome\n ? outcome.error\n : {\n status: outcome.status,\n message: String(outcome.body.message ?? 'Search failed.'),\n }", @@ -90281,7 +90281,7 @@ }, { "path": "server/routes/search.ts", - "line": 2361, + "line": 2452, "kind": "authored-message-field", "field": "message", "expression": "String(outcome.body.message ?? 'Search failed.')", @@ -90290,7 +90290,7 @@ }, { "path": "server/routes/search.ts", - "line": 2399, + "line": 2490, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90299,7 +90299,7 @@ }, { "path": "server/routes/search.ts", - "line": 2414, + "line": 2505, "kind": "authored-message-field", "field": "errorMessage", "expression": "e.message", @@ -90308,7 +90308,7 @@ }, { "path": "server/routes/search.ts", - "line": 2427, + "line": 2518, "kind": "authored-message-field", "field": "message", "expression": "parsedQuery.error", @@ -90317,7 +90317,7 @@ }, { "path": "server/routes/search.ts", - "line": 2442, + "line": 2533, "kind": "authored-message-field", "field": "errorMessage", "expression": "e.message", diff --git a/server/api/themoviedb/index.ts b/server/api/themoviedb/index.ts index 7d5449d9e7..1dd7f1986c 100644 --- a/server/api/themoviedb/index.ts +++ b/server/api/themoviedb/index.ts @@ -1158,6 +1158,40 @@ class TheMovieDb extends ExternalAPI implements TvShowProvider { } }; + public getPopularPeople = async ({ + page = 1, + language = this.locale, + }: { + page?: number; + language?: string; + } = {}): Promise => { + const data = await this.get( + '/person/popular', + { params: { page, language } }, + // popularity lists move slowly; refreshed once a day + 86_400 + ); + const response = sanitizeTmdbPagedResponse( + data, + page + ); + return { + ...response, + results: response.results + .filter( + (person) => + !!person && + Number.isSafeInteger(person.id) && + typeof person.name === 'string' && + !person.adult + ) + .map((person) => ({ + ...person, + known_for: Array.isArray(person.known_for) ? person.known_for : [], + })), + }; + }; + public searchPeople = async ({ query, page = 1, diff --git a/server/lib/searchSuggest.ts b/server/lib/searchSuggest.ts index f84722c900..d041867b60 100644 --- a/server/lib/searchSuggest.ts +++ b/server/lib/searchSuggest.ts @@ -11,6 +11,10 @@ * MusicBrainz, books, authors). What anyone searched for recently * becomes suggestable, typos included. Capped, oldest dropped. * popular TMDB trending titles and people, refreshed hourly. + * dictionary TMDB popular people and popular stand-up specials (keyword + * 9716; their titles carry the comedians' names), refreshed + * daily. Library people (creators, directors, artists, authors) + * are part of the library entries' words. * * The vocabulary of every indexed word doubles as the dictionary for "did * you mean": a query word the index does not know is replaced by the closest @@ -65,12 +69,16 @@ type IndexedEntry = SuggestEntry & { const LIBRARY_REFRESH_MS = 15 * 60 * 1000; const POPULAR_REFRESH_MS = 60 * 60 * 1000; +const DICTIONARY_REFRESH_MS = 24 * 60 * 60 * 1000; const MAX_LEARNED = 5_000; const MAX_LIBRARY = 25_000; const library = new Map(); const learned = new Map(); const popular = new Map(); +// popular people and stand-up specials, seeded daily for "did you mean" +const dictionary = new Map(); +let dictionaryLoadedAt = 0; // first letter of each word → entries, so a lookup scores a few hundred // entries instead of every one const buckets = new Map>(); @@ -215,6 +223,18 @@ export const setPopularEntries = (entries: readonly SuggestEntry[]) => { export const popularEntriesStale = () => Date.now() - popularLoadedAt > POPULAR_REFRESH_MS; +/** Seeds the "did you mean" dictionary (popular people, specials). */ +export const setDictionaryEntries = (entries: readonly SuggestEntry[]) => { + for (const entry of dictionary.values()) removeFromBuckets(entry); + dictionary.clear(); + for (const entry of entries) + index(dictionary, { ...entry, source: 'popular' }); + dictionaryLoadedAt = Date.now(); +}; + +export const dictionaryEntriesStale = () => + Date.now() - dictionaryLoadedAt > DICTIONARY_REFRESH_MS; + const MEDIA_TYPE_NAMES: Partial> = { [MediaType.MOVIE]: 'movie', [MediaType.TV]: 'tv', @@ -419,9 +439,11 @@ export const resetSearchSuggestIndex = () => { library.clear(); learned.clear(); popular.clear(); + dictionary.clear(); buckets.clear(); vocabulary.clear(); libraryLoadedAt = 0; popularLoadedAt = 0; + dictionaryLoadedAt = 0; libraryLoading = undefined; }; diff --git a/server/routes/search.ts b/server/routes/search.ts index 9dbb9afe6b..85fa22b9ef 100644 --- a/server/routes/search.ts +++ b/server/routes/search.ts @@ -62,10 +62,12 @@ import { } from '@server/lib/searchRanking'; import { correctSearchQuery, + dictionaryEntriesStale, ensureLibraryIndex, learnSearchResults, matchSuggestions, popularEntriesStale, + setDictionaryEntries, setPopularEntries, type SuggestEntry, type SuggestionMatch, @@ -456,47 +458,118 @@ const waitAtMost = (promise: Promise, ms: number) => ); }); +const toSuggestEntries = async ( + raw: Parameters[0] +): Promise => + (await mapSearchResults(raw)).flatMap((result): SuggestEntry[] => { + const item = result as unknown as Record; + if (item.adult === true) return []; + const mediaType = item.mediaType; + if (mediaType !== 'movie' && mediaType !== 'tv' && mediaType !== 'person') + return []; + const date = String(item.releaseDate ?? item.firstAirDate ?? ''); + const knownFor = Array.isArray(item.knownFor) + ? (item.knownFor as { + genreIds?: number[]; + title?: string; + name?: string; + }[]) + : []; + return [ + { + mediaType, + id: item.id as number, + title: String(item.title ?? item.name ?? ''), + year: /^\d{4}/.test(date) ? date.slice(0, 4) : undefined, + posterPath: (item.posterPath ?? item.profilePath) as string | undefined, + subtitle: + mediaType === 'person' + ? knownFor + .slice(0, 2) + .map((work) => work.title ?? work.name) + .filter(Boolean) + .join(', ') || undefined + : undefined, + popularity: Number(item.popularity ?? 0) || 0, + owned: false, + source: 'popular', + comedian: + mediaType === 'person' && + knownFor.some( + (work) => + work.genreIds?.includes(35) || + /stand.?up|special/i.test(work.title ?? work.name ?? '') + ), + }, + ]; + }); + let popularLoading = false; +let dictionaryLoading = false; +/** Pages of TMDB popular people and stand-up specials seeded daily. */ +const DICTIONARY_PEOPLE_PAGES = 5; +const DICTIONARY_STANDUP_PAGES = 5; const refreshPopularSuggestions = () => { - if (popularLoading || !popularEntriesStale()) return; - popularLoading = true; - trackBackgroundTask('search suggestion trending titles', async () => { - try { - const trending = await new TheMovieDb().getAllTrending({ - timeWindow: 'week', - }); - const mapped = await mapSearchResults(trending.results); - setPopularEntries( - mapped.flatMap((result): SuggestEntry[] => { - const item = result as unknown as Record; - if (item.adult === true) return []; - const mediaType = item.mediaType; - if ( - mediaType !== 'movie' && - mediaType !== 'tv' && - mediaType !== 'person' - ) - return []; - const date = String(item.releaseDate ?? item.firstAirDate ?? ''); - return [ - { - mediaType, - id: item.id as number, - title: String(item.title ?? item.name ?? ''), - year: /^\d{4}/.test(date) ? date.slice(0, 4) : undefined, - posterPath: (item.posterPath ?? item.profilePath) as - string | undefined, - popularity: Number(item.popularity ?? 0) || 0, - owned: false, - source: 'popular', - }, - ]; - }) - ); - } finally { - popularLoading = false; - } - }); + if (!popularLoading && popularEntriesStale()) { + popularLoading = true; + trackBackgroundTask('search suggestion trending titles', async () => { + try { + const trending = await new TheMovieDb().getAllTrending({ + timeWindow: 'week', + }); + setPopularEntries(await toSuggestEntries(trending.results)); + } finally { + popularLoading = false; + } + }); + } + // The dictionary behind "did you mean": popular people and popular + // stand-up specials (their titles carry the comedians' names), so + // "bergatze" corrects to "bargatze" before anyone searched for him. + if (!dictionaryLoading && dictionaryEntriesStale()) { + dictionaryLoading = true; + trackBackgroundTask('search suggestion dictionary', async () => { + try { + const tmdb = new TheMovieDb(); + const pages = (count: number) => + Array.from({ length: count }, (_, index) => index + 1); + const [people, specials] = await Promise.all([ + Promise.all( + pages(DICTIONARY_PEOPLE_PAGES).map((page) => + tmdb + .getPopularPeople({ page }) + .then((response) => response.results) + .catch(() => []) + ) + ), + Promise.all( + pages(DICTIONARY_STANDUP_PAGES).map((page) => + tmdb + .getDiscoverMovies({ keywords: '9716', page }) + .then((response) => + response.results.map((movie) => ({ + ...movie, + media_type: 'movie' as const, + })) + ) + .catch(() => []) + ) + ), + ]); + setDictionaryEntries( + await toSuggestEntries([ + ...people.flat().map((person) => ({ + ...person, + media_type: 'person' as const, + })), + ...specials.flat(), + ]) + ); + } finally { + dictionaryLoading = false; + } + }); + } }; // last words that are still being typed into an intent ("nate st…") @@ -732,7 +805,23 @@ async function handleSuggest(req: Request, res: Response) { : intent.season !== undefined ? `season ${intent.season}` : completion?.phrase; - const lead = matches.find((match) => match.score >= 0.75); + // the phrase belongs to a kind of thing: stand-up to a person, live + // albums to an artist, a season to a series + const phraseTypes = + intent.format === 'standup' || intent.format === 'documentary' + ? ['person'] + : intent.format === 'live' + ? ['artist'] + : intent.format === 'audiobook' + ? ['author'] + : intent.season !== undefined + ? ['tv'] + : completion?.types; + const lead = matches.find( + (match) => + match.score >= 0.75 && + (!phrase || !phraseTypes || phraseTypes.includes(match.mediaType)) + ); if (lead) { if (phrase) { queries.push({ text: `${lead.title} ${phrase}`, kind: 'intent' }); @@ -2303,6 +2392,8 @@ searchRoutes.get('/stream', async (req, res) => { ); const startedAt = Date.now(); const intent = parseSearchIntent(parsedQuery.value); + refreshPopularSuggestions(); + void ensureLibraryIndex(); let closed = false; res.on('close', () => { closed = true; diff --git a/server/routes/searchSmart.test.ts b/server/routes/searchSmart.test.ts index 6747b2cb5d..39d8801568 100644 --- a/server/routes/searchSmart.test.ts +++ b/server/routes/searchSmart.test.ts @@ -662,6 +662,48 @@ describe('GET /search/suggest', () => { assert.equal(typo.body.people[0]?.title, 'Nate Bargatze'); }); + it('corrects a misspelled comedian from the seeded dictionary without a prior search', async () => { + mockTmdb((path, params) => { + if (path === '/person/popular') + return params.page === 1 + ? { page: 1, total_pages: 5, total_results: 1, results: [NATE_DIAZ] } + : { + page: params.page, + total_pages: 5, + total_results: 1, + results: [], + }; + if (path === '/discover/movie' && params.with_keywords === '9716') + return params.page === 1 + ? { + page: 1, + total_pages: 5, + total_results: 1, + results: [SPECIALS[1]], + } + : { + page: params.page, + total_pages: 5, + total_results: 1, + results: [], + }; + return undefined; + }); + const { agent } = await login(); + // the first suggestion request seeds the dictionary in the background + await agent.get('/search/suggest').query({ q: 'zz' }); + await agent.get('/search/suggest').query({ q: 'zzz' }); + await waitForBackgroundTasks(); + assert.ok(tmdbCalls.some((call) => call.path === '/person/popular')); + const typo = await agent.get('/search/suggest').query({ q: 'bergatze' }); + assert.equal(typo.body.didYouMean, 'bargatze'); + assert.ok( + typo.body.titles.some((title: { title: string }) => + title.title.includes('Bargatze') + ) + ); + }); + it('answers within the budget from TMDB when the index knows nothing yet', async () => { mockTmdb(nateHandler, 20); const { agent } = await login(); From df70eb55f4602af14dba061b4e8c901e839d2ac6 Mon Sep 17 00:00:00 2001 From: Ncbudd Date: Sat, 28 Nov 2026 00:00:36 -0500 Subject: [PATCH 3/4] feat(lumen): search suggestions, streamed All search and a top result - the top search box suggests while typing from GET /search/suggest: query suggestions ("Nate Bargatze stand-up specials", "Did you mean"), recent searches, people and titles with an In library badge - combobox semantics: arrow keys, Enter, Escape, aria-activedescendant; taps and clicks keep focus until a choice is made, 44 px rows - 120 ms debounce; each new keystroke aborts the previous request - searchStream reads GET /search/stream line by line (groups arrive as they answer) and rejects cut-off streams so callers can fall back; runStreamedSearch merges each group into page snapshots, keeps the first top result steady and collects the sources that did not answer - All reads GET /search/stream (video, music, authors, magazines; books and comics keep their own endpoints): movies and series show as soon as they answer, slower groups fill in, typing on aborts the old search, and the classic /search is the fallback - Top result card above the sections ("nate standup": Nate Bargatze and his stand-up specials, or a series that opens at the asked season); what it shows is not repeated below, and it steps aside when a sort is chosen - sections follow the order the query asked for (intent.sections) - the quiet partial-failure note names the sources that did not answer (Music, Authors...) with Retry; "Showing results for" a correction and a "Did you mean" link - the phone search box gets the suggestions dropdown; it stays closed on arrival until something is typed, so it never covers the results - messages registered in en, fr and ar --- lumen/i18n-keys.json | 22 +- lumen/i18n-overrides.json | 66 +- lumen/src/components/SearchSuggestions.tsx | 285 +++++++++ lumen/src/components/Shell.tsx | 20 + lumen/src/components/TopResultCard.tsx | 126 ++++ lumen/src/i18n/locales/ar.generated.ts | 20 + lumen/src/i18n/locales/en.generated.ts | 20 + lumen/src/i18n/locales/fr.generated.ts | 20 + lumen/src/pages/Search.tsx | 595 ++++++++++++------ lumen/src/searchStream.ts | 134 ++++ lumen/src/searchSuggest.ts | 96 +++ lumen/src/streamedSearch.ts | 151 +++++ lumen/src/styles/search-suggest.css | 189 ++++++ lumen/tests/browser/search-stream.spec.ts | 213 +++++++ .../tests/browser/search-suggestions.spec.ts | 83 +++ lumen/tests/browser/searchFixtures.ts | 68 ++ lumen/tests/searchStream.test.mjs | 82 +++ 17 files changed, 2002 insertions(+), 188 deletions(-) create mode 100644 lumen/src/components/SearchSuggestions.tsx create mode 100644 lumen/src/components/TopResultCard.tsx create mode 100644 lumen/src/searchStream.ts create mode 100644 lumen/src/searchSuggest.ts create mode 100644 lumen/src/streamedSearch.ts create mode 100644 lumen/src/styles/search-suggest.css create mode 100644 lumen/tests/browser/search-stream.spec.ts create mode 100644 lumen/tests/browser/search-suggestions.spec.ts create mode 100644 lumen/tests/browser/searchFixtures.ts create mode 100644 lumen/tests/searchStream.test.mjs diff --git a/lumen/i18n-keys.json b/lumen/i18n-keys.json index c3bb3114a9..07ff117825 100644 --- a/lumen/i18n-keys.json +++ b/lumen/i18n-keys.json @@ -6964,5 +6964,25 @@ "lumen.bookDetail.allNarrations", "lumen.bookDetail.edition", "lumen.bookDetail.ebookEpub", - "lumen.bookDetail.pageCount" + "lumen.bookDetail.pageCount", + "lumen.search.suggest.queries", + "lumen.search.suggest.recent", + "lumen.search.suggest.people", + "lumen.search.suggest.titles", + "lumen.search.suggest.didYouMean", + "lumen.search.suggest.owned", + "lumen.search.suggest.label", + "lumen.search.top.heading", + "lumen.search.top.person", + "lumen.search.top.series", + "lumen.search.top.movie", + "lumen.search.top.openSeason", + "lumen.search.top.matches", + "lumen.search.top.knownFor", + "lumen.search.showingResultsFor", + "lumen.search.didYouMean", + "lumen.search.source.video", + "lumen.search.source.music", + "lumen.search.source.authors", + "lumen.search.source.magazines" ] diff --git a/lumen/i18n-overrides.json b/lumen/i18n-overrides.json index 8e7eb06bc4..76e94d65c7 100644 --- a/lumen/i18n-overrides.json +++ b/lumen/i18n-overrides.json @@ -5543,7 +5543,27 @@ "lumen.bookDetail.allNarrations": "All {count} narrations", "lumen.bookDetail.edition": "Edition", "lumen.bookDetail.ebookEpub": "Ebook · EPUB", - "lumen.bookDetail.pageCount": "{count} pages" + "lumen.bookDetail.pageCount": "{count} pages", + "lumen.search.suggest.people": "People", + "lumen.search.top.knownFor": "Known for", + "lumen.search.suggest.titles": "Titles", + "lumen.search.source.magazines": "Magazines", + "lumen.search.top.heading": "Top result", + "lumen.search.source.music": "Music", + "lumen.search.source.authors": "Authors", + "lumen.search.top.series": "Series", + "lumen.search.suggest.label": "Search suggestions", + "lumen.search.top.matches": "Matches", + "lumen.search.showingResultsFor": "Showing results for {term}", + "lumen.search.source.video": "Movies & TV", + "lumen.search.top.person": "Person", + "lumen.search.suggest.queries": "Searches", + "lumen.search.didYouMean": "Did you mean", + "lumen.search.top.movie": "Movie", + "lumen.search.suggest.didYouMean": "Did you mean", + "lumen.search.suggest.owned": "In library", + "lumen.search.suggest.recent": "Recent", + "lumen.search.top.openSeason": "Open season {season}" }, "fr": { "components.IssueDetails.allepisodes": "Tous les épisodes", @@ -11381,7 +11401,27 @@ "lumen.bookDetail.allNarrations": "Les {count} narrations", "lumen.bookDetail.edition": "Édition", "lumen.bookDetail.ebookEpub": "Livre numérique · EPUB", - "lumen.bookDetail.pageCount": "{count} pages" + "lumen.bookDetail.pageCount": "{count} pages", + "lumen.search.suggest.people": "Personnes", + "lumen.search.top.knownFor": "Connu pour", + "lumen.search.suggest.titles": "Titres", + "lumen.search.source.magazines": "Magazines", + "lumen.search.top.heading": "Meilleur résultat", + "lumen.search.source.music": "Musique", + "lumen.search.source.authors": "Auteurs", + "lumen.search.top.series": "Série", + "lumen.search.suggest.label": "Suggestions de recherche", + "lumen.search.top.matches": "Correspondances", + "lumen.search.showingResultsFor": "Résultats pour {term}", + "lumen.search.source.video": "Films et séries", + "lumen.search.top.person": "Personne", + "lumen.search.suggest.queries": "Recherches", + "lumen.search.didYouMean": "Vouliez-vous dire", + "lumen.search.top.movie": "Film", + "lumen.search.suggest.didYouMean": "Vouliez-vous dire", + "lumen.search.suggest.owned": "Dans la bibliothèque", + "lumen.search.suggest.recent": "Récentes", + "lumen.search.top.openSeason": "Ouvrir la saison {season}" }, "ar": { "components.IssueDetails.allepisodes": "جميع الحلقات", @@ -17236,6 +17276,26 @@ "lumen.bookDetail.allNarrations": "كل التسجيلات ({count})", "lumen.bookDetail.edition": "الإصدار", "lumen.bookDetail.ebookEpub": "كتاب إلكتروني · EPUB", - "lumen.bookDetail.pageCount": "{count} صفحة" + "lumen.bookDetail.pageCount": "{count} صفحة", + "lumen.search.suggest.people": "الأشخاص", + "lumen.search.top.knownFor": "معروف بـ", + "lumen.search.suggest.titles": "العناوين", + "lumen.search.source.magazines": "المجلات", + "lumen.search.top.heading": "أفضل نتيجة", + "lumen.search.source.music": "الموسيقى", + "lumen.search.source.authors": "المؤلفون", + "lumen.search.top.series": "مسلسل", + "lumen.search.suggest.label": "اقتراحات البحث", + "lumen.search.top.matches": "المطابقات", + "lumen.search.showingResultsFor": "عرض نتائج {term}", + "lumen.search.source.video": "الأفلام والمسلسلات", + "lumen.search.top.person": "شخص", + "lumen.search.suggest.queries": "عمليات البحث", + "lumen.search.didYouMean": "هل تقصد", + "lumen.search.top.movie": "فيلم", + "lumen.search.suggest.didYouMean": "هل تقصد", + "lumen.search.suggest.owned": "في المكتبة", + "lumen.search.suggest.recent": "الأخيرة", + "lumen.search.top.openSeason": "افتح الموسم {season}" } } diff --git a/lumen/src/components/SearchSuggestions.tsx b/lumen/src/components/SearchSuggestions.tsx new file mode 100644 index 0000000000..3c715ca60a --- /dev/null +++ b/lumen/src/components/SearchSuggestions.tsx @@ -0,0 +1,285 @@ +// The suggestions dropdown under a search box: query suggestions ("Nate Bargatze stand-up +// specials", "Did you mean"), recent searches, people and titles. A combobox: arrow keys move, +// Enter opens, Escape closes; taps and clicks keep the keyboard up until something is chosen. +import { + useEffect, + useId, + useMemo, + useRef, + useState, + type KeyboardEvent, + type ReactNode, +} from 'react'; +import { useNavigate } from 'react-router-dom'; +import { tmdbImg } from '../api'; +import { useLumenLocale } from '../i18n'; +import { Icon } from '../icons'; +import { + suggestionHref, + useSearchSuggestions, + type SuggestionItem, +} from '../searchSuggest'; +import '../styles/search-suggest.css'; + +type Option = { + key: string; + group: 'queries' | 'recent' | 'people' | 'titles'; + label: string; + detail?: string; + image?: string; + owned?: boolean; + correction?: boolean; + query?: string; + href?: string; +}; + +const thumb = (item: SuggestionItem) => + item.posterPath?.startsWith('/') ? tmdbImg(item.posterPath, 'w92') : ''; + +export function useSuggestionCombobox({ + term, + enabled, + recent = [], + onSearch, + openOnFocus = true, +}: { + term: string; + enabled: boolean; + /** Recent searches of this account, newest first. */ + recent?: string[]; + /** Runs a search for a chosen query suggestion or recent search. */ + onSearch: (query: string) => void; + /** + * False keeps the list closed when the box gains focus until something is typed (or + * ArrowDown): a box focused on arrival must not cover the results it shows. + */ + openOnFocus?: boolean; +}) { + const { t } = useLumenLocale(); + const nav = useNavigate(); + const listId = useId(); + const [focused, setFocused] = useState(false); + const [dismissed, setDismissed] = useState(false); + const [active, setActive] = useState(-1); + const trimmed = term.trim(); + const reply = useSearchSuggestions(term, enabled && focused && !dismissed); + // typing reopens a dismissed list; a term that merely arrives with the page does not + const lastTerm = useRef(trimmed); + useEffect(() => { + if (lastTerm.current === trimmed) return; + lastTerm.current = trimmed; + setDismissed(false); + }, [trimmed]); + + const options = useMemo(() => { + const list: Option[] = []; + const lower = trimmed.toLocaleLowerCase(); + for (const entry of reply?.queries ?? []) { + list.push({ + key: `q:${entry.text}`, + group: 'queries', + label: entry.text, + correction: entry.kind === 'correction', + query: entry.text, + }); + } + for (const entry of recent + .filter( + (text) => + text.toLocaleLowerCase() !== lower && + (!lower || text.toLocaleLowerCase().startsWith(lower)) + ) + .slice(0, lower ? 2 : 5)) { + list.push({ + key: `r:${entry}`, + group: 'recent', + label: entry, + query: entry, + }); + } + for (const item of [...(reply?.people ?? []), ...(reply?.titles ?? [])]) { + const href = suggestionHref(item); + if (!href) continue; + const person = + item.mediaType === 'person' || + item.mediaType === 'artist' || + item.mediaType === 'author'; + list.push({ + key: `${item.mediaType}:${item.id}`, + group: person ? 'people' : 'titles', + label: item.title, + detail: [item.year, item.subtitle].filter(Boolean).join(' · '), + image: thumb(item), + owned: item.owned, + href, + }); + } + return list; + }, [reply, recent, trimmed]); + + useEffect(() => { + setActive(-1); + }, [options]); + + const open = enabled && focused && !dismissed && options.length > 0; + const choose = (option: Option) => { + setDismissed(true); + setActive(-1); + if (option.href) nav(option.href); + else if (option.query) onSearch(option.query); + }; + + /** Handles a key in the box; true when the dropdown used it. */ + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape' && open) { + event.preventDefault(); + setDismissed(true); + return true; + } + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + if (dismissed && enabled) { + // a closed list opens (and asks for suggestions) before moving + event.preventDefault(); + setDismissed(false); + return true; + } + if (!options.length) return false; + event.preventDefault(); + const step = event.key === 'ArrowDown' ? 1 : -1; + setActive((current) => { + const next = current + step; + if (next < -1) return options.length - 1; + if (next >= options.length) return -1; + return next; + }); + return true; + } + if (event.key === 'Enter' && open && active >= 0 && options[active]) { + event.preventDefault(); + choose(options[active]); + return true; + } + if (event.key === 'Enter') setDismissed(true); + return false; + }; + + const optionId = (index: number) => `${listId}-option-${index}`; + const inputProps = { + // the box stays a search box (its native role); the list is tied to it by aria-controls + // and the highlighted option by aria-activedescendant + 'aria-controls': open ? listId : undefined, + 'aria-autocomplete': 'list' as const, + 'aria-activedescendant': open && active >= 0 ? optionId(active) : undefined, + onFocus: () => { + setFocused(true); + if (!openOnFocus) setDismissed(true); + }, + onBlur: () => setFocused(false), + }; + + const headings: Record = { + queries: t('lumen.search.suggest.queries', 'Searches'), + recent: t('lumen.search.suggest.recent', 'Recent'), + people: t('lumen.search.suggest.people', 'People'), + titles: t('lumen.search.suggest.titles', 'Titles'), + }; + const groups: ReactNode[] = []; + for (const group of ['queries', 'recent', 'people', 'titles'] as const) { + const members = options + .map((option, position) => ({ option, position })) + .filter(({ option }) => option.group === group); + if (!members.length) continue; + groups.push( +
+ + {members.map(({ option, position }) => { + return ( + // a combobox option: focus stays in the search box, which handles the arrow keys, + // Enter and Escape (aria-activedescendant points here), so the option takes none + // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/interactive-supports-focus +
event.preventDefault()} + onMouseDown={(event) => event.preventDefault()} + onMouseEnter={() => setActive(position)} + onClick={() => choose(option)} + > + {group === 'queries' || group === 'recent' ? ( + + ) : option.image ? ( + + ) : ( +
+ ); + })} +
+ ); + } + const list = open ? ( +
+ {groups} +
+ ) : null; + + return { + open, + inputProps, + handleKeyDown, + list, + close: () => setDismissed(true), + }; +} diff --git a/lumen/src/components/Shell.tsx b/lumen/src/components/Shell.tsx index f50704898d..e3264f445a 100644 --- a/lumen/src/components/Shell.tsx +++ b/lumen/src/components/Shell.tsx @@ -24,6 +24,7 @@ import { canSearchIndexers } from '../indexerPermissions'; import { canManageIssues, canReadIssues } from '../issuePermissions'; import { useLiveTvStatus } from '../liveTv'; import { scrollBehavior } from '../motion'; +import { readRecentSearches } from '../recentSearches'; import { normalizeSearchParams } from '../searchParams'; import { usePrefs } from '../settings'; import { VideoAvailabilityProvider } from '../videoAvailability'; @@ -36,6 +37,7 @@ import { useShareAvailable, } from './detail'; import { MusicPreviewBar } from './MusicPlayback'; +import { useSuggestionCombobox } from './SearchSuggestions'; // scroll position of each history entry, for Back const scrollSpots = new Map(); @@ -414,6 +416,17 @@ export default function Shell({ children }: { children: ReactNode }) { if (scope !== 'all') u.set('f', scope); return '/search' + (u.toString() ? '?' + u : ''); }; + // suggestions while typing (Music and Podcasts search their own catalogs in place) + const [recentTerms, setRecentTerms] = useState([]); + const suggestions = useSuggestionCombobox({ + term, + enabled: scope !== 'music' && scope !== 'podcast', + recent: recentTerms, + onSearch: (value) => { + setTerm(value); + nav(searchUrl(value)); + }, + }); useEffect(() => { document.body.classList.toggle('is-detail', detail); @@ -1024,6 +1037,11 @@ export default function Shell({ children }: { children: ReactNode }) { spellCheck={false} enterKeyHint="search" value={term} + {...suggestions.inputProps} + onFocus={() => { + setRecentTerms(readRecentSearches()); + suggestions.inputProps.onFocus(); + }} onChange={(e) => { const value = e.target.value; setTerm(value); @@ -1040,6 +1058,7 @@ export default function Shell({ children }: { children: ReactNode }) { nav(searchUrl(value), { replace: true }); }} onKeyDown={(e) => { + if (suggestions.handleKeyDown(e)) return; if (e.key !== 'Enter') return; const value = e.currentTarget.value; window.clearTimeout(musicTyping.current); @@ -1049,6 +1068,7 @@ export default function Shell({ children }: { children: ReactNode }) { /> / + {suggestions.list}
diff --git a/lumen/src/components/TopResultCard.tsx b/lumen/src/components/TopResultCard.tsx new file mode 100644 index 0000000000..83ccdfa171 --- /dev/null +++ b/lumen/src/components/TopResultCard.tsx @@ -0,0 +1,126 @@ +// "Top result": shown above the result sections when the search knows what you meant. A person +// comes with the works that fit the search (Nate Bargatze with his stand-up specials); a series +// asked for by season opens at that season. +import { Link } from 'react-router-dom'; +import { tmdbImg, type TitleResult } from '../api'; +import { useLumenLocale } from '../i18n'; +import type { TopResult } from '../searchStream'; +import '../styles/search-suggest.css'; +import { TitleCard } from './cards'; + +type TopItem = { + id: number | string; + mediaType: string; + title?: string; + name?: string; + posterPath?: string; + profilePath?: string; + releaseDate?: string; + firstAirDate?: string; + 'first-release-date'?: string; +}; + +const isTitle = (item: TopItem): item is TitleResult & TopItem => + (item.mediaType === 'movie' || item.mediaType === 'tv') && + typeof item.id === 'number'; + +const hrefFor = (item: TopItem, season?: number) => { + const id = encodeURIComponent(String(item.id)); + switch (item.mediaType) { + case 'person': + return `/person/${id}`; + case 'movie': + return `/movie/${id}`; + case 'tv': + return `/tv/${id}${season !== undefined ? `#season-${season}` : ''}`; + case 'collection': + return `/collection/${id}`; + case 'album': + return `/music/${id}`; + case 'artist': + return `/artist/${id}`; + case 'author': + return `/author/${id}`; + case 'book': + return `/book/${id}`; + case 'comic': + return `/comic/${id}`; + default: + return null; + } +}; + +export function TopResultCard({ top }: { top: TopResult }) { + const { t } = useLumenLocale(); + const item = top.item; + const name = item.title ?? item.name ?? ''; + const href = hrefFor(item, top.season); + if (!href || !name) return null; + const image = tmdbImg(item.profilePath ?? item.posterPath, 'w185'); + const year = String( + item.releaseDate ?? item.firstAirDate ?? item['first-release-date'] ?? '' + ).slice(0, 4); + const person = top.kind === 'person'; + const works = top.works.filter(isTitle); + const kindLabel = person + ? t('lumen.search.top.person', 'Person') + : item.mediaType === 'tv' + ? t('lumen.search.top.series', 'Series') + : item.mediaType === 'movie' + ? t('lumen.search.top.movie', 'Movie') + : ''; + return ( +
+
+ + {image ? ( + + ) : ( +
+ {works.length > 0 && ( +
+

+ {top.label ?? + (top.reason === 'intent' + ? t('lumen.search.top.matches', 'Matches') + : t('lumen.search.top.knownFor', 'Known for'))} +

+
+ {works.slice(0, 12).map((work) => ( + + ))} +
+
+ )} +
+ ); +} diff --git a/lumen/src/i18n/locales/ar.generated.ts b/lumen/src/i18n/locales/ar.generated.ts index a03c0c112d..d7ad224f9d 100644 --- a/lumen/src/i18n/locales/ar.generated.ts +++ b/lumen/src/i18n/locales/ar.generated.ts @@ -8184,4 +8184,24 @@ export const messages = { 'lumen.bookDetail.edition': 'الإصدار', 'lumen.bookDetail.ebookEpub': 'كتاب إلكتروني · EPUB', 'lumen.bookDetail.pageCount': '{count} صفحة', + 'lumen.search.suggest.queries': 'عمليات البحث', + 'lumen.search.suggest.recent': 'الأخيرة', + 'lumen.search.suggest.people': 'الأشخاص', + 'lumen.search.suggest.titles': 'العناوين', + 'lumen.search.suggest.didYouMean': 'هل تقصد', + 'lumen.search.suggest.owned': 'في المكتبة', + 'lumen.search.suggest.label': 'اقتراحات البحث', + 'lumen.search.top.heading': 'أفضل نتيجة', + 'lumen.search.top.person': 'شخص', + 'lumen.search.top.series': 'مسلسل', + 'lumen.search.top.movie': 'فيلم', + 'lumen.search.top.openSeason': 'افتح الموسم {season}', + 'lumen.search.top.matches': 'المطابقات', + 'lumen.search.top.knownFor': 'معروف بـ', + 'lumen.search.showingResultsFor': 'عرض نتائج {term}', + 'lumen.search.didYouMean': 'هل تقصد', + 'lumen.search.source.video': 'الأفلام والمسلسلات', + 'lumen.search.source.music': 'الموسيقى', + 'lumen.search.source.authors': 'المؤلفون', + 'lumen.search.source.magazines': 'المجلات', } as const; diff --git a/lumen/src/i18n/locales/en.generated.ts b/lumen/src/i18n/locales/en.generated.ts index f0942c8113..df3453cb57 100644 --- a/lumen/src/i18n/locales/en.generated.ts +++ b/lumen/src/i18n/locales/en.generated.ts @@ -8088,4 +8088,24 @@ export const messages = { 'lumen.bookDetail.edition': 'Edition', 'lumen.bookDetail.ebookEpub': 'Ebook · EPUB', 'lumen.bookDetail.pageCount': '{count} pages', + 'lumen.search.suggest.queries': 'Searches', + 'lumen.search.suggest.recent': 'Recent', + 'lumen.search.suggest.people': 'People', + 'lumen.search.suggest.titles': 'Titles', + 'lumen.search.suggest.didYouMean': 'Did you mean', + 'lumen.search.suggest.owned': 'In library', + 'lumen.search.suggest.label': 'Search suggestions', + 'lumen.search.top.heading': 'Top result', + 'lumen.search.top.person': 'Person', + 'lumen.search.top.series': 'Series', + 'lumen.search.top.movie': 'Movie', + 'lumen.search.top.openSeason': 'Open season {season}', + 'lumen.search.top.matches': 'Matches', + 'lumen.search.top.knownFor': 'Known for', + 'lumen.search.showingResultsFor': 'Showing results for {term}', + 'lumen.search.didYouMean': 'Did you mean', + 'lumen.search.source.video': 'Movies & TV', + 'lumen.search.source.music': 'Music', + 'lumen.search.source.authors': 'Authors', + 'lumen.search.source.magazines': 'Magazines', } as const; diff --git a/lumen/src/i18n/locales/fr.generated.ts b/lumen/src/i18n/locales/fr.generated.ts index 92f7a8227a..3ba4952477 100644 --- a/lumen/src/i18n/locales/fr.generated.ts +++ b/lumen/src/i18n/locales/fr.generated.ts @@ -8882,4 +8882,24 @@ export const messages = { 'lumen.bookDetail.edition': 'Édition', 'lumen.bookDetail.ebookEpub': 'Livre numérique · EPUB', 'lumen.bookDetail.pageCount': '{count} pages', + 'lumen.search.suggest.queries': 'Recherches', + 'lumen.search.suggest.recent': 'Récentes', + 'lumen.search.suggest.people': 'Personnes', + 'lumen.search.suggest.titles': 'Titres', + 'lumen.search.suggest.didYouMean': 'Vouliez-vous dire', + 'lumen.search.suggest.owned': 'Dans la bibliothèque', + 'lumen.search.suggest.label': 'Suggestions de recherche', + 'lumen.search.top.heading': 'Meilleur résultat', + 'lumen.search.top.person': 'Personne', + 'lumen.search.top.series': 'Série', + 'lumen.search.top.movie': 'Film', + 'lumen.search.top.openSeason': 'Ouvrir la saison {season}', + 'lumen.search.top.matches': 'Correspondances', + 'lumen.search.top.knownFor': 'Connu pour', + 'lumen.search.showingResultsFor': 'Résultats pour {term}', + 'lumen.search.didYouMean': 'Vouliez-vous dire', + 'lumen.search.source.video': 'Films et séries', + 'lumen.search.source.music': 'Musique', + 'lumen.search.source.authors': 'Auteurs', + 'lumen.search.source.magazines': 'Magazines', } as const; diff --git a/lumen/src/pages/Search.tsx b/lumen/src/pages/Search.tsx index c3963006de..a56df666be 100644 --- a/lumen/src/pages/Search.tsx +++ b/lumen/src/pages/Search.tsx @@ -1,4 +1,11 @@ -import { useEffect, useMemo, useRef, useState } from 'react'; +import { + Fragment, + useEffect, + useMemo, + useRef, + useState, + type ReactNode, +} from 'react'; import { Link, Navigate, @@ -28,6 +35,8 @@ import { ServiceNote, } from '../components/extra'; import { usePhone } from '../components/PhoneFilters'; +import { useSuggestionCombobox } from '../components/SearchSuggestions'; +import { TopResultCard } from '../components/TopResultCard'; import { friendlyError } from '../errors'; import { artistOf, @@ -53,8 +62,10 @@ import { searchResultPage, videoFilterKeys, } from '../searchParams'; +import type { SearchIntentInfo, TopResult } from '../searchStream'; import { sessionGeneration } from '../sessionState'; import { usePrefs } from '../settings'; +import { isAbort, runStreamedSearch } from '../streamedSearch'; import { BookSeriesResults } from './BookSeriesSearch'; import { AlbumCard } from './Music'; import { PersonCard } from './People'; @@ -278,6 +289,13 @@ function SearchResults({ const [searching, setSearching] = useState(false); const [searchError, setSearchError] = useState(null); const [failedSources, setFailedSources] = useState([]); + // what the streamed "All" search understood: the top result card, section order, spelling + const [topResult, setTopResult] = useState | null>( + null + ); + const [intentInfo, setIntentInfo] = useState(null); + const [correctedQuery, setCorrectedQuery] = useState(null); + const [didYouMean, setDidYouMean] = useState(null); const lastReply = useRef(null); const retryReply = useRef(null); const [attempt, setAttempt] = useState(0); @@ -422,9 +440,15 @@ function SearchResults({ setComics(null); setSearching(false); setSearchError(null); + setTopResult(null); + setIntentInfo(null); + setCorrectedQuery(null); + setDidYouMean(null); return; } let live = true; + // typing on cancels the search for the older words + const controller = new AbortController(); const session = sessionGeneration(); const generation = cacheGeneration(); const reusable = retryReply.current; @@ -455,12 +479,73 @@ function SearchResults({ : [format]; let error: string | null = null; let catalogueUnavailable = false; - // which kinds of results a provider failed to give (for the quiet note under the results) - const failed = new Set<'titles' | 'books' | 'comics'>(); + // which kinds of results a provider failed to give (for the quiet note under the results): + // 'titles' | 'books' | 'comics', or a source the streamed search named ("Music") + const failed = new Set(); const failure = (e: unknown) => { error = friendlyError(e, t('lumen.search.failed', 'Search failed')); return null; }; + const keepTitle = ({ mediaType }: SearchResult) => { + if (mediaType === 'movie' && !movieEnabled) return false; + if (mediaType === 'tv' && !tvEnabled) return false; + if (mediaType === 'collection' && !movieEnabled) return false; + if (mediaType === 'person' && !movieEnabled && !tvEnabled) return false; + if (mediaType === 'author' && !bookEnabled) return false; + if (f === 'music') + return mediaType === 'album' || mediaType === 'artist'; + if (f === 'author' || f === 'tv' || f === 'magazine' || f === 'sports') + return mediaType === f; + if (f === 'movie') return mediaType === 'movie'; + return ( + mediaType === 'movie' || + mediaType === 'tv' || + mediaType === 'person' || + mediaType === 'collection' || + (prefs.showBooks && mediaType === 'author') || + (musicOn && (mediaType === 'album' || mediaType === 'artist')) || + (magazinesOn && mediaType === 'magazine') + ); + }; + // "All" streams: movies and series show while music, authors and magazines still load. + // Books and comics come from their own endpoints below, so the stream skips them. + const streamable = f === 'all' && titlePath.startsWith('/search?'); + const groups = [ + ...(movieEnabled || tvEnabled ? ['video'] : []), + ...(musicOn ? ['music'] : []), + ...(prefs.showBooks && bookEnabled ? ['authors'] : []), + ...(magazinesOn ? ['magazines'] : []), + ]; + const stream: { + snapshot: Awaited< + ReturnType> + > | null; + } = { snapshot: null }; + const streamTitles = () => + runStreamedSearch(titlePath, { + groups: groups.length ? groups : undefined, + signal: controller.signal, + onUpdate: (snapshot) => { + if (!live) return; + setIntentInfo(snapshot.intent ?? null); + setDidYouMean(snapshot.didYouMean ?? null); + setCorrectedQuery(snapshot.correctedQuery ?? null); + if (snapshot.results.length || snapshot.done) { + setTopResult(snapshot.topResult ?? null); + setTitles(snapshot.results.filter(keepTitle)); + // the first answer is on screen: slower groups fill in without a spinner + setSearching(false); + } + }, + }).then((snapshot): SearchPage => { + stream.snapshot = snapshot; + return { + page: resultPage, + totalPages: snapshot.totalPages, + results: snapshot.results, + partial: snapshot.partial, + }; + }); const comicsAsk = wantComics ? cachedApi>( `/discover/comics?query=${encodeURIComponent(term)}&group=works&page=${resultPage}` @@ -475,7 +560,11 @@ function SearchResults({ reusable.session === session && reusable.generation === generation ? reusable.page - : api(titlePath).catch((e: unknown) => { + : (streamable + ? streamTitles() + : api(titlePath, { signal: controller.signal }) + ).catch((e: unknown) => { + if (!live || isAbort(e)) return null; failed.add('titles'); return failure(e); }) @@ -503,27 +592,7 @@ function SearchResults({ const resultsOnPage = (response: Paged | null) => response && resultPage <= response.totalPages ? response.results : []; const foundComics = resultsOnPage(cr); - const foundTitles = resultsOnPage(tr).filter(({ mediaType }) => { - if (mediaType === 'movie' && !movieEnabled) return false; - if (mediaType === 'tv' && !tvEnabled) return false; - if (mediaType === 'collection' && !movieEnabled) return false; - if (mediaType === 'person' && !movieEnabled && !tvEnabled) return false; - if (mediaType === 'author' && !bookEnabled) return false; - if (f === 'music') - return mediaType === 'album' || mediaType === 'artist'; - if (f === 'author' || f === 'tv' || f === 'magazine' || f === 'sports') - return mediaType === f; - if (f === 'movie') return mediaType === 'movie'; - return ( - mediaType === 'movie' || - mediaType === 'tv' || - mediaType === 'person' || - mediaType === 'collection' || - (prefs.showBooks && mediaType === 'author') || - (musicOn && (mediaType === 'album' || mediaType === 'artist')) || - (magazinesOn && mediaType === 'magazine') - ); - }); + const foundTitles = resultsOnPage(tr).filter(keepTitle); let foundBooks = brs.flatMap((r, i) => resultsOnPage(r) .filter((b) => b.mediaType === 'book') @@ -562,7 +631,17 @@ function SearchResults({ setTitles(foundTitles); setBooks(foundBooks); setComics(foundComics); - if (tr?.partial) failed.add('titles'); + const snapshot = stream.snapshot; + if (snapshot?.partial && snapshot.failedSources.length) + for (const source of snapshot.failedSources) failed.add(source); + else if (tr?.partial) failed.add('titles'); + if (!snapshot && !(streamable && reusable?.path === titlePath)) { + // a scoped search has no top result or intent of its own + setTopResult(null); + setIntentInfo(null); + setCorrectedQuery(null); + setDidYouMean(null); + } setFailedSources([...failed]); setSearchError( error ?? @@ -578,6 +657,7 @@ function SearchResults({ return () => { live = false; clearTimeout(timer); + controller.abort(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ @@ -659,7 +739,22 @@ function SearchResults({ requestedOrder === 'asc' || requestedOrder === 'desc' ? requestedOrder : (activeSort?.defaultOrder ?? 'desc'); - const orderedTitles = sortSearchResults(titles, sortField, sortOrder); + // the top result card (All, first page, best-match order); what it shows is not repeated below + const topShown = + f === 'all' && resultPage === 1 && !sortField && topResult + ? topResult + : null; + const inTop = new Set( + topShown + ? [ + ...topShown.works, + ...(topShown.kind === 'person' ? [topShown.item] : []), + ].map((item) => `${item.mediaType}:${item.id}`) + : [] + ); + const orderedTitles = sortSearchResults(titles, sortField, sortOrder).filter( + (item) => !inTop.has(`${item.mediaType}:${item.id}`) + ); const people = f === 'all' ? orderedTitles.filter((t): t is TitleResult => t.mediaType === 'person') @@ -702,7 +797,44 @@ function SearchResults({ !magazines.length && !leagues.length && !bookCards.length && - !comicCards.length; + !comicCards.length && + !topShown; + // sections in the order the query asked for ("metallica live": albums first), else the usual + const defaultSectionOrder = [ + 'movie', + 'collection', + 'tv', + 'person', + 'album', + 'artist', + 'author', + 'book', + 'sports', + 'magazine', + 'comic', + ]; + const sectionRank = (type: string) => { + const asked = intentInfo?.sections?.indexOf(type) ?? -1; + return asked >= 0 && f === 'all' + ? asked + : 100 + defaultSectionOrder.indexOf(type); + }; + // suggestions under the phone search box (desktop uses the one in the top bar) + const phoneSuggestions = useSuggestionCombobox({ + term: q, + enabled: f !== 'music' && f !== 'sports' && f !== 'magazine', + // the page already lists recent searches while the box is empty + recent: q.trim() ? recent : [], + // the phone box is focused when the page opens: stay closed until something is typed + openOnFocus: false, + onSearch: (value) => { + setQ(value); + const next = new URLSearchParams(p); + next.delete('page'); + next.set('q', value); + setP(next); + }, + }); return ( <> @@ -721,34 +853,39 @@ function SearchResults({ {/* phones only: on desktop the top search bar is the search box (the mockup hides this one) */} - +
+ + {phoneSuggestions.list} +
)} + {f === 'all' && hasSearch && correctedQuery && ( +

+ {t('lumen.search.showingResultsFor', 'Showing results for {term}', { + term: correctedQuery, + })} +

+ )} + {f === 'all' && + hasSearch && + !correctedQuery && + didYouMean && + didYouMean !== term0.toLocaleLowerCase() && ( +

+ {t('lumen.search.didYouMean', 'Did you mean')}{' '} + + ? +

+ )}
{ if ((e.target as HTMLElement).closest('a,button')) remember(term0); }} > - {!!movies.length && ( -
-
- {movies.map((m) => ( - - ))} -
-
- )} - {!!collections.length && ( -
-
- {collections.map((collection) => ( - - ))} -
-
- )} - {!!shows.length && ( -
-
- {shows.map((m) => ( - - ))} -
-
- )} - {!!people.length && ( -
-
- {people.map((person) => ( - - ))} -
-
- )} - {!!albums.length && ( -
-
- {albums.map((album) => ( - - ))} -
-
- )} - {!!artists.length && ( -
-
- {artists.map(({ id, name }) => ( - } + {( + [ + [ + 'movie', + !!movies.length && ( +
+
+ {movies.map((m) => ( + + ))} +
+
+ ), + ], + [ + 'collection', + !!collections.length && ( +
- {name} - - ))} -
-
- )} - {!!authors.length && ( -
-
- {authors.map(({ id, name }) => ( - + {collections.map((collection) => ( + + ))} +
+
+ ), + ], + [ + 'tv', + !!shows.length && ( +
+
+ {shows.map((m) => ( + + ))} +
+
+ ), + ], + [ + 'person', + !!people.length && ( +
+
+ {people.map((person) => ( + + ))} +
+
+ ), + ], + [ + 'album', + !!albums.length && ( +
+
+ {albums.map((album) => ( + + ))} +
+
+ ), + ], + [ + 'artist', + !!artists.length && ( +
+
+ {artists.map(({ id, name }) => ( + + {name} + + ))} +
+
+ ), + ], + [ + 'author', + !!authors.length && ( +
+
+ {authors.map(({ id, name }) => ( + + {name} + + ))} +
+
+ ), + ], + [ + 'book', + !!bookCards.length && ( +
- {name} - - ))} -
- - )} - {!!bookCards.length && ( -
-
- {bookCards.map((b) => ( - - ))} -
-
- )} - {!!leagues.length && ( -
-
- {leagues.map((league) => ( - - ))} -
-
- )} - {!!magazines.length && ( -
-
- {magazines.map((magazine) => ( - - ))} -
-
- )} - {!!comicCards.length && ( -
-
- {comicCards.map((w) => ( - - ))} -
-
- )} +
+ {bookCards.map((b) => ( + + ))} +
+ + ), + ], + [ + 'sports', + !!leagues.length && ( +
+
+ {leagues.map((league) => ( + + ))} +
+
+ ), + ], + [ + 'magazine', + !!magazines.length && ( +
+
+ {magazines.map((magazine) => ( + + ))} +
+
+ ), + ], + [ + 'comic', + !!comicCards.length && ( +
+
+ {comicCards.map((w) => ( + + ))} +
+
+ ), + ], + ] as [string, ReactNode][] + ) + .sort(([left], [right]) => sectionRank(left) - sectionRank(right)) + .map(([type, node]) => ( + {node} + ))}
{/* some providers failed but others answered: one quiet line, not an error card */} {!searching && !nothing && searchError && ( @@ -1127,14 +1343,25 @@ function SearchResults({ sources: failedSources .map((source) => - source === 'books' + source === 'books' || source === 'Books' ? t('lumen.search.source.books', 'Books') - : source === 'comics' + : source === 'comics' || source === 'Comics' ? t('lumen.search.source.comics', 'Comics') - : t( - 'lumen.search.source.titles', - 'Movies, series and music' - ) + : source === 'Movies & TV' + ? t('lumen.search.source.video', 'Movies & TV') + : source === 'Music' + ? t('lumen.search.source.music', 'Music') + : source === 'Authors' + ? t('lumen.search.source.authors', 'Authors') + : source === 'Magazines' + ? t( + 'lumen.search.source.magazines', + 'Magazines' + ) + : t( + 'lumen.search.source.titles', + 'Movies, series and music' + ) ) .join(', ') || t('lumen.search.source.some', 'some providers'), diff --git a/lumen/src/searchStream.ts b/lumen/src/searchStream.ts new file mode 100644 index 0000000000..c449de9eec --- /dev/null +++ b/lumen/src/searchStream.ts @@ -0,0 +1,134 @@ +// The streamed global search (GET /search/stream): one JSON object per line, each provider +// group as soon as it answers, so movies and series show while books or music still load. +import { csrfHeaders, strictQuery } from './api'; + +export type SearchIntentInfo = { + kind: 'title' | 'person-works' | 'discover' | 'show-season'; + entity: string; + format?: string; + mediaType?: string; + genre?: string; + year?: number; + season?: number; + episode?: number; + label?: string; + sections: string[]; +}; + +export type TopResult> = { + kind: 'person' | 'title'; + reason: 'intent' | 'match'; + label?: string; + item: T; + works: T[]; + season?: number; + episode?: number; +}; + +export type SearchStreamEvent> = + | { + type: 'intent'; + query: string; + intent: SearchIntentInfo; + didYouMean?: string; + } + | { + type: 'results'; + group: string; + page: number; + totalPages: number; + totalResults: number; + results: T[]; + topResult?: TopResult; + correctedQuery?: string; + partial?: boolean; + failedSources?: string[]; + } + | { type: 'error'; group: string; status: number; message: string } + | { + type: 'done'; + totalPages: number; + partial: boolean; + failedSources: string[]; + elapsedMs: number; + }; + +/** Splits streamed text into complete JSON lines; returns the unfinished rest. */ +export function takeNdjsonLines(buffer: string): { + events: unknown[]; + rest: string; +} { + const events: unknown[] = []; + let rest = buffer; + let newline = rest.indexOf('\n'); + while (newline >= 0) { + const line = rest.slice(0, newline).trim(); + rest = rest.slice(newline + 1); + newline = rest.indexOf('\n'); + if (!line) continue; + try { + events.push(JSON.parse(line)); + } catch { + // a damaged line is skipped; the rest of the stream still counts + } + } + return { events, rest }; +} + +/** + * Reads the streamed search at `path` (an /api/v1-relative /search/stream URL), calling + * `onEvent` for each line. Resolves when the stream ends; rejects on HTTP or network + * failure (callers fall back to the classic /search). Aborting `signal` stops reading. + */ +export async function streamSearch>( + path: string, + onEvent: (event: SearchStreamEvent) => void, + signal?: AbortSignal +): Promise { + const response = await fetch('/api/v1' + strictQuery(path), { + credentials: 'same-origin', + cache: 'no-store', + headers: { Accept: 'application/x-ndjson', ...csrfHeaders() }, + signal, + }); + if (!response.ok || !response.body) { + throw new Error(`Search stream failed (${response.status})`); + } + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + let sawDone = false; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + buffer += decoder.decode(value, { stream: true }); + const { events, rest } = takeNdjsonLines(buffer); + buffer = rest; + for (const event of events) { + const typed = event as SearchStreamEvent; + if (typed.type === 'done') sawDone = true; + onEvent(typed); + } + } + const { events } = takeNdjsonLines(buffer + '\n'); + for (const event of events) { + const typed = event as SearchStreamEvent; + if (typed.type === 'done') sawDone = true; + onEvent(typed); + } + } finally { + reader.releaseLock(); + } + if (!sawDone && !signal?.aborted) { + throw new Error('Search stream ended early'); + } +} + +/** The /search/stream URL for a classic /search URL built by scopedSearchPath. */ +export function streamPathFor(searchPath: string, groups?: string[]) { + if (!searchPath.startsWith('/search?')) return null; + const params = new URLSearchParams(searchPath.slice('/search?'.length)); + if (groups?.length) params.set('groups', groups.join(',')); + return `/search/stream?${params}`; +} diff --git a/lumen/src/searchSuggest.ts b/lumen/src/searchSuggest.ts new file mode 100644 index 0000000000..c4f73c15a1 --- /dev/null +++ b/lumen/src/searchSuggest.ts @@ -0,0 +1,96 @@ +// Search suggestions while typing: GET /search/suggest answers from the server's in-memory +// index (library, recent answers, trending, popular people) in about 100 ms. +import { useEffect, useState } from 'react'; +import { api } from './api'; + +export type SuggestionItem = { + mediaType: + | 'movie' + | 'tv' + | 'person' + | 'collection' + | 'album' + | 'artist' + | 'book' + | 'author' + | 'comic'; + id: number | string; + title: string; + year?: string; + posterPath?: string; + subtitle?: string; + owned?: boolean; +}; +export type SuggestionQuery = { text: string; kind: 'intent' | 'correction' }; +export type SuggestionReply = { + query: string; + queries: SuggestionQuery[]; + titles: SuggestionItem[]; + people: SuggestionItem[]; + didYouMean?: string; +}; + +// wait this long after the last key before asking; each new key cancels the last ask +export const SUGGEST_DEBOUNCE_MS = 120; + +/** Where a suggestion opens, or null when it has no page of its own. */ +export function suggestionHref(item: SuggestionItem): string | null { + const id = encodeURIComponent(String(item.id)); + switch (item.mediaType) { + case 'movie': + return `/movie/${id}`; + case 'tv': + return `/tv/${id}`; + case 'person': + return `/person/${id}`; + case 'collection': + return `/collection/${id}`; + case 'album': + return `/music/${id}`; + case 'artist': + return `/artist/${id}`; + case 'book': + return `/book/${id}`; + case 'author': + return `/author/${id}`; + case 'comic': + return `/comic/${id}`; + default: + return null; + } +} + +/** + * Suggestions for what is being typed. Debounced, and a newer term aborts the + * request for an older one, so a slow answer never replaces a newer list. + */ +export function useSearchSuggestions(term: string, enabled: boolean) { + const [reply, setReply] = useState(null); + const trimmed = term.trim(); + useEffect(() => { + if (!enabled || trimmed.length < 2) { + setReply(null); + return; + } + const controller = new AbortController(); + const timer = window.setTimeout(() => { + api( + `/search/suggest?q=${encodeURIComponent(trimmed.slice(0, 100))}`, + { signal: controller.signal, invalidateCache: false } + ) + .then((next) => { + if (!controller.signal.aborted) setReply(next); + }) + .catch(() => { + // suggestions are optional: a failed ask just shows none + if (!controller.signal.aborted) setReply(null); + }); + }, SUGGEST_DEBOUNCE_MS); + return () => { + window.clearTimeout(timer); + controller.abort(); + }; + }, [trimmed, enabled]); + // an answer for an older term is not shown under a newer one + return reply && reply.query === trimmed ? reply : null; +} diff --git a/lumen/src/streamedSearch.ts b/lumen/src/streamedSearch.ts new file mode 100644 index 0000000000..b204d3f2ef --- /dev/null +++ b/lumen/src/streamedSearch.ts @@ -0,0 +1,151 @@ +// Gathers the streamed global search into page-shaped snapshots for the Search page: every +// group's results as they arrive, the top result, how the query was understood, and which +// sources did not answer. Falls back to the classic /search when the stream is unavailable. +import { api, ApiError } from './api'; +import { + streamPathFor, + streamSearch, + type SearchIntentInfo, + type TopResult, +} from './searchStream'; + +export type StreamedSearchSnapshot = { + results: T[]; + totalPages: number; + intent?: SearchIntentInfo; + topResult?: TopResult; + correctedQuery?: string; + didYouMean?: string; + /** Plain names of sources that did not answer ("Music", "Books"). */ + failedSources: string[]; + /** Every group has answered (or given up). */ + done: boolean; + /** A group answered with an error the page should mention. */ + partial: boolean; +}; + +type ClassicPage = { + results: T[]; + totalPages: number; + partial?: boolean; + failedSources?: string[]; + intent?: SearchIntentInfo; + topResult?: TopResult; + correctedQuery?: string; +}; + +/** + * Runs the search behind `searchPath` (a classic `/search?...` path) as a stream when it + * can, calling `onUpdate` after each answer, and resolves with the final snapshot. + * `groups` limits the provider groups (Lumen reads books and comics elsewhere). + */ +export async function runStreamedSearch( + searchPath: string, + { + groups, + signal, + onUpdate, + }: { + groups?: string[]; + signal?: AbortSignal; + onUpdate?: (snapshot: StreamedSearchSnapshot) => void; + } = {} +): Promise> { + const streamPath = streamPathFor(searchPath, groups); + const byGroup = new Map(); + const order = groups ?? [ + 'video', + 'music', + 'books', + 'authors', + 'comics', + 'magazines', + ]; + const snapshot: StreamedSearchSnapshot = { + results: [], + totalPages: 1, + failedSources: [], + done: false, + partial: false, + }; + const emit = () => { + snapshot.results = order.flatMap((group) => byGroup.get(group) ?? []); + onUpdate?.({ ...snapshot, failedSources: [...snapshot.failedSources] }); + }; + const fail = (source: string) => { + if (!snapshot.failedSources.includes(source)) + snapshot.failedSources.push(source); + snapshot.partial = true; + }; + + if (streamPath) { + try { + await streamSearch( + streamPath, + (event) => { + if (event.type === 'intent') { + snapshot.intent = event.intent; + snapshot.didYouMean = event.didYouMean; + emit(); + } else if (event.type === 'results') { + byGroup.set(event.group, event.results ?? []); + snapshot.totalPages = Math.max( + snapshot.totalPages, + event.totalPages || 1 + ); + // the first top result stays put (no jumping card), unless a later one comes + // from the query's intent and the first was only a strong title match + if ( + event.topResult && + (!snapshot.topResult || + (snapshot.topResult.reason === 'match' && + event.topResult.reason === 'intent')) + ) { + snapshot.topResult = event.topResult; + } + if (event.correctedQuery) + snapshot.correctedQuery = event.correctedQuery; + for (const source of event.failedSources ?? []) fail(source); + emit(); + } else if (event.type === 'error') { + fail(event.message.replace(/ did not answer in time\.$/, '')); + emit(); + } else if (event.type === 'done') { + for (const source of event.failedSources ?? []) fail(source); + snapshot.totalPages = Math.max( + snapshot.totalPages, + event.totalPages || 1 + ); + snapshot.done = true; + emit(); + } + }, + signal + ); + snapshot.done = true; + return snapshot; + } catch (error) { + if (signal?.aborted) throw error; + // groups already shown stay; the classic search fills in the rest below + if (byGroup.size > 0 && snapshot.done) return snapshot; + } + } + + const page = await api>(searchPath, { signal }); + snapshot.results = page.results; + snapshot.totalPages = page.totalPages || 1; + snapshot.intent = page.intent ?? snapshot.intent; + snapshot.topResult = page.topResult ?? snapshot.topResult; + snapshot.correctedQuery = page.correctedQuery; + if (page.partial) { + for (const source of page.failedSources ?? []) fail(source); + snapshot.partial = true; + } + snapshot.done = true; + onUpdate?.({ ...snapshot }); + return snapshot; +} + +export const isAbort = (error: unknown) => + (error instanceof DOMException && error.name === 'AbortError') || + (error instanceof ApiError && error.status === 0); diff --git a/lumen/src/styles/search-suggest.css b/lumen/src/styles/search-suggest.css new file mode 100644 index 0000000000..a328a146d5 --- /dev/null +++ b/lumen/src/styles/search-suggest.css @@ -0,0 +1,189 @@ +/* Search suggestions dropdown and the Top result card. */ +.qwrap, +.search-suggest-anchor { + position: relative; +} +.suggest { + position: absolute; + z-index: 60; + top: calc(100% + 6px); + left: 0; + right: 0; + max-height: min(70vh, 520px); + overflow-y: auto; + overscroll-behavior: contain; + padding: 6px; + border-radius: 16px; + background: var(--surface); + border: 1px solid var(--line); + box-shadow: var(--shadow-float); +} +.suggest-group + .suggest-group { + margin-top: 4px; + padding-top: 4px; + border-top: 1px solid var(--line); +} +.suggest-heading { + padding: 6px 10px 2px; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--ink-3); +} +.suggest-option { + display: flex; + align-items: center; + gap: 12px; + /* thumb-sized rows on phones */ + min-height: 44px; + padding: 6px 10px; + border-radius: 10px; + cursor: pointer; + color: var(--ink); + -webkit-tap-highlight-color: transparent; +} +.suggest-option[aria-selected='true'], +.suggest-option:hover { + background: var(--surface-2); +} +.suggest-icon { + display: grid; + place-items: center; + width: 32px; + height: 32px; + color: var(--ink-3); + flex: none; +} +.suggest-thumb { + width: 32px; + height: 46px; + border-radius: 6px; + object-fit: cover; + background: var(--surface-3); + flex: none; +} +.suggest-thumb.round { + width: 36px; + height: 36px; + border-radius: 50%; +} +.suggest-text { + display: grid; + min-width: 0; + flex: 1; +} +.suggest-label, +.suggest-detail { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.suggest-label { + font-size: 15px; +} +.suggest-hint { + color: var(--ink-3); +} +.suggest-detail { + font-size: 12px; + color: var(--ink-3); +} +.suggest-owned { + flex: none; + font-size: 11px; + font-weight: 700; + padding: 3px 8px; + border-radius: 999px; + background: var(--ok-soft, var(--surface-2)); + color: var(--ok, var(--ink-2)); +} + +/* ---------- Top result ---------- */ +.top-result { + display: grid; + /* the works row scrolls inside the card; it never widens the page */ + grid-template-columns: minmax(0, 1fr); + min-width: 0; + max-width: 100%; + gap: 14px; + padding: 16px; + border-radius: 20px; + background: var(--surface-2); +} +.top-result-head { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} +.top-result-main { + display: flex; + align-items: center; + gap: 14px; + min-width: 0; + flex: 1; + color: inherit; + text-decoration: none; +} +.top-result-img { + width: 72px; + height: 108px; + border-radius: 10px; + object-fit: cover; + background: var(--surface-3); + flex: none; +} +.top-result-img.round { + width: 84px; + height: 84px; + border-radius: 50%; +} +.top-result-text { + display: grid; + gap: 2px; + min-width: 0; +} +.top-result-name { + font-size: 22px; + line-height: 1.2; + overflow-wrap: anywhere; +} +.top-result-meta { + color: var(--ink-3); + font-size: 13px; +} +.top-result-label { + margin: 0 0 8px; + font-size: 14px; + font-weight: 700; + color: var(--ink-2); +} +.top-result-works { + min-width: 0; +} +.top-result-row { + min-width: 0; + display: grid; + grid-auto-flow: column; + grid-auto-columns: var(--pw, 128px); + gap: 12px; + overflow-x: auto; + scroll-snap-type: x proximity; + padding-bottom: 4px; +} +.top-result-row > * { + scroll-snap-align: start; +} +@media (max-width: 600px) { + .top-result { + padding: 12px; + } + .top-result-name { + font-size: 19px; + } + .top-result-img.round { + width: 64px; + height: 64px; + } +} diff --git a/lumen/tests/browser/search-stream.spec.ts b/lumen/tests/browser/search-stream.spec.ts new file mode 100644 index 0000000000..133df47910 --- /dev/null +++ b/lumen/tests/browser/search-stream.spec.ts @@ -0,0 +1,213 @@ +import { expect, test, type Page } from '@playwright/test'; +import { suggestFixtures } from './searchFixtures'; +import { testAppPath } from './testAppPath'; + +const special = (id: number, title: string, date: string) => ({ + id, + mediaType: 'movie', + title, + releaseDate: date, + posterPath: null, + genreIds: [35], + matchScore: 80, +}); +const SPECIALS = [ + special(2000001, 'Nate Bargatze: Hello World', '2023-01-31'), + special( + 2000002, + 'Nate Bargatze: The Greatest Average American', + '2021-04-27' + ), + special(2000003, 'Nate Bargatze: The Tennessee Kid', '2019-01-29'), +]; +const NATE = { + id: 1000001, + mediaType: 'person', + name: 'Nate Bargatze', + knownFor: [], + matchScore: 70, +}; +const NATE_FILM = { + id: 4000001, + mediaType: 'movie', + title: 'Nate', + releaseDate: '2017-05-05', + matchScore: 50, +}; + +const ndjson = (events: unknown[]) => + events.map((event) => JSON.stringify(event)).join('\n') + '\n'; + +async function streamFixtures( + page: Page, + options: { musicFails?: boolean; streamCalls?: string[] } = {} +) { + await suggestFixtures(page); + await page.route('**/api/v1/search/stream**', (route) => { + const url = new URL(route.request().url()); + options.streamCalls?.push(url.search); + const query = url.searchParams.get('query') ?? ''; + const standup = query.toLowerCase() === 'nate standup'; + return route.fulfill({ + status: 200, + contentType: 'application/x-ndjson', + body: ndjson([ + { + type: 'intent', + query, + intent: standup + ? { + kind: 'person-works', + entity: 'nate', + format: 'standup', + label: 'Stand-up specials', + sections: [ + 'movie', + 'tv', + 'person', + 'collection', + 'album', + 'artist', + 'author', + ], + matched: ['standup'], + } + : { + kind: 'title', + entity: query, + sections: ['movie', 'tv', 'person'], + matched: [], + }, + }, + { + type: 'results', + group: 'video', + page: 1, + totalPages: 1, + totalResults: 5, + results: [...SPECIALS, NATE_FILM, NATE], + ...(standup && { + topResult: { + kind: 'person', + reason: 'intent', + label: 'Stand-up specials', + item: NATE, + works: SPECIALS, + }, + }), + }, + options.musicFails + ? { + type: 'error', + group: 'music', + status: 504, + message: 'Music did not answer in time.', + } + : { + type: 'results', + group: 'music', + page: 1, + totalPages: 1, + totalResults: 0, + results: [], + }, + { + type: 'done', + totalPages: 1, + partial: !!options.musicFails, + failedSources: options.musicFails ? ['Music'] : [], + elapsedMs: 420, + }, + ]), + }); + }); +} + +test('"nate standup" shows Nate Bargatze with his specials as the top result', async ({ + page, +}, info) => { + const streamCalls: string[] = []; + await streamFixtures(page, { streamCalls }); + await page.goto(testAppPath('/search?q=nate%20standup')); + const top = page.getByRole('region', { name: 'Top result' }); + await expect(top).toBeVisible(); + await expect(top.getByText('Nate Bargatze', { exact: true })).toBeVisible(); + await expect( + top.getByRole('heading', { name: 'Stand-up specials' }) + ).toBeVisible(); + await expect( + top.getByRole('link', { name: /Hello World/ }).first() + ).toBeVisible(); + // specials in the card are not repeated in the Movies section below + const movies = page.locator('section', { + has: page.getByRole('heading', { name: 'Movies', exact: true }), + }); + await expect( + movies.getByRole('link', { name: /^Nate/ }).first() + ).toBeVisible(); + await expect(movies.getByRole('link', { name: /Hello World/ })).toHaveCount( + 0 + ); + // the works row scrolls inside the card, never the page + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= window.innerWidth + 1 + ) + ).toBe(true); + expect(streamCalls[0]).toContain('groups='); + expect(streamCalls[0]).not.toContain('books'); + await page.screenshot({ + path: info.outputPath('search-top-result.png'), + fullPage: false, + }); + await top + .getByRole('link', { name: /Nate Bargatze/ }) + .first() + .click(); + await expect(page).toHaveURL(/\/person\/1000001$/); +}); + +test('a source that does not answer gets one quiet note with Retry', async ({ + page, +}, info) => { + const streamCalls: string[] = []; + await streamFixtures(page, { musicFails: true, streamCalls }); + await page.goto(testAppPath('/search?q=nate%20standup')); + await expect(page.getByRole('region', { name: 'Top result' })).toBeVisible(); + const note = page.getByText(/didn.t answer \(Music\)/); + await expect(note).toBeVisible(); + await expect(page.getByText(/Couldn.t load some search results/)).toHaveCount( + 0 + ); + await note.scrollIntoViewIfNeeded(); + await page.screenshot({ + path: info.outputPath('search-partial.png'), + fullPage: false, + }); + const before = streamCalls.length; + await page.getByRole('button', { name: 'Retry' }).click(); + await expect.poll(() => streamCalls.length).toBeGreaterThan(before); +}); + +test('the Search page box suggests while typing', async ({ page }, info) => { + await streamFixtures(page); + await page.goto(testAppPath('/search')); + const box = page.locator( + (page.viewportSize()?.width ?? 0) >= 1040 ? '#tq' : '#sq' + ); + await box.click(); + await box.pressSequentially('nate st', { delay: 20 }); + const list = page.getByRole('listbox', { name: 'Search suggestions' }); + await expect(list).toBeVisible(); + await expect( + list.getByRole('option', { name: /Nate Bargatze stand-up specials/ }) + ).toBeVisible(); + await page.screenshot({ + path: info.outputPath('search-suggest.png'), + fullPage: false, + }); + await list + .getByRole('option', { name: /Nate Bargatze stand-up specials/ }) + .click(); + await expect(page).toHaveURL(/q=Nate\+Bargatze\+stand-up\+specials/); +}); diff --git a/lumen/tests/browser/search-suggestions.spec.ts b/lumen/tests/browser/search-suggestions.spec.ts new file mode 100644 index 0000000000..8d80cf5843 --- /dev/null +++ b/lumen/tests/browser/search-suggestions.spec.ts @@ -0,0 +1,83 @@ +import { expect, test } from '@playwright/test'; +import { suggestFixtures } from './searchFixtures'; +import { testAppPath } from './testAppPath'; + +test.describe('search suggestions in the top search box', () => { + test.skip( + ({ viewport }) => (viewport?.width ?? 0) < 1040, + 'the top search box is the desktop search; phones use the Search page box' + ); + + test('suggests while typing, moves with the keyboard and searches the pick', async ({ + page, + }, info) => { + const asked: string[] = []; + await suggestFixtures(page, asked); + await page.goto(testAppPath('/discover')); + const box = page.locator('#tq'); + await box.click(); + await box.pressSequentially('nate st', { delay: 20 }); + const list = page.getByRole('listbox', { name: 'Search suggestions' }); + await expect(list).toBeVisible(); + await expect(box).toHaveAttribute( + 'aria-controls', + (await list.getAttribute('id')) as string + ); + const intent = list.getByRole('option', { + name: /Nate Bargatze stand-up specials/, + }); + await expect(intent).toBeVisible(); + await expect( + list.locator('[role="option"][data-group="people"]', { + hasText: 'Nate Bargatze', + }) + ).toBeVisible(); + await expect(list.getByText('In library')).toBeVisible(); + // typing quickly asks once for the finished word, not for every letter + expect(asked.length).toBeLessThan(4); + expect(asked.at(-1)).toBe('nate st'); + await page.screenshot({ path: info.outputPath('suggest-desktop.png') }); + + await box.press('ArrowDown'); + await expect(intent).toHaveAttribute('aria-selected', 'true'); + await expect(box).toHaveAttribute( + 'aria-activedescendant', + (await intent.getAttribute('id')) as string + ); + await box.press('Enter'); + await expect(page).toHaveURL( + /\/search\?q=Nate\+Bargatze\+stand-up\+specials/ + ); + await expect(list).toBeHidden(); + }); + + test('opens a person with a click and closes on Escape', async ({ page }) => { + await suggestFixtures(page); + await page.goto(testAppPath('/discover')); + const box = page.locator('#tq'); + await box.click(); + await box.fill('nate barg'); + const list = page.getByRole('listbox', { name: 'Search suggestions' }); + await expect(list).toBeVisible(); + await box.press('Escape'); + await expect(list).toBeHidden(); + await box.press('ArrowDown'); + await expect(list).toBeVisible(); + await list.locator('[role="option"][data-group="people"]').click(); + await expect(page).toHaveURL(/\/person\/1000001$/); + }); + + test('offers a spelling correction', async ({ page }) => { + await suggestFixtures(page); + await page.goto(testAppPath('/discover')); + const box = page.locator('#tq'); + await box.click(); + await box.fill('bergatze'); + const correction = page.getByRole('option', { + name: /Did you mean bargatze/, + }); + await expect(correction).toBeVisible(); + await correction.click(); + await expect(page).toHaveURL(/\/search\?q=bargatze/); + }); +}); diff --git a/lumen/tests/browser/searchFixtures.ts b/lumen/tests/browser/searchFixtures.ts new file mode 100644 index 0000000000..e9dafecad9 --- /dev/null +++ b/lumen/tests/browser/searchFixtures.ts @@ -0,0 +1,68 @@ +import type { Page } from '@playwright/test'; + +const paged = (results: unknown[]) => ({ + page: 1, + totalPages: 1, + totalResults: results.length, + results, +}); + +const NATE = { + mediaType: 'person', + id: 1000001, + title: 'Nate Bargatze', + subtitle: 'Nate Bargatze: Hello World', + owned: false, +}; +const SPECIAL = { + mediaType: 'movie', + id: 2000001, + title: 'Nate Bargatze: Hello World', + year: '2023', + owned: true, +}; + +/** A signed-in viewer, the suggestion endpoint and empty answers for everything else. */ +export async function suggestFixtures(page: Page, asked: string[] = []) { + await page.route('**/lumen-config.json', (r) => r.fulfill({ json: {} })); + await page.route('**/api/v1/**', (route) => { + const url = new URL(route.request().url()); + const path = url.pathname.slice('/api/v1'.length); + if (path === '/auth/me') + return route.fulfill({ + json: { id: 1, displayName: 'Viewer', permissions: 2 }, + }); + if (path === '/settings/public') + return route.fulfill({ + json: { applicationTitle: 'SeerrNG', booksEnabled: false }, + }); + if (path === '/search/suggest') { + const q = url.searchParams.get('q') ?? ''; + asked.push(q); + const lower = q.toLowerCase(); + const known = lower.startsWith('nate') || lower === 'bergatze'; + return route.fulfill({ + json: { + query: q, + queries: [ + ...(lower === 'bergatze' + ? [{ text: 'bargatze', kind: 'correction' }] + : []), + ...(known + ? [{ text: 'Nate Bargatze stand-up specials', kind: 'intent' }] + : []), + ], + people: known ? [NATE] : [], + titles: known ? [SPECIAL] : [], + ...(lower === 'bergatze' && { didYouMean: 'bargatze' }), + elapsedMs: 3, + }, + }); + } + if (path === '/person/1000001') + return route.fulfill({ + json: { id: 1000001, name: 'Nate Bargatze', biography: 'Comedian.' }, + }); + return route.fulfill({ json: paged([]) }); + }); +} diff --git a/lumen/tests/searchStream.test.mjs b/lumen/tests/searchStream.test.mjs new file mode 100644 index 0000000000..a054ea7911 --- /dev/null +++ b/lumen/tests/searchStream.test.mjs @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; +import ts from 'typescript'; + +// searchStream.ts imports ./api for fetch helpers; the pure helpers tested here do not use it +const source = ( + await readFile(new URL('../src/searchStream.ts', import.meta.url), 'utf8') +).replace( + /^import .*$/m, + 'const csrfHeaders = () => ({}); const strictQuery = (p) => p;' +); +const compiled = ts.transpileModule(source, { + compilerOptions: { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + }, +}).outputText; +const { takeNdjsonLines, streamPathFor, streamSearch } = await import( + `data:text/javascript,${encodeURIComponent(compiled)}` +); + +test('splits streamed text into whole JSON lines and keeps the rest', () => { + const first = takeNdjsonLines('{"type":"intent"}\n{"type":"res'); + assert.deepEqual(first.events, [{ type: 'intent' }]); + assert.equal(first.rest, '{"type":"res'); + const second = takeNdjsonLines( + first.rest + 'ults"}\n\nnot json\n{"type":"done"}\n' + ); + assert.deepEqual(second.events, [{ type: 'results' }, { type: 'done' }]); + assert.equal(second.rest, ''); +}); + +test('builds the stream path from a classic search path', () => { + assert.equal( + streamPathFor('/search?query=nate%20standup&page=1', ['video', 'music']), + '/search/stream?query=nate+standup&page=1&groups=video%2Cmusic' + ); + assert.equal(streamPathFor('/discover/movies?page=1'), null); +}); + +test('reads events from a chunked response and rejects a cut-off stream', async () => { + const encoder = new TextEncoder(); + const respond = (chunks) => + new Response( + new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(encoder.encode(chunk)); + controller.close(); + }, + }), + { status: 200 } + ); + const originalFetch = globalThis.fetch; + try { + globalThis.fetch = async () => + respond([ + '{"type":"intent","query":"x"}\n{"type":"re', + 'sults","group":"video","results":[]}\n', + '{"type":"done","failedSources":[]}', + ]); + const seen = []; + await streamSearch('/search/stream?query=x', (event) => + seen.push(event.type) + ); + assert.deepEqual(seen, ['intent', 'results', 'done']); + + globalThis.fetch = async () => respond(['{"type":"intent","query":"x"}\n']); + await assert.rejects( + streamSearch('/search/stream?query=x', () => {}), + /ended early/ + ); + + globalThis.fetch = async () => new Response('nope', { status: 503 }); + await assert.rejects( + streamSearch('/search/stream?query=x', () => {}), + /503/ + ); + } finally { + globalThis.fetch = originalFetch; + } +}); From c6175bc780b935f24b7b02972409e79d65f7a38d Mon Sep 17 00:00:00 2001 From: snapetech Date: Sun, 29 Nov 2026 14:58:58 -0600 Subject: [PATCH 4/4] docs(release): add search change note --- release-notes/search-smarter-results.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 release-notes/search-smarter-results.md diff --git a/release-notes/search-smarter-results.md b/release-notes/search-smarter-results.md new file mode 100644 index 0000000000..14c381ccb1 --- /dev/null +++ b/release-notes/search-smarter-results.md @@ -0,0 +1,9 @@ +--- +category: added +audience: users, operators +area: search +action: none +breaking: false +--- + +Search now understands common intent, suggests titles as you type, and streams result groups as they arrive so useful matches appear sooner.