diff --git a/CHANGELOG.md b/CHANGELOG.md index 500a9b9..ea2e7d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.55.8 — 2026-10-27 + +- Show search matches as soon as the provider search completes, without waiting for every result's episode list, audio availability, or AniDB alternative titles. Load these details in the background with at most two checks at once across browser requests. +- Cache successful result details for five minutes and failed checks for one minute; reuse cached details directly in repeat search results and suppress duplicate concurrent lookups. Bound each provider episode check to 30 seconds. +- Update existing cards in place as details arrive. Keep unverified audio availability visible and selectable with a pending or unavailable label; language filters exclude a title only after its availability has been checked. Cancel further background requests when a new search starts and ignore stale responses. +- Preserve the existing fully populated search API by default; the browser opts into `fast=1` and loads details through the authenticated search detail endpoint. Watchlists, queue history, thumbnails, downloads, and configuration are preserved. +- All 436 tests passed. An isolated live Iceblade search returned two initial results in 0.206 seconds; the first detail lookup took 1.301 seconds afterward, with its repeat lookup served from memory. Provider and network response times still affect results. +- Checked providers against upstream revision `5a1de84ad651d088cf427655573a96500151d862`; no new active-provider updates were available. AniNeko remains retired upstream with its compatibility adapter retained. + ## 0.55.7 — 2026-10-27 - Wrap Provider updates messages and badges within the Config sidebar panel, including long provider paths and retirement notices. Keep the badge grid constrained to the panel width. diff --git a/README.md b/README.md index 7c0db6e..1607771 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ Floating dialogs stay open when you click outside them or press Escape. Use thei The Config sidebar's Provider updates panel wraps long messages and provider badges within its boundaries. +Search shows matches as soon as the provider responds. Episode counts, sub/dub availability, and alternative titles load afterward, two results at a time, without replacing cards or closing the selection dialog. Pending or failed audio checks remain visible and selectable; the Sub/Dub filter hides a title only once its availability is verified. Successful details are cached in memory for five minutes, while failed checks wait one minute before retrying on a later search. Starting a new search cancels further browser detail requests and ignores old responses. Provider response times still affect initial results. API clients retain the full search response by default; `GET /api/search?fast=1` opts into deferred details from `POST /api/search/details` with `id`, `title`, and `provider`. + Search posters use one shared metadata request from the browser for up to 100 result titles. Kaizoku matches them against the search query's AnimeSchedule results (up to three pages of 18 entries), caches that metadata for five minutes, and serves matched images through its own authenticated image cache. External provider image URLs are skipped because the page's image policy blocks them. Image files still load individually, with at most four downloads at once and no per-title metadata lookup. Concurrent requests share lookups and downloads; source failures back off for at least a minute. Existing cached images remain available, while unmatched or temporarily unavailable posters show title initials. Broad searches can leave posters unmatched beyond the metadata page limit; watchlist thumbnail lookup remains independent. Jellyfin handoff checks each downloaded TV season in **Finished** separately, verifies its season-specific completion metadata, and moves only that season and its sidecars once its expected video files are present. Other seasons remain in Downloads. Use **Config → Handoff → Run now** after updating to repair missing or incorrect season metadata and retry previously skipped seasons. If metadata cannot be verified, the queue reports the skip and retains the files for a later retry. diff --git a/VERSION b/VERSION index 42f7f41..3ac43b0 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.55.7 +0.55.8 diff --git a/app.py b/app.py index b274e83..a87a24f 100644 --- a/app.py +++ b/app.py @@ -109,6 +109,11 @@ SEARCH_POSTER_RETRY_AT = 0.0 SEARCH_POSTER_SOURCES = {} SEARCH_POSTER_DOWNLOAD_SLOTS = threading.BoundedSemaphore(4) SEARCH_POSTER_IMAGE_LOCKS = [threading.Lock() for _ in range(32)] +SEARCH_DETAILS_CACHE = {} +SEARCH_DETAILS_LOCK = threading.Lock() +SEARCH_DETAILS_SLOTS = threading.BoundedSemaphore(2) +SEARCH_DETAILS_ALIAS_LOCK = threading.Lock() +SEARCH_DETAILS_ITEM_LOCKS = [threading.Lock() for _ in range(32)] def cached_search_poster(key): @@ -1031,9 +1036,10 @@ def episode_language_summary(show_id, provider): "sub_count": 0, "dub_count": 0, "total": 0, + "ready": False, } try: - rows = provider_bridge.episodes(show_id, provider=provider) + rows = provider_bridge.episodes(show_id, provider=provider, timeout=30) except Exception as exc: debug_log("search.episode_language_summary_failed", show_id=show_id, provider=provider, error=exc) return summary @@ -1058,10 +1064,45 @@ def episode_language_summary(show_id, provider): summary["sub_count"] = len(sub_values) summary["dub_count"] = len(dub_values) summary["total"] = len(all_values) + summary["ready"] = True return summary -def search_anime(query, mode, provider=None): +def get_search_result_details(show_id, title, provider): + if not isinstance(show_id, str) or not show_id.strip() or len(show_id) > 500: + raise ValueError("Search result ID must contain 1–500 characters") + if not isinstance(title, str) or not title.strip() or len(title) > 500: + raise ValueError("Search result title must contain 1–500 characters") + if provider not in provider_bridge.PROVIDERS: + raise ValueError("Unknown search provider") + actual_provider, provider_id = provider_bridge.parse_provider_id(show_id, provider) + if actual_provider != provider or not provider_id or (":" in show_id and show_id.split(":", 1)[0] != provider): + raise ValueError("Search result ID must match its provider") + key = (provider, provider_id, title.strip()) + with SEARCH_DETAILS_ITEM_LOCKS[hash(key) % len(SEARCH_DETAILS_ITEM_LOCKS)]: + with SEARCH_DETAILS_LOCK: + cached = SEARCH_DETAILS_CACHE.get(key) + if cached and cached[0] > time.monotonic(): + return dict(cached[1]) + with SEARCH_DETAILS_SLOTS: + summary = episode_language_summary(show_id, provider) + with SEARCH_DETAILS_ALIAS_LOCK: + alternative_titles = extract_anidb_alternative_titles_for_title(title, primary_title=title) + ready = summary.get("ready", True) + details = { + "episodes": summary["total"], "has_sub": summary["sub"] if ready else None, + "has_dub": summary["dub"] if ready else None, "sub_episodes": summary["sub_count"], + "dub_episodes": summary["dub_count"], "alternative_titles": alternative_titles, + "details_ready": ready, "details_error": not ready, + } + with SEARCH_DETAILS_LOCK: + if len(SEARCH_DETAILS_CACHE) >= 512: + SEARCH_DETAILS_CACHE.pop(next(iter(SEARCH_DETAILS_CACHE))) + SEARCH_DETAILS_CACHE[key] = (time.monotonic() + (300 if ready else 60), details) + return dict(details) + + +def search_anime(query, mode, provider=None, include_details=True): runtime = ensure_runtime() tracked_by_id, tracked_by_title = {}, {} watchlist = runtime.get("watchlist") @@ -1084,27 +1125,31 @@ def search_anime(query, mode, provider=None): show_id = str(show.get("id") or "").strip() if not show_id or not title: continue - language_summary = episode_language_summary(show_id, show.get("provider") or provider) - alternative_titles = extract_anidb_alternative_titles_for_title(title, primary_title=title) + result_provider = show.get("provider") or provider + details = get_search_result_details(show_id, title, result_provider) if include_details else { + "episodes": None, "has_sub": None, "has_dub": None, "sub_episodes": None, + "dub_episodes": None, "alternative_titles": [], "details_ready": False, "details_error": False, + } + if not include_details: + _, provider_id = provider_bridge.parse_provider_id(show_id, result_provider) + with SEARCH_DETAILS_LOCK: + cached = SEARCH_DETAILS_CACHE.get((result_provider, provider_id, title)) + if cached and cached[0] > time.monotonic(): + details = dict(cached[1]) tracked_category = tracked_by_id.get(show_id) or tracked_by_title.get(normalize_identity_title_key(title), "") index = len(results) + 1 results.append( { "id": show_id, "title": title, - "episodes": language_summary["total"], - "has_sub": language_summary["sub"], - "has_dub": language_summary["dub"], - "sub_episodes": language_summary["sub_count"], - "dub_episodes": language_summary["dub_count"], + **details, "image": show.get("image") or "", "index": index, "query": query, "watchlist_category": tracked_category, "watchlist_category_label": WATCHLIST.category_labels.get(tracked_category, watchlist_category_label(tracked_category)) if tracked_category and WATCHLIST else "", "mode": mode, - "provider": show.get("provider") or provider, - "alternative_titles": alternative_titles, + "provider": result_provider, } ) return results @@ -3868,6 +3913,7 @@ Handler = build_handler_class( runtime_state=runtime_state, save_runtime_config=save_runtime_config, search_anime=search_anime, + get_search_result_details=get_search_result_details, resolve_search_thumbnail=resolve_search_thumbnail, resolve_search_thumbnails=resolve_search_thumbnails, resolve_search_poster=resolve_search_poster, diff --git a/http_handler.py b/http_handler.py index 7aaa863..1f96962 100644 --- a/http_handler.py +++ b/http_handler.py @@ -91,6 +91,7 @@ class HandlerContext: runtime_state: object save_runtime_config: object search_anime: object + get_search_result_details: object resolve_search_thumbnail: object resolve_search_thumbnails: object resolve_search_poster: object @@ -820,7 +821,10 @@ class Handler(BaseHTTPRequestHandler): if mode not in MODE_CHOICES: raise ValueError("Mode must be sub or dub") try: - results = Handler._context(self).search_anime(query, mode, provider=provider) + search_options = {"provider": provider} + if (params.get("fast") or [""])[0] == "1": + search_options["include_details"] = False + results = Handler._context(self).search_anime(query, mode, **search_options) except provider_bridge.ProviderError: self.error(HTTPStatus.SERVICE_UNAVAILABLE, "Anime provider search is temporarily unavailable. Try another provider or query.") else: @@ -1000,6 +1004,9 @@ class Handler(BaseHTTPRequestHandler): payload["expected"], payload.get("output_fingerprint", ""))) else: self.error(HTTPStatus.NOT_FOUND, "Not found") + elif parsed.path == "/api/search/details": + payload = Handler.require_fields(self, self.body_json(), "id", "title", "provider") + self.json(Handler._context(self).get_search_result_details(payload["id"], payload["title"], payload["provider"])) elif parsed.path == "/api/search/thumbnails": payload = Handler.require_json_object(self, self.body_json()) posters = Handler._context(self).resolve_search_thumbnails(payload.get("query"), payload.get("titles")) diff --git a/search_page.py b/search_page.py index 89ac4a1..c3cc036 100644 --- a/search_page.py +++ b/search_page.py @@ -584,6 +584,8 @@ INDEX_HTML = r""" searchRequestId: 0, searchQuery: "", thumbnailBatch: null, + detailsPending: 0, + detailsController: null, episodeRequestId: 0 }; @@ -648,6 +650,29 @@ INDEX_HTML = r""" selectionModal.hidden = true; } + function updateResultDetails(btn, item) { + const subtitle = btn.querySelector(".result-subtitle"); + const alternativeTitle = Array.isArray(item.alternative_titles) && item.alternative_titles.length + ? String(item.alternative_titles[0].value || "").trim() + : ""; + subtitle.textContent = alternativeTitle ? `Also known as: ${alternativeTitle}` : ""; + subtitle.hidden = !alternativeTitle; + btn.querySelector(".cover-fallback").textContent = coverInitials(item.title); + const meta = btn.querySelector(".result-meta"); + meta.replaceChildren(); + const addPill = (text) => { + const pill = document.createElement("span"); + pill.className = "result-pill"; + pill.textContent = text; + meta.appendChild(pill); + }; + addPill(`Source: ${providerLabel(item.provider)}`); + if (item.details_ready === false) addPill(item.details_error ? "Audio check unavailable" : "Checking audio..."); + if (item.has_sub) addPill("SUB"); + if (item.has_dub) addPill("DUB"); + addPill(item.episodes ? `${item.episodes} episodes` : `Result ${item.index}`); + } + function renderResults(results) { const el = $("results"); el.innerHTML = ""; @@ -660,6 +685,8 @@ INDEX_HTML = r""" const btn = document.createElement("button"); btn.type = "button"; btn.className = "result-card"; + btn.dataset.resultId = item.id; + if (state.selected && state.selected.id === item.id) btn.classList.add("active"); if (item.watchlist_category_label) btn.classList.add("in-watchlist"); btn.innerHTML = ` @@ -675,24 +702,7 @@ INDEX_HTML = r""" const watchlistTag = btn.querySelector(".watchlist-result-tag"); watchlistTag.textContent = item.watchlist_category_label || ""; watchlistTag.hidden = !item.watchlist_category_label; - const subtitle = btn.querySelector(".result-subtitle"); - const alternativeTitle = Array.isArray(item.alternative_titles) && item.alternative_titles.length - ? String(item.alternative_titles[0].value || "").trim() - : ""; - subtitle.textContent = alternativeTitle ? `Also known as: ${alternativeTitle}` : ""; - subtitle.hidden = !alternativeTitle; - btn.querySelector(".cover-fallback").textContent = coverInitials(item.title); - const meta = btn.querySelector(".result-meta"); - const addPill = (text) => { - const pill = document.createElement("span"); - pill.className = "result-pill"; - pill.textContent = text; - meta.appendChild(pill); - }; - addPill(`Source: ${providerLabel(item.provider)}`); - if (item.has_sub) addPill("SUB"); - if (item.has_dub) addPill("DUB"); - addPill(item.episodes ? `${item.episodes} episodes` : `Result ${item.index}`); + updateResultDetails(btn, item); const img = btn.querySelector("img"); const tile = btn.querySelector(".cover-tile"); img.alt = item.title; @@ -723,17 +733,55 @@ INDEX_HTML = r""" } function modeAvailable(item, mode) { - return Boolean(item && item[`has_${mode}`]); + return Boolean(item && (item.details_ready === false || item[`has_${mode}`])); + } + + function applyResultFilter() { + const language = $("searchLanguage").value; + const byId = new Map(state.results.map(item => [item.id, item])); + const matches = state.results.filter(item => language === "all" || modeAvailable(item, language)); + for (const card of document.querySelectorAll("#results .result-card")) { + card.hidden = language !== "all" && !modeAvailable(byId.get(card.dataset.resultId), language); + } + if (!state.results.length) return 0; + const pending = state.detailsPending ? ` · ${state.detailsPending} audio checks pending` : ""; + $("resultsMeta").textContent = matches.length + ? `${matches.length} matching anime${pending}` + : `No ${language === "sub" ? "subbed" : "dubbed"} results found. Try Sub + Dub.${pending}`; + return matches.length; } function renderFilteredResults() { - const language = $("searchLanguage").value; - const matches = language === "all" ? state.results : state.results.filter(item => modeAvailable(item, language)); - renderResults(matches); - if (state.results.length && !matches.length) { - $("resultsMeta").textContent = `No ${language === "sub" ? "subbed" : "dubbed"} results found. Try Sub + Dub.`; - } - return matches.length; + renderResults(state.results); + return applyResultFilter(); + } + + async function loadSearchResultDetails(requestId) { + const controller = new AbortController(); + state.detailsController = controller; + const results = state.results.filter(item => item.details_ready === false && !item.details_error); + let next = 0; + await Promise.all(Array.from({ length: Math.min(2, results.length) }, async () => { + while (requestId === state.searchRequestId && next < results.length) { + const item = results[next++]; + try { + const details = await api("/api/search/details", { + method: "POST", signal: controller.signal, + body: JSON.stringify({ id: item.id, title: item.title, provider: item.provider }) + }); + if (requestId !== state.searchRequestId) return; + Object.assign(item, details); + } catch (_error) { + if (requestId !== state.searchRequestId || controller.signal.aborted) return; + item.details_error = true; + } + state.detailsPending -= 1; + const card = [...document.querySelectorAll("#results .result-card")] + .find(node => node.dataset.resultId === item.id); + if (card) updateResultDetails(card, item); + applyResultFilter(); + } + })); } async function loadSelectedEpisodes(mode) { @@ -799,9 +847,10 @@ INDEX_HTML = r""" } async function search() { - const requestId = ++state.searchRequestId; const query = $("search-query").value.trim(); if (!query) return setNotice("Type a title first."); + const requestId = ++state.searchRequestId; + if (state.detailsController) state.detailsController.abort(); state.config.provider = $("searchProvider").value; setNotice("Searching..."); $("resultsMeta").textContent = "Searching..."; @@ -811,13 +860,15 @@ INDEX_HTML = r""" $("trackBtn").disabled = true; $("results").innerHTML = ""; try { - const data = await api(`/api/search?q=${encodeURIComponent(query)}&mode=${state.config.mode}&provider=${encodeURIComponent(state.config.provider)}`); + const data = await api(`/api/search?q=${encodeURIComponent(query)}&mode=${state.config.mode}&provider=${encodeURIComponent(state.config.provider)}&fast=1`); if (requestId !== state.searchRequestId) return; state.results = data.results; state.searchQuery = query; state.thumbnailBatch = null; - const matchCount = renderFilteredResults(); - setNotice(`${matchCount} of ${data.results.length} results shown`); + state.detailsPending = state.results.filter(item => item.details_ready === false && !item.details_error).length; + renderFilteredResults(); + setNotice(`Found ${data.results.length} results. Audio availability loads in the background.`); + void loadSearchResultDetails(requestId); } catch (error) { if (requestId !== state.searchRequestId) return; setNotice(error.message); diff --git a/test_app.py b/test_app.py index 8d75724..b43c0a2 100644 --- a/test_app.py +++ b/test_app.py @@ -241,7 +241,144 @@ class SearchPosterBatchTests(unittest.TestCase): self.assertEqual(proc.returncode, 0, proc.stderr) +class FastSearchTests(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(APP, "SEARCH_DETAILS_CACHE", {}) + patcher.start() + self.addCleanup(patcher.stop) + self.summary = {"sub": True, "dub": False, "sub_count": 1, "dub_count": 0, "total": 1, "ready": True} + + def test_fast_search_returns_matches_without_episode_or_alias_requests(self): + with mock.patch.object(provider_bridge, "search", return_value={"results": [ + {"id": "anikoto:one", "title": "One"}, {"id": "anikoto:two", "title": "Two"} + ]}), mock.patch.object(provider_bridge, "episodes", side_effect=AssertionError("Search must not wait for episodes")), mock.patch.object( + APP, "extract_anidb_alternative_titles_for_title", side_effect=AssertionError("Search must not wait for aliases") + ): + results = APP.search_anime("query", "dub", "anikoto", include_details=False) + self.assertEqual([row["title"] for row in results], ["One", "Two"]) + self.assertTrue(all(row["details_ready"] is False and row["has_dub"] is None for row in results)) + + def test_detail_cache_reuses_concurrent_lookups_and_expires(self): + from concurrent.futures import ThreadPoolExecutor + with mock.patch.object(APP.time, "monotonic", return_value=1000), mock.patch.object( + APP, "episode_language_summary", return_value=self.summary + ) as fetch, mock.patch.object(APP, "extract_anidb_alternative_titles_for_title", return_value=[]): + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(lambda _: APP.get_search_result_details("anikoto:one", "One", "anikoto"), range(8))) + fetch.assert_called_once() + self.assertTrue(all(row["details_ready"] and row["has_sub"] for row in results)) + with mock.patch.object(provider_bridge, "search", return_value={"results": [{"id": "anikoto:one", "title": "One"}]}): + quick = APP.search_anime("one", "sub", "anikoto", include_details=False) + self.assertTrue(quick[0]["details_ready"]) + self.assertTrue(quick[0]["has_sub"]) + fetch.assert_called_once() + with mock.patch.object(APP.time, "monotonic", return_value=1301), mock.patch.object( + APP, "episode_language_summary", return_value=self.summary + ) as fetch, mock.patch.object(APP, "extract_anidb_alternative_titles_for_title", return_value=[]): + APP.get_search_result_details("anikoto:one", "One", "anikoto") + fetch.assert_called_once() + + def test_failed_detail_check_stays_unknown_and_is_cached_briefly(self): + with mock.patch.object(provider_bridge, "episodes", side_effect=provider_bridge.ProviderError("blocked")) as fetch, mock.patch.object( + APP, "extract_anidb_alternative_titles_for_title", return_value=[] + ): + first = APP.get_search_result_details("anikoto:one", "One", "anikoto") + self.assertEqual(APP.get_search_result_details("anikoto:one", "One", "anikoto"), first) + fetch.assert_called_once_with("anikoto:one", provider="anikoto", timeout=30) + self.assertTrue(first["details_error"]) + self.assertFalse(first["details_ready"]) + self.assertIsNone(first["has_sub"]) + self.assertIsNone(first["has_dub"]) + + def test_detail_concurrency_is_bounded_across_browser_requests(self): + from concurrent.futures import ThreadPoolExecutor + counters = {"active": 0, "maximum": 0} + lock = threading.Lock() + started, release = threading.Event(), threading.Event() + + def lookup(*_args): + with lock: + counters["active"] += 1 + counters["maximum"] = max(counters["maximum"], counters["active"]) + if counters["active"] == 2: + started.set() + release.wait(2) + with lock: + counters["active"] -= 1 + return self.summary + + with mock.patch.object(APP, "episode_language_summary", side_effect=lookup), mock.patch.object( + APP, "extract_anidb_alternative_titles_for_title", return_value=[] + ), ThreadPoolExecutor(max_workers=8) as pool: + futures = [pool.submit(APP.get_search_result_details, f"anikoto:{index}", str(index), "anikoto") for index in range(8)] + try: + self.assertTrue(started.wait(2)) + finally: + release.set() + for future in futures: + self.assertTrue(future.result()["details_ready"]) + self.assertEqual(counters["maximum"], 2) + + def test_detail_validation_rejects_mismatched_provider_ids(self): + for args in (("pahe:1", "One", "anikoto"), ("unknown:1", "One", "anikoto"), + ("", "One", "anikoto"), ("anikoto:1", "", "anikoto"), ("1", "One", "unknown")): + with self.subTest(args=args), self.assertRaises(ValueError): + APP.get_search_result_details(*args) + + def test_browser_enriches_cards_without_replacing_them_and_ignores_stale_responses(self): + source = APP.INDEX_HTML.split(" function modeAvailable", 1)[1].split(" async function loadSelectedEpisodes", 1)[0] + script = r""" +const assert=require('assert'); +const state={results:[1,2,3].map(id=>({id:String(id),title:'Show '+id,provider:'anikoto',details_ready:false})),searchRequestId:1,detailsPending:3}; +const cards=state.results.map(item=>({dataset:{resultId:item.id},hidden:false})); +const document={querySelectorAll:()=>cards}; +const $=id=>id==='searchLanguage'?{value:'sub'}:{}; +const updateResultDetails=(card,item)=>{card.updated=item.id;}; +const pending=[]; +const api=(path,options)=>new Promise((resolve,reject)=>pending.push({resolve,reject,options})); +""" + "function modeAvailable" + source + r""" +(async()=>{ + assert(modeAvailable(state.results[0],'dub'),'Unknown availability must remain selectable'); + const task=loadSearchResultDetails(1); + assert.strictEqual(pending.length,2,'Only two checks should run'); + pending[0].resolve({details_ready:true,has_sub:false,has_dub:true}); + await new Promise(setImmediate); + assert.strictEqual(pending.length,3); + pending[1].reject(Error('source unavailable')); + pending[2].resolve({details_ready:true,has_sub:true,has_dub:false}); + await task; + assert.deepStrictEqual(cards.map(c=>c.hidden),[true,false,false]); + assert.strictEqual(state.detailsPending,0); + assert(state.results[1].details_error); + assert.strictEqual(cards[0].updated,'1'); + const old={id:'old',title:'Old',provider:'anikoto',details_ready:false}; + state.results=[old];state.detailsPending=1; + const stale=loadSearchResultDetails(1); + state.searchRequestId=2; + pending[3].resolve({details_ready:true,has_sub:true}); + await stale; + assert.strictEqual(old.details_ready,false,'Stale response must not update results'); +})().catch(e=>{console.error(e);process.exitCode=1;}); +""" + proc = subprocess.run(["node", "-e", script], capture_output=True, text=True, timeout=10) + self.assertEqual(proc.returncode, 0, proc.stderr) + + class NetworkGuardTests(unittest.TestCase): + def test_fast_search_route_skips_details_and_details_endpoint_is_available(self): + search = mock.Mock(return_value=[{"id": "anikoto:one", "title": "One", "details_ready": False}]) + handler = DummyHandler("/api/search?q=one&mode=sub&provider=anikoto&fast=1") + handler.handler_context = dataclasses.replace(APP.Handler.handler_context, search_anime=search) + APP.Handler.do_GET(handler) + search.assert_called_once_with("one", "sub", provider="anikoto", include_details=False) + body = json.dumps({"id": "anikoto:one", "title": "One", "provider": "anikoto"}).encode() + details = mock.Mock(return_value={"has_sub": True, "details_ready": True}) + handler = DummyHandler("/api/search/details", body, len(body)) + handler.handler_context = dataclasses.replace(APP.Handler.handler_context, get_search_result_details=details) + APP.Handler.do_POST(handler) + details.assert_called_once_with("anikoto:one", "One", "anikoto") + self.assertEqual(handler.json_payload, {"has_sub": True, "details_ready": True}) + def test_search_provider_failure_returns_service_unavailable_without_webhook(self): handler = DummyHandler("/api/search?q=Witch&mode=dub&provider=pahe") handler.handler_context = dataclasses.replace(