Core extension API
Overview
The core/** module is the shared Kotlin/Android library that extension modules compile against. core/build.gradle.kts declares it as an Android library under namespace keiyoushi.core, with Tachiyomi/Mihon and common dependencies as compileOnly; extension authors get API types and helpers without bundling the host app implementation.
The main extension base class is keiyoushi.source.KeiSource in core/…/KeiSource.kt. It extends Tachiyomi's HttpSource, makes the inherited headers eager, and exposes suspend-first entry points for popular/latest/search, URL search resolution, manga updates, related manga, page lists, and image requests. Subclasses implement getPopularManga, getLatestUpdates, getSearchMangaList, fetchMangaUpdate, and getPageList; URL queries are intercepted in getSearchManga and routed to getMangasByUrl/getMangaByUrl when the query parses as an HttpUrl. getMangaUpdate serializes concurrent updates by SManga.url, requires at least one of details/chapters, and always marks returned manga initialized before handing the SMangaUpdate back to the host.
KeiSource.client centralizes the extension HTTP stack. It starts from the host default client, checks that important host interceptors are present or absent, optionally installs BaseUrlFetchInterceptor before source interceptors, runs the source's configureClient, moves Cloudflare handling below source-specific interceptors, then adds browser request tagging/compression/cache/browser-header behavior. Extension authors customize it by overriding OkHttpClient.Builder.configureClient() rather than overriding client; request helpers in core/…/OkHttp.kt provide suspend get, post, put, head, and call overloads, including context-receiver forms that pull HttpSource.headers automatically.
Base URL state is modeled in core/…/FetchableBaseUrl.kt, CustomUrlPreferences.kt, and MirrorPreferences.kt. CustomUrlPreferences stores overrideBaseUrl, defaultBaseUrl, and fetchedBaseUrl, sanitizes user-entered URLs to scheme/host/port, and exposes an EditTextPreference. MirrorPreferences stores a selected mirror index plus fetched mirror lists and exposes a ListPreference only when there are at least two options. KeiSource.fetchBaseUrls runs once per app launch before the first source request when fetchableBaseUrl is present, normalizes and de-duplicates fetched URLs, and updates either custom URL or mirror state.
Dynamic filters are also handled by KeiSource.kt. Sources that set supportsFilterFetching = true implement fetchFilterData() and a fast, synchronous getFilterList(data: JsonElement?). Core caches fetched JSON as applicationContext.cacheDir/source_$id/filters.json.zst for three days, limits retries to three failures per launch, and returns the source's fallback filters plus a localized header hint while cache data is unavailable.
core/…/UrlActivity.kt is a tiny deep-link shim: when launched with a data URI it starts the host eu.kanade.tachiyomi.SEARCH action with query set to that URI and filter set to the extension package, then exits. core/…/Source.kt provides a source-retention class annotation used by extension tooling.
Key packages/classes
keiyoushi.source(KeiSource.kt, CustomUrlPreferences.kt, MirrorPreferences.kt, FetchableBaseUrl.kt, UrlActivity.kt): Tachiyomi/Mihon source base, base URL preference models, URL search intent bridge, and theFetchableBaseUrlcontract used by base URL discovery.keiyoushi.network(OkHttp.kt, BrowserRequests.kt, BrowserHeaders.kt, RateLimit.kt, Cookie.kt, CacheControlInterceptor.kt, BaseUrlFetchInterceptor.kt, Deflate.kt, XorInterceptor.kt): OkHttp helpers for browser-like request kinds (Fetch.DOCUMENT,XHR,SCRIPT,IMAGE,NONE), header synthesis and wire ordering for Chrome/Firefox/WebKit UAs, default cache control, range-friendly compression, per-source rate limiting, cookie injection, and response-body XOR transforms.keiyoushi.utils(Json.kt, JsonElement.kt, Jsoup.kt, Markdown.kt, Date.kt, Crypto.kt, Binary.kt, GraphQL.kt, NextJs.kt, Protobuf.kt, Inflater.kt, SeedRandom.kt, Preferences.kt, Context.kt, Collections.kt): parsing and serialization helpers for JSON/GraphQL/Protobuf/HTML, Markdown description building, date parsing, crypto/decryption primitives, little-endian/big-endian byte reads, deterministic shuffling, shared preference access by source id, injectedapplicationContext, and small collection helpers.- keiyoushi.utils.WebView.kt, keiyoushi.utils.TurnstileHelper.kt, keiyoushi.webview.internal.WebViewGlueBridge.kt, and
keiyoushi.utils.ui/*: headless or user-visible WebView automation.runWebViewowns a single offscreen WebView, exposes navigation hooks, request interception/proxying through a sourceOkHttpClient, origin-scoped web-message bridges, document-start/event JS injection, user overlays for captcha interaction, and timeouts that pause while the user is actively solving.getTurnstileTokenbuilds on it to solve Cloudflare Turnstile and only shows an overlay when interaction is required.WebViewGlueBridgereflects Chromium support-lib boundary interfaces copied undercore/src/main/kotlin/org/chromium/support_lib_boundary/*so advanced features can be used without depending directly on androidx.webkit at runtime. keiyoushi.zip(Zip.kt, RemoteZip.kt): ZIP central-directory parsing and remote range-reading helpers.zipDirectoryfetches the EOCD tail with HTTP range requests and returns absolute entry offsets;readZipEntryfetches just an entry's local-header/data range and returns a decompressedSourcefor stored or deflated entries.keiyoushi.utils.reactFlightandkeiyoushi.utils.protobuf: supporting serializers/encoders used by NextJs.kt and Protobuf.kt for React Flight special numbers/bigints and streaming protobuf encode/decode.
How extension authors use the APIs
Extension sources should subclass KeiSource from core/…/KeiSource.kt and override the documented suspend methods instead of Tachiyomi's older callback-style parsing methods. Use configureHeaders() to add source headers; core always sets Referer to $baseUrl/, and KeiSource.client later augments per-request browser headers based on Fetch. Use configureClient() to install per-source interceptors, cookies, rate limits, custom DNS/cache/timeouts, GraphQL error interceptors, or XOR/AES decoding.
For HTTP calls, prefer client.get(url, Fetch.XHR), client.get(url, Fetch.DOCUMENT.from(pageUrl)), client.post(url, Fetch.XHR, body), or a manually built Request.Builder().fetch(Fetch.SCRIPT) from core/…/OkHttp.kt and BrowserRequests.kt. Fetch.from controls referrer trimming across redirects and cross-origin hops. Fetch.NONE deliberately sends a request as built; KeiSource.imageRequest adds imageFetch to normal GET image loads when a custom image request did not already set a fetch kind.
Use OkHttpClient.Builder.rateLimit from core/…/RateLimit.kt for sliding-window request limits, defining specific URL predicates before broad rules because the first matching rule wins. Use addCookie from core/…/Cookie.kt to mirror source cookies into both OkHttp requests and Android CookieManager for matching domains.
For common response processing, Json.kt and JsonElement.kt provide parseAs, toJsonRequestBody, toJsonElement, and ergonomic JSON accessors; Jsoup.kt parses responses or strings into Jsoup documents and offers nullable selectors/text helpers; Markdown.kt builds safe Tachiyomi descriptions from text, HTML, ratings, fields, alt titles, and links. GraphQL.kt builds POST bodies or GET query parameters, persisted query extensions, and parseGraphQLAs envelopes. NextJs.kt extracts serializable models from Next.js Pages Router hydration, App Router self.__next_f.push scripts, or raw text/x-component RSC responses, resolving React Flight markers, outlined model refs, maps/sets, lazy refs, promises, large text chunks, dates, bigints, and non-finite numbers.
For encrypted or binary sources, Crypto.kt covers hex decoding, MD5/SHA/HMAC, RC4, XOR response/source transforms, AES CBC/GCM/CTR/ECB, AES streaming response decryption, prepended-IV decryption, EVP_BytesToKey, and CryptoJS-compatible salted AES. Protobuf.kt supports injected ProtoBuf, byte-array/base64 encode/decode, streaming BufferedSource decode, and chunked protobuf RequestBody creation. Zip.kt/RemoteZip.kt let an extension list and fetch image archives without downloading the full ZIP, provided the server honors range requests.
For JavaScript-heavy or protected sites, runWebView in core/…/WebView.kt is the extension-facing WebView DSL. Call loadUrl or loadData once, then resolve/reject from page hooks, polling, JS evaluation, web-message bridges, or intercepted requests. proxyRequest converts selected WebView GETs into OkHttp requests with an inferred Fetch kind so the source client can add the same browser headers and share cookies. showToUser/hideFromUser expose a WebView or selected CSS area when a human tap is needed; getTurnstileToken in TurnstileHelper.kt packages that flow for Cloudflare Turnstile.
Notable tests/resources/translations
- Browser-header behavior is covered by core/…/BrowserHeadersTest.kt, BrowserHeadersCacheTest.kt, and WebKitBrowserHeadersTest.kt, including Chrome/Firefox/WebKit header values, client hints, Origin/Sec-Fetch behavior, redirect/cache interactions, and HTTP/2 wire-order handling.
- Compression and decoding helpers are covered by core/…/DeflateTest.kt, core/…/CryptoTest.kt, XorTest.kt, and ProxyFetchTest.kt.
- core/…/NextJsTest.kt uses fixtures in core/…/*.txt and a regeneration helper under
core/src/test/rsc-capture/to validate real React 19 Flight markers, large text chunks, collections, path refs, promises, and lazy refs. - core/…/MarkdownTest.kt validates escaping, HTML-to-Markdown conversion, rating stars, and description composition. core/…/ZipTest.kt and RemoteZipTest.kt validate local ZIP parsing, ZIP64/name handling, remote range reads, and range-rejection failures.
- core/…/WebViewGlueBridgeTest.kt guards the copied
org.chromium.support_lib_boundary/*interfaces and feature-name strings against androidx.webkit's boundary definitions. - core/…/strings.json provides user-facing strings for shared preference/filter UI:
mirrorTitle,customUrlTitle,customUrlDialogMessage, andfilterFetchHint, with English plus partial Arabic, German, Spanish, Japanese, Portuguese-Brazilian, Russian, Ukrainian, Vietnamese, and Chinese variants. - core/…/ic_launcher.png contains launcher icons packaged by the core Android library.
Coupling
- If
KeiSource.clientin core/…/KeiSource.kt changes interceptor order, verify core/…/BrowserHeaders.kt, BaseUrlFetchInterceptor.kt, CacheControlInterceptor.kt, and RateLimit.kt: base URL rewriting is intentionally first, source interceptors run before Cloudflare is reinserted, browser call tagging must precede the networkBrowserHeadersInterceptor, compression must precede network decoding, and the source rate limiter is deliberately kept as the last network interceptor. - If
Fetch.Kindor request tagging changes in core/…/BrowserRequests.kt, update core/…/BrowserHeaders.kt, core/…/WebView.kt'sproxyFetch, and core/…/KeiSource.kt'simageRequestbehavior together; browser metadata is carried only through OkHttp request tags. - If Chromium WebView support-lib features or boundary interfaces change, update both core/…/WebViewGlueBridge.kt and the copied interfaces under
core/src/main/kotlin/org/chromium/support_lib_boundary/*, then run core/…/WebViewGlueBridgeTest.kt; Chromium looks methods up by the declaring boundary interface signature. - If shared UI strings are renamed or new built-in preference/filter labels are added in core/…/CustomUrlPreferences.kt, MirrorPreferences.kt, or KeiSource.kt, update core/…/strings.json so extension-generated resources keep matching the keys the API expects.
Risks
- core/…/KeiSource.kt uses reflection to replace Tachiyomi
HttpSource's privateheaders$delegate. If the upstream field name or lazy contract changes, source initialization can fail before any network request. - core/…/WebView.kt falls back from native origin-scoped messaging to
addJavascriptInterfaceon old Chromium versions; the fallback ignoresallowedOriginRulesand reports null sender origin, so a bridge handler that trusts origin checks may accept messages from unexpected frames unless it requires modern WebView support. - core/…/RemoteZip.kt assumes servers honor byte range requests and provide a valid
Content-Rangetotal. If a source points it at a CDN that stripsRange,rangeSource()throws and archive-backed chapters cannot load.