* Docs: URL intent filter (keiyoushi/extensions-source#14330) * Docs: URL intent filter * Docs: Changes requested by Luigi * fix typos and improve clarity --------- Co-authored-by: AwkwardPeak7 <48650614+AwkwardPeak7@users.noreply.github.com> (cherry picked from commit ba2e51e60d05051cba078c3b42d0b6306a37d9fd) * Update CONTRIBUTING.md (keiyoushi/extensions-source#14788) * spelling mistakes * add keiyoushi.utils (core utilities) * Misc notes edit * JSON models (DTOs) and serialization * Extension logic and app features * HTML and Image Processing, OkHttp and Network * dto.kt filters.kt naming scheme rule * Serializable private fields * Memory-efficient Image Interceptors rewrite * Misc notes Store minimal unique URL * add prevent memory leaks * Update CONTRIBUTING.md Co-authored-by: Abdullah Al-Shamiry (Ace) <its.shamiry@gmail.com> * Update CONTRIBUTING.md Co-authored-by: Abdullah Al-Shamiry (Ace) <its.shamiry@gmail.com> * Update CONTRIBUTING.md Co-authored-by: Romain <wycvhrt6vzscfpedxr@gmail.com> * Update CONTRIBUTING.md Co-authored-by: Abdullah Al-Shamiry (Ace) <its.shamiry@gmail.com> * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * Update CONTRIBUTING.md * add lib tools explanation * lib tools shrink * Available libs edit * Loading a subset of Gradle modules edit * Cloning the repository edit * Update CONTRIBUTING.md Co-authored-by: AwkwardPeak7 <48650614+AwkwardPeak7@users.noreply.github.com> * Update CONTRIBUTING.md Co-authored-by: AwkwardPeak7 <48650614+AwkwardPeak7@users.noreply.github.com> * Generating Page lists edit * OkHttp and Network edit * Chapter Pages edit * Misc notes edit * Extension logic and app features edit * Multi-source themes edit * change “” to "" * JSON models (DTOs) and serialization edit * Misc notes edit * Rewrite the multisrc section + some additional changes * Update CONTRIBUTING.md Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * Update CONTRIBUTING.md Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * Generating Page lists edit * Grammar, Formatting, Markdown, Explanations edit * Table of Contents Edit * Update CONTRIBUTING.md Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * Update CONTRIBUTING.md Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * Update CONTRIBUTING.md Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * Apply suggestions from code review Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * missed review commits * Fix Ammount of # and Replace Em Dashes * Mixing * and - unordered lists. - is used elsewhere. edit * Core dependencies title edit * Update CONTRIBUTING.md --------- Co-authored-by: Abdullah Al-Shamiry (Ace) <its.shamiry@gmail.com> Co-authored-by: Romain <wycvhrt6vzscfpedxr@gmail.com> Co-authored-by: AwkwardPeak7 <48650614+AwkwardPeak7@users.noreply.github.com> Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> (cherry picked from commit 948a94ae6620ea0b042e3ec39da7539d21f26c5b) (cherry picked from commit b32aa5fb8a1a9f37804618d95657919c3a2fd02f) (cherry picked from commit 1a98617d44706d23cb631ea78917bbd0e6417b64) * Edit Contributing.md (keiyoushi/extensions-source#15117) * Media Types Edit * Add Protobuf parsing and serialization section * JSON parsing and JSON serialization edit (cherry picked from commit 1534e22c244ca4af9cd82dd9b6d588e360a7c510) (cherry picked from commit b699b2794e234ae1cc3c103d9dcdd84279fabee7) (cherry picked from commit c039de28d7b796c797397503a93e649dd3acabb0) * lint `CONTRIBUTING.md` (keiyoushi/extensions-source#15133) (cherry picked from commit 6306e551a5ca29c28a7994f0880d9556b7b84818) (cherry picked from commit 78fd2bdc8f29637633a754b2b8e71a079b8304a4) * Update CONTRIBUTING.md (keiyoushi/extensions-source#15530) * Update mandatory fields requirements in CONTRIBUTING.md * Update CONTRIBUTING.md with best practices Added guidelines for using custom headers and overriding HttpSource methods. * Enhance CONTRIBUTING.md with code sectioning advice Added guidelines for organizing methods in extension classes for better readability. * Revise code organization and mandatory fields guidelines Updated guidelines for code organization and mandatory fields in CONTRIBUTING.md. (cherry picked from commit bf1788640af871b45c87597f4bdcbdb6aedb2773) (cherry picked from commit 86fa3e4bb222ae09a43b36013e7a28edc8ea6d0e) * Update PR template with AI check (keiyoushi/extensions-source#15629) * update PR template with AI check * update (cherry picked from commit 76670add437924cbdb40b269d2da5c1b482f4cb8) (cherry picked from commit 41efb8492b14379ffafec0f2eb326b16d398d792) * [skip ci] tweak contributing guidelines with common PR suggestions (keiyoushi/extensions-source#15635) * [skip ci] tweak contributing guidelines with common PR suggestions * [skip ci] em-dash, emoji * [skip ci] prefer id/slug (cherry picked from commit c52288f0b4d6dd06e9cc1c525722adc48cf39b84) (cherry picked from commit d17be38f3c37be95737a2bdcc7934cb5e3d61241) (cherry picked from commit eb185477d1e84639c76a09e3f5b8a7844de7d216) * Update CONTRIBUTING.md (keiyoushi/extensions-source#15829) Update contributing guidelines with best practices (cherry picked from commit a3edac4f638f0f2b704376fc13accfaab063f5f7) (cherry picked from commit 847b9c883342a43bd42474be2f7189c23a026088) * Enhance CONTRIBUTING.md with new guidelines (keiyoushi/extensions-source#15860) * Enhance CONTRIBUTING.md with new guidelines Add guidelines for configurable sources and preferences in CONTRIBUTING.md * Update CONTRIBUTING.md with JSON and method guidelines Clarify guidelines on JSON handling and method overrides. (cherry picked from commit afa7562f33a875dfee2d54b9a73312fd2c9105a2) (cherry picked from commit 44fd972567cfb728621a8c4c339549ed1eec7346) * Rework Gradle build logic (keiyoushi/extensions-source#15657) * Add new gradle build logic * rework ko.wolfdotcom * rework all other extensions (cherry picked from commit 153fbece55832e8a76f32e26199bb6f8f4252fcb) --------- Co-authored-by: Cuong-Tran <16017808+cuong-tran@users.noreply.github.com> (cherry picked from commit b030eeff0bc2e68fff2f070a86c851d950f82145) (cherry picked from commit d7ba3e81a5a0af9c91d96bee014592e991c4efd9) * Refactor: Replace deprecated network.cloudflareClient globally (keiyoushi/extensions-source#15988) * Cloudflare: update extensions and multisrc * undo * Update Cloudflare client usage instructions * Cloudflare: update extensions and multisrc * Update lib-multisrc/comicaso/src/eu/kanade/tachiyomi/multisrc/comicaso/Comicaso.kt Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> * Fix client initialization in CONTRIBUTING.md * remove redundant `client` overrides * UNDO AGAIN... --------- Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> (cherry picked from commit 29b999187a6256198bfc238fd456a891fb753019) (cherry picked from commit 372bc6d78875e0a4ae9d394da8b9875b17b01b21) * Refactor to anime/episode * Change references from "Aniyomi" to "Anikku" in CONTRIBUTING.md and README.md. * Update section titles and content to align with the focus on anime instead of manga. --------- Co-authored-by: CriosChan <36739192+CriosChan@users.noreply.github.com> Co-authored-by: AwkwardPeak7 <48650614+AwkwardPeak7@users.noreply.github.com> Co-authored-by: darwin-256 <viktorasordinass@gmail.com> Co-authored-by: Abdullah Al-Shamiry (Ace) <its.shamiry@gmail.com> Co-authored-by: Romain <wycvhrt6vzscfpedxr@gmail.com> Co-authored-by: Vetle Ledaal <vetle.ledaal@gmail.com> Co-authored-by: FourTOne5 <107297513+FourTOne5@users.noreply.github.com>
72 KiB
Contributing
This guide has some instructions and tips on how to create a new Anikku extension. Please read it carefully if you're a new contributor or don't have any experience on the required languages and knowledges.
This guide is not definitive and it's being updated over time. If you find any issues in it, feel free to report it through a Meta Issue or fixing it directly by submitting a Pull Request.
Table of Contents
- Contributing
- Table of Contents
- Prerequisites
- Getting help
- Writing an extension
- Setting up a new Gradle module
- Loading a subset of Gradle modules
- Core dependencies
- Extension API
- lib tools
- Available libs
- Adding a lib dependency
- i18n library
- Creating a new lib
- keiyoushi.utils (core utilities)
- JSON parsing -
parseAs - JSON serialization -
toJsonString/toJsonRequestBody - JSON models (DTOs) and serialization
- Protobuf parsing and serialization -
parseAsProto/toRequestBodyProto - Date parsing -
tryParse - Filter helpers -
firstInstance/firstInstanceOrNull - Next.js data extraction -
extractNextJs/extractNextJsRsc - Extracting URLs -
setUrlWithoutDomain+absUrl
- JSON parsing -
- Additional dependencies
- Extension main class
- HTML and Video Processing
- OkHttp and Network
- Extension call flow
- Misc notes
- Advanced Extension features
- Multi-source themes
- Running
- Debugging
- Building
- Submitting the changes
Prerequisites
Before you start, please note that the ability to use following technologies is required and that existing contributors will not actively teach these to you.
- Basic Android development
- Kotlin
- Web scraping
Tools
- Android Studio
- Emulator or phone with developer options enabled and a recent version of Anikku installed
- Icon Generator
- Try jsoup
Cloning the repository
Some alternative steps can be followed to skip unrelated sources, which will make it faster to pull, navigate and build. This will also reduce disk usage and network traffic.
Due to the large size of this repository, it is highly recommended to do a partial clone to save network traffic and disk space.
Steps
-
Do a partial clone.
git clone --filter=blob:none --sparse <fork-repo-url> cd anime-extensions/ -
Configure sparse checkout.
There are two modes of pattern matching. The default is cone mode. Cone mode enables significantly faster pattern matching for big monorepos and the sparse index feature to make Git commands more responsive. In this mode, you can only filter by file path, which is less flexible and might require more work when the project structure changes.
You can skip this code block to use legacy mode if you want easier filters. It won't be much slower as the repo doesn't have that many files.
To enable cone mode together with sparse index, follow these steps:
git sparse-checkout set --cone --sparse-index # add project folders git sparse-checkout add common core gradle lib lib-multisrc utils # add a single source git sparse-checkout add src/<lang>/<source>To remove a source, open
.git/info/sparse-checkoutand delete the exact lines you typed when adding it. Don't touch the other auto-generated lines unless you fully understand how cone mode works, or you might break it.To use the legacy non-cone mode, follow these steps:
# enable sparse checkout git sparse-checkout set --no-cone # edit sparse checkout filter vim .git/info/sparse-checkout # alternatively, if you have VS Code installed code .git/info/sparse-checkoutHere's an example:
/* !/src/* !/multisrc-lib/* # allow a single source /src/<lang>/<source> # allow a multisrc theme /lib-multisrc/<source> # or type the source name directly <source>Explanation: the rules are like
gitignore. We first exclude all sources while retaining project folders, then add the needed sources back manually. -
Configure remotes.
# add upstream git remote add upstream <yuzono-url> # optionally disable push to upstream git remote set-url --push upstream no_pushing # optionally fetch master only (ignore all other branches) git config remote.upstream.fetch "+refs/heads/master:refs/remotes/upstream/master" # update remotes git remote update # track master of upstream instead of fork git branch master -u upstream/master -
Useful configurations. (optional)
# prune obsolete remote branches on fetch git config remote.origin.prune true # fast-forward only when pulling master branch git config pull.ff only # Add an alias to sync master branch without fetching useless blobs. # If you run `git pull` to fast-forward in a blobless clone like this, # all blobs (files) in the new commits are still fetched regardless of # sparse rules, which makes the local repo accumulate unused files. # Use `git sync-master` to avoid this. Be careful if you have changes # on master branch, which is bad practice. git config alias.sync-master '!git switch master && git fetch upstream && git reset --keep FETCH_HEAD' -
Later, if you change the sparse checkout filter, run
git sparse-checkout reapply.
Read more on Git's object model, partial clone, sparse checkout, sparse index, and negative refspecs.
Getting help
- Join the Discord server for online help and to ask questions while
developing your extension. When doing so, please ask them in the
#devchannel. - There are some features and tricks that are not explored in this document. Refer to existing extension code for examples.
Writing an extension
The quickest way to get started is to copy an existing extension's folder structure and renaming it as needed. We also recommend reading through a few existing extensions' code before you start.
Setting up a new Gradle module
Each extension should reside in src/<lang>/<mysourcename>. Use all as <lang> if your target
source supports multiple languages or if it could support multiple sources.
The <lang> used in the folder inside src should be the major language part. For example, if
you will be creating a pt-BR source, use <lang> here as pt only. Inside the source class, use
the full locale string instead.
Loading a subset of Gradle modules
By default, all individual and multisrc extensions are loaded for local development. This may be inconvenient and can drastically slow down your system when working on a single extension.
To adjust which modules are loaded, make adjustments to the settings.gradle.kts file as needed. You can specify the single extension you want to work on in the load individual extension function. This helps avoid loading unnecessary modules, making the build process more efficient and preventing your CPU from being overworked.
Extension file structure
The simplest extension structure looks like this:
$ tree src/<lang>/<mysourcename>/
src/<lang>/<mysourcename>/
├── AndroidManifest.xml (optional)
├── build.gradle
├── res
│ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ └── mipmap-xxxhdpi
│ └── ic_launcher.png
└── src
└── eu
└── kanade
└── tachiyomi
└── animeextension
└── <lang>
└── <mysourcename>
├── <MySourceName>.kt
├── <Dto>.kt (optional)
├── <Filters>.kt (optional)
└── <UrlActivity>.kt (optional)
<lang> should be an ISO 639-1 compliant language code (two letters or all). <mysourcename>
should be adapted from the site name, and can only contain lowercase ASCII letters and digits.
Your extension code must be placed in the package eu.kanade.tachiyomi.animeextension.<lang>.<mysourcename>.
Tip
Additional files in the extension package (like
Dto.kt,Filters.kt,UrlActivity.kt) should NOT repeat the extension name (e.g. useDto.ktinstead ofMySourceNameDto.kt). Note: While older extensions might use the repeated name pattern, avoiding it is a newly enforced convention to maintain consistency across the repository.
AndroidManifest.xml (optional)
You only need to create this file if you want to add deep linking to your extension. See URL intent filter for more information.
build.gradle
Make sure that your new extension's build.gradle file follows the following structure:
ext {
extName = '<My source name>'
extClass = '.<MySourceName>'
extVersionCode = 1
isNsfw = true
}
apply plugin: "kei.plugins.extension.legacy"
| Field | Description |
|---|---|
extName |
The name of the extension. Should be romanized if site name is not in English. |
extClass |
Points to the class that implements AnimeSource. You can use a relative path starting with a dot (the package name is the base path). This is used to find and instantiate the source(s). |
extVersionCode |
The extension version code. This must be a positive integer and incremented with any change to the code. Do not bump for changes that do not affect users, such as changing a private function to a public function. |
isNsfw |
Flag to indicate that a source contains NSFW content. Should always be set explicitly to either true or false. Falls back to false if not set. |
The extension's version name is generated automatically by concatenating 14 and extVersionCode.
With the example used above, the version would be 14.1.
Core dependencies
Extension API
Extensions rely on aniyomi-extensions-lib, which provides some interfaces and stubs from the app for compilation purposes. The actual implementations can be found in the Anikku source code. Referencing the actual implementation will help with understanding extensions' call flow.
lib tools
The lib/ directory contains reusable Gradle modules that solve common problems shared across
multiple extensions, such as cookie injection, stream descrambling, JavaScript deobfuscation, and
more. Before implementing something from scratch, check whether an existing lib already covers your
use case. Each lib is self-documented via KDoc comments and/or a README in its own folder.
Available libs
| Module | Description |
|---|---|
lib-cookieinterceptor |
Injects cookies into OkHttp requests for a given domain |
lib-cryptoaes |
AES-CBC decryption compatible with CryptoJS; JSFuck deobfuscation |
lib-randomua |
Fetches and rotates real-world User-Agent strings |
lib-synchrony |
JavaScript deobfuscation via the Synchrony engine (QuickJS sandbox) |
lib-textinterceptor |
Renders plain text or HTML as a PNG image page |
lib-unpacker |
Unpacks Dean Edwards-packed JavaScript; substring extraction helpers |
Note
The table above highlights the most commonly used libraries. Check the
lib/directory for the full list of available modules and their specific READMEs.
Adding a lib dependency
Declare the module in your extension's build.gradle:
dependencies {
implementation(project(':lib:<name>'))
}
For example:
dependencies {
implementation(project(':lib:dataimage'))
}
Gradle resolves transitive dependencies automatically, so you only need to declare the lib you are directly using.
i18n library
lib-i18n is a library for handling
internationalization in the sources. It allows loading .properties files with messages located under
the assets/i18n folder of each extension, that can be used to translate strings under the source.
Creating a new lib
If no existing lib fits your needs and the functionality is generic enough to be shared across multiple extensions, you can create a new one.
A lib follows this structure:
lib/<mylibname>/
├── build.gradle.kts
└── src
└── keiyoushi
└── lib
└── <mylibname>
└── MyLib.kt
A video source extractor lib follows this structure:
lib/<mylibname>/
├── build.gradle.kts
└── src
└── aniyomi
└── lib
└── <mylibname>
└── MyLib.kt
The build.gradle.kts must apply the kei.plugins.library plugin:
plugins {
alias(kei.plugins.library)
}
If your lib depends on another lib, declare it in the same file:
plugins {
alias(kei.plugins.library)
}
dependencies {
implementation(project(":lib:<other-lib>"))
}
Place your code in the package keiyoushi.lib.<mylibname> or aniyomi.lib.<mylibname>. Document public API with KDoc so
contributors can understand the lib without needing to read CONTRIBUTING.md.
keiyoushi.utils (core utilities)
The core/utils module provides a set of shared extension functions that are available to all extensions
without any extra Gradle dependency. Prefer using these helpers instead of implementing your own equivalents, as they provide standardized and maintained solutions.
The utilities live in the keiyoushi.utils package and are imported individually.
JSON parsing - parseAs
Use keiyoushi.utils.parseAs to deserialize JSON. It works on String, Response, InputStream, and JsonElement receivers and uses the shared jsonInstance (a pre-configured Json with ignoreUnknownKeys = true). The Response and InputStream variants use efficient stream decoding and automatically close the stream after reading.
import keiyoushi.utils.parseAs
// From a Response (uses streaming and consumes the body):
val dto = response.parseAs<MyDto>()
// From a String:
val dto = jsonString.parseAs<MyDto>()
// With a transform applied before parsing (e.g., stripping JSONP callbacks):
val dto = response.parseAs<MyDto> { it.substringAfter("callback(").dropLast(1) }
Do not create a local private val json: Json by injectLazy() unless you specifically need a custom JSON configuration (e.g., isLenient = true or custom serializers). For standard parsing, the global instance is already available via jsonInstance and the parseAs helpers use it automatically.
JSON serialization - toJsonString / toJsonRequestBody
Use keiyoushi.utils.toJsonString to serialize an object to a JSON string. If you are sending a POST/PUT request, use keiyoushi.utils.toJsonRequestBody to directly convert your object into an OkHttp RequestBody with the correct application/json media type.
import keiyoushi.utils.toJsonRequestBody
import keiyoushi.utils.toJsonString
// To a RequestBody for OkHttp (recommended for APIs):
val body = myRequestDto.toJsonRequestBody()
// To a simple String:
val jsonString = myRequestDto.toJsonString()
JSON models (DTOs) and serialization
When defining @Serializable classes for JSON parsing, do not use data class unless you actually need data class features (like copy() or destructuring). Use a regular class instead to reduce the generated bytecode size.
Always use camelCase for Kotlin properties. Only use @SerialName when the JSON key does not match the property name (e.g., mapping a snake_case JSON key like cover_img to coverImg, or an invalid Kotlin identifier like _count to count). If the JSON key already matches the property name exactly, @SerialName is redundant and should be omitted. It is also recommended to make fields private if they are only used internally (for instance, when mapping directly to SAnime or SEpisode within the DTO).
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
// Bad: Using data class and snake_case variable names
@Serializable
data class MyDto(val anime_id: Int, val cover_img: String)
// Good: Regular class, camelCase variables mapped with @SerialName only when names differ, and private fields
@Serializable
class MyDto(
@SerialName("anime_id") private val animeId: Int,
@SerialName("cover_img") private val coverImg: String,
private val title: String, // No @SerialName needed if JSON key is "title"
@SerialName("_count") private val count: Int, // Needed for invalid Kotlin identifiers
) {
fun toSAnime() = SAnime.create().apply {
url = animeId.toString()
thumbnail_url = coverImg
this.title = title
}
}
- Use
@Serializableclasses instead ofJsonObject: Do not manually traverseJsonObjectorJsonArray. Define@Serializableclasses and useparseAs<T>(). - Map only used fields: Do not map all fields from the JSON response in your DTOs if they are not used. Omit unused fields to keep the class clean and reduce bytecode.
- Mandatory fields should not have defaults: Do not provide default empty/null values to mandatory fields (like an anime's ID or title) in DTOs just to avoid parsing exceptions. Let the parser fail early so broken entries are detected.
- Avoid
buildJsonObjectfor requests: Instead of manually buildingJsonObjectwithbuildJsonObject { put(...) }, define a@Serializablerequest DTO class and usetoJsonRequestBody(). - Avoid manual JSON string reading: Avoid manually reading the response body as a string to parse JSON (e.g.,
response.body.string()orresponse.peekBody(Long.MAX_VALUE).string()outside of interceptors). Useresponse.parseAs<T>()directly, which handles efficient stream decoding and automatically closes the response body.
Protobuf parsing and serialization - parseAsProto / toRequestBodyProto
If a source's API uses Protocol Buffers (Protobuf) instead of JSON, use the keiyoushi.utils helpers to decode and encode the data. These extensions use a shared protoInstance and automatically handle resource management.
import keiyoushi.utils.parseAsProto
import keiyoushi.utils.toRequestBodyProto
import keiyoushi.utils.decodeProtoBase64
// From a Response (automatically closes the body):
val dto = response.parseAsProto<MyProtoDto>()
// From a Response with a transform applied before decoding:
val dto = response.parseAsProto<MyProtoDto> { bytes -> bytes.drop(4).toByteArray() }
// Decoding a Base64-encoded Protobuf string:
val dto = base64String.decodeProtoBase64<MyProtoDto>()
// Creating a RequestBody for a POST request (defaults to application/protobuf):
val requestBody = myRequestDto.toRequestBodyProto()
If you only need to work with raw bytes, you can also use .decodeProto() and .encodeProto() directly on a ByteArray.
Do not create a local private val proto: ProtoBuf by injectLazy() unless you specifically need a custom configuration. For standard parsing, the global instance is already available and the parseAsProto helpers use it automatically.
Date parsing - tryParse
Use keiyoushi.utils.tryParse on a SimpleDateFormat instance to safely parse a date string.
It returns 0L on failure or when the input is null, which is exactly what the app expects.
import keiyoushi.utils.tryParse
// Declare dateFormat at class/file level - creating SimpleDateFormat is expensive:
private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).apply {
timeZone = TimeZone.getTimeZone("UTC")
}
episode.date_upload = dateFormat.tryParse(dateStr)
Do not write manual try/catch blocks or null-guards around SimpleDateFormat.parse() -
tryParse handles both. Also, always declare your SimpleDateFormat as a class-level or
file-level val so it is not reconstructed for every episode.
Two common mistakes to avoid:
-
Always set
Locale.ROOT, unless the pattern contains locale-sensitive text (such as month names) - in which case use the appropriate locale. -
Set the timezone if known. Either if the site's region is known, or because the pattern uses a literal
'Z'.// Wrong: 'Z' is treated as a literal character, timezone defaults to device local time SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT) // Correct: SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ROOT).apply { timeZone = TimeZone.getTimeZone("UTC") } // Also correct (Z without quotes parses the timezone offset from the string): SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ROOT)
Filter helpers - firstInstance / firstInstanceOrNull
Use these instead of filterIsInstance<T>().first() / filterIsInstance<T>().firstOrNull().
import keiyoushi.utils.firstInstance
import keiyoushi.utils.firstInstanceOrNull
val genreFilter = filters.firstInstanceOrNull<GenreFilter>()
SharedPreferences - getPreferences / getPreferencesLazy
Use these instead of accessing Injekt manually.
import keiyoushi.utils.getPreferences
import keiyoushi.utils.getPreferencesLazy
// Eager:
private val preferences = getPreferences()
// Lazy (recommended for most cases):
private val preferences by getPreferencesLazy()
Next.js data extraction - extractNextJs / extractNextJsRsc
If the site is built with Next.js, use keiyoushi.utils.extractNextJs on a Document or Response,
or keiyoushi.utils.extractNextJsRsc on a raw RSC response string to pull typed data out of the
hydration payload without fragile HTML scraping.
import keiyoushi.utils.extractNextJs
val data = response.extractNextJs<MyDto>()
// Or with an explicit predicate:
val data = document.extractNextJs<MyDto> { element ->
element is JsonObject && "slug" in element
}
For client-side navigation responses (text/x-component content type), pass the rsc: 1
request header and use extractNextJsRsc on the response body string.
See #14266 and
#14446 for real-world usage.
Extracting URLs - setUrlWithoutDomain + absUrl
When extracting URLs from HTML, prefer element.absUrl("href") or element.attr("abs:href") over manually concatenating baseUrl + path. Combined with setUrlWithoutDomain(), this safely handles both absolute and relative links.
// Risky - setUrlWithoutDomain cannot resolve all relative URLs:
setUrlWithoutDomain(element.attr("href"))
// Safe:
setUrlWithoutDomain(element.absUrl("href"))
Additional dependencies
If you find yourself needing additional functionality, you can add more dependencies to your build.gradle
file. Many of the dependencies
from the app are exposed to extensions by default.
Note
Several dependencies are already exposed to all extensions via Gradle's version catalog. To view which are available check the
gradle/libs.versions.tomlfile.
Notice that we're using compileOnly instead of implementation if the app already contains it.
You could use implementation instead for a new dependency, or you prefer not to rely on whatever
the main app has at the expense of app size.
Important
Using
compileOnlyrestricts you to versions that must be compatible with those used in the latest stable version of the app.
Extension main class
The class which is referenced and defined by extClass in build.gradle. This class should implement
either AnimeSourceFactory or AnimeHttpSource.
| Class | Description |
|---|---|
AnimeSourceFactory |
Used to expose multiple AnimeSources. Use this in case of a source that supports multiple languages or mirrors of the same website. |
AnimeHttpSource |
For online source, where requests are made using HTTP. |
ParsedAnimeHttpSource |
Deprecated, use AnimeHttpSource instead. |
Main class key variables
| Field | Description |
|---|---|
name |
Name displayed in the "Sources" tab in the app. |
baseUrl |
Base URL of the source without any trailing slashes. |
lang |
An ISO 639-1 compliant language code (two letters in lower case in most cases, but can also include the country/dialect part by using a simple dash character). |
id |
Identifier of your source, automatically set in AnimeHttpSource. It should only be manually overridden if you need to copy an existing autogenerated ID. |
HTML and Video Processing
-
Parsing partial HTML: If an API returns a JSON response containing an HTML string, use
Jsoup.parseBodyFragment(html, baseUrl)instead ofJsoup.parse(html). Passing thebaseUrlensures thatabs:hrefandabsUrl()can correctly resolve relative links. -
Formatting Episode Numbers: Do not write custom
DecimalFormatlogic just to remove trailing zeros from float episode numbers. Simply use.toString().removeSuffix(".0"). -
Generating Video lists: Return a
List<Video>fromvideoListParseorgetVideoList. EachVideoneeds a display name (quality), a stream URL, and optionally custom headers. Example:return document.select("source").map { source -> Video(source.attr("abs:src"), source.attr("label"), source.attr("abs:src")) } -
Memory-efficient Video Interceptors: When implementing interceptors for decrypting or transforming video streams, avoid loading the entire file into a
ByteArrayon low-end devices. Prefer stream-based processing instead:- Read: Use
response.body.byteStream()when you need to process the response body incrementally. - Write: Write processed output into an Okio
Bufferviaoutput.outputStream()and convert it usingasResponseBody(mediaType). - Decryption: Use Okio's
cipherSourceextension for stream-based decryption rather than decrypting a full byte array in memory. - Note:
readByteArray()should generally be avoided here because it forces full in-memory buffering of the video. Streaming directly keeps memory usage lower and more stable. - Always wrap network responses in
response.use { ... }to ensure the response body is properly closed and to prevent memory leaks.
- Read: Use
-
Do not manually check for Cloudflare: Do not manually check for Cloudflare challenges (e.g., checking for "Just a moment..." text) in
parsemethods. The app handles this before calling the parser. -
Prefer stable selectors: Avoid relying on volatile auto-generated CSS class names (e.g.,
styles_Card__jN8og) or complex regex for parsing. Prefer stable structural selectors. -
Use
ownText()to avoid mutation: To get text from an element without including text from its children, use.ownText(). This avoids having to select and remove child elements (.select().remove()) or mutate the document. -
Parse status using
.lowercase(): When comparing strings for status parsing (e.g.,contains("ongoing")), prefer calling.lowercase()on the source string once instead of usingignoreCase = trueon multiplecontainschecks.
OkHttp and Network
-
Always pass
headers: EveryGET()andPOST()call must includeheaders(or a custom headers object). Omitting headers will send the request without the app's default User-Agent and other expected headers. -
Referer header trailing slash: When setting a
Refererheader pointing to the site root, always include a trailing slash:.add("Referer", "$baseUrl/"). This matches what browsers send and is required by some servers. -
Static URLs don't need
HttpUrl.Builder: Use string interpolation directly for URLs with no dynamic query parameters. Only useHttpUrl.Builder(or.toHttpUrl().newBuilder()) when query parameters need URL-encoding or the URL is built conditionally.// Unnecessary builder for a static URL: val url = "$baseUrl/anime".toHttpUrl().newBuilder().build() // Prefer: return GET("$baseUrl/anime", headers) -
GraphQL Queries: If you are sending GraphQL requests, use Kotlin's raw multi-dollar string interpolation (
$$"""...""") for your queries. This prevents having to escape every JSON variable$symbol manually. -
Empty checks on
.text(): Because Jsoup's.text()automatically trims whitespace, you can use.isNotEmpty()instead of.isNotBlank()when checking for empty strings. The same applies to.ownText(). This also means you should not use.trim()with these functions. -
Use
network.clientfor Cloudflare: When overriding the client for sources protected by Cloudflare, simply useoverride val client = network.client.newBuilder().... The defaultclientnow handles Cloudflare challenges automatically. Do not usenetwork.cloudflareClient, as it is deprecated. -
Never use
Thread.sleep(): Do not useThread.sleep()for rate limiting. Use OkHttp'srateLimitHostinterceptor instead. -
Avoid synchronous calls in
parsemethods: Do not callclient.newCall(...).execute()inside parsing methods likevideoListParseorepisodeListParse. Make the request part of the standard flow by overriding the corresponding request method (e.g.,videoListRequest) orgetVideoList. -
Pass
HttpUrldirectly: TheGET()andPOST()helpers accept anHttpUrlobject. Do not call.toString()on a builtHttpUrlbefore passing it. -
Use
HttpUrlfor URL manipulation: When parsing or extracting parts of a URL, prefer usingHttpUrlmethods (likepathSegments()orqueryParameter()) over manual string splitting or regex. It is safer and handles edge cases better. -
Use
CookieInterceptorfor custom cookies: When you need to inject custom cookies into requests, use thelib-cookieinterceptordependency instead of manually addingCookieheaders. Manually setting theCookieheader overrides all cookies (including Cloudflare cookies set via WebView), breaking login and challenge solving.
Extension call flow
Popular Anime
a.k.a. the Browse source entry point in the app (invoked by tapping on the source name).
- The app calls
getPopularAnime(or usespopularAnimeRequest/popularAnimeParse) which should return anAnimesPagecontaining the first batch of foundSAnimeentries.- This method supports pagination. When user scrolls the anime list and more results must be fetched,
the app calls it again with increasing
pagevalues (starting withpage=1). This continues whileAnimesPage.hasNextPageis passed astrueandAnimesPage.animesis not empty.
- This method supports pagination. When user scrolls the anime list and more results must be fetched,
the app calls it again with increasing
- To show the list properly, the app needs
url,titleandthumbnail_url. You must set them here. The rest of the fields could be filled later (refer to Anime Details below).
Latest Anime
a.k.a. the Latest source entry point in the app (invoked by tapping on the "Latest" button beside the source name).
- Enabled if
supportsLatestistruefor a source - Similar to popular anime, but should be fetching the latest entries from a source.
Anime Search
- When the user searches inside the app,
getSearchAnime(orsearchAnimeRequest/searchAnimeParse) will be called and the rest of the flow is similar to what happens withgetPopularAnime.- If search functionality is not available, return
AnimesPage(emptyList(), false)from the corresponding parse method.
- If search functionality is not available, return
getFilterListwill be called to get all filters and filter types.
Filters
The search flow has support for filters that can be added to an AnimeFilterList inside the
getFilterList method. When the user changes the filters' state, they will be passed to
searchAnimeRequest, and they can be iterated to create the request (by getting the
filter.state value, where the type varies depending on the AnimeFilter used). You can check the
filter types available in AnimeFilter.kt
and in the table below.
| Filter | State type | Description |
|---|---|---|
AnimeFilter.Header |
None | A simple header. Useful for separating sections in the list or showing any note or warning to the user. |
AnimeFilter.Separator |
None | A line separator. Useful for visual distinction between sections. |
AnimeFilter.Select<V> |
Int |
A select control, similar to HTML's <select>. Only one item can be selected, and the state is the index of the selected one. |
AnimeFilter.Text |
String |
A text control, similar to HTML's <input type="text">. |
AnimeFilter.CheckBox |
Boolean |
A checkbox control, similar to HTML's <input type="checkbox">. The state is true if it's checked. |
AnimeFilter.TriState |
Int |
A enhanced checkbox control that supports an excluding state. The state can be compared with STATE_IGNORE, STATE_INCLUDE and STATE_EXCLUDE constants of the class. |
AnimeFilter.Group<V> |
List<V> |
A group of filters (preferentially of the same type). The state will be a List with all the states. |
AnimeFilter.Sort |
Selection |
A control for sorting, with support for the ordering. The state indicates which item index is selected and if the sorting is ascending. |
All control filters can have a default state set. It's usually recommended, if the source has filters to make the initial state match the popular anime list. This way, when the user opens the filter sheet the state accurately represents the currently displayed anime.
The AnimeFilter classes can also be extended, so you can create new custom filters like the UriPartFilter:
open class UriPartFilter(displayName: String, private val vals: Array<Pair<String, String>>) :
AnimeFilter.Select<String>(displayName, vals.map { it.first }.toTypedArray()) {
fun toUriPart() = vals[state].second
}
Anime Details
- When user taps on an anime,
getAnimeDetailsandgetEpisodeListwill be called and the results will be cached.- A
SAnimeentry is identified by itsurl.
- A
getAnimeDetailsis called to update an anime's details from when it was initialized earlier.SAnime.initializedtells the app if it should callgetAnimeDetails. If you are overridinggetAnimeDetails, make sure to pass it astrue.SAnime.genreis a string containing list of all genres separated with", ".SAnime.statusis an "enum" value. Refer to the values in theSAnimecompanion object.- During a backup, only
urlandtitleare stored. To restore the rest of the anime data, the app callsgetAnimeDetails, so all fields should be (re)filled in if possible. - If a
SAnimeis cached,getAnimeDetailswill be only called when the user does a manual update (Swipe-to-Refresh).
getEpisodeListis called to display the episode list.- The list should be sorted descending by the source order.
getAnimeUrlis called when the user taps "Open in WebView".- If the source uses an API to fetch the data, consider overriding this method to return the anime absolute URL in the website instead.
- It defaults to the URL provided to the request in
animeDetailsRequest.
Episode
SEpisode.date_uploadis the UNIX Epoch time expressed in milliseconds.-
If you don't pass
SEpisode.date_uploadand leave it zero, the app will use the default date instead, but it's recommended to always fill it if it's available. -
To get the time in milliseconds from a date string, you can use a
SimpleDateFormatlike in the example below.import keiyoushi.utils.tryParse episode.date_upload = dateFormat.tryParse(dateStr) private val dateFormat by lazy { SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH) }Make sure you make the
SimpleDateFormata class constant or variable so it doesn't get recreated for every episode. If you need to parse or format dates in anime description, create another instance sinceSimpleDateFormatis not thread-safe. -
If the parsing has any problems, make sure to return
0Lso the app will use the default date instead. -
The app will overwrite dates of existing old episodes UNLESS
0Lis returned. -
If the source only provides the anime's updated date, assign it to the latest episode only.
-
getEpisodeUrlis called when the user taps "Open in WebView" in the player.- If the source uses an API to fetch the data, consider overriding this method to return the episode absolute URL in the website instead.
- It defaults to the URL provided to the request in
videoListRequest.
Episode Videos
- When user opens an episode,
getVideoList(orvideoListParse) will be called and it will return a list ofVideos. - Each
Videorepresents a playable stream (or quality option) for the episode. The constructor isVideo(url, quality, videoUrl, headers). - The
Video.urlandVideo.videoUrlattributes should be set as absolute URLs when possible. - Return videos already sorted by quality or server preference when the source provides that order.
- If you need to pass additional data to a custom extractor, it is recommended to pass it as a URL
fragment (e.g.
url + "#data"). OkHttp does not send fragments to the server, so there is no need to strip it out afterwards.
Misc notes
- Use
asJsoup(): Instead of manually reading the response body and parsing it with Jsoup (Jsoup.parse(response.body.string())), use the app's built-in extension function:response.asJsoup()(requireseu.kanade.tachiyomi.util.asJsoup). - Jsoup
.text()is already trimmed: Callingelement.text().trim()is redundant because Jsoup automatically normalizes and trims whitespace. Just useelement.text(). - Omit default
joinToStringseparator: The default separator forjoinToStringis already", ". Do not pass it explicitly. UsejoinToString { it.text() }instead ofjoinToString(", ") { it.text() }, andjoinToString()instead ofjoinToString(", "). - Use named parameters for
Video: InstantiateVideoclearly with named parameters. Use theVideo(url, quality, videoUrl, headers)constructor and pass custom headers when the stream requires them. - Throw
UnsupportedOperationException: If a source uses an API and doesn't need to parse HTML for videos in a legacy method, throwUnsupportedOperationException()instead of returning an empty value. Also use this pattern for unused inherited methods. - Cache Regex instances: Define
Regexinstances at the class level or in acompanion objectso they aren't recompiled on every method call. - Do not hardcode
User-Agent: Unless absolutely necessary (e.g., to bypass Cloudflare/protection, or to retrieve a specific mobile layout/different selectors), do not hardcode a specificUser-Agent. Callingsuper.headersBuilder()already provides the app's default User-Agent. - Use
buildString { }: When building descriptions or dynamic strings, use Kotlin'sbuildString { ... }instead of manually instantiating aStringBuilder(). - Media Types:
application/jsonis intrinsically UTF-8. Avoid usingapplication/json; charset=utf-8. Prefer helper functions liketoJsonRequestBody()instead of manually specifying media types (e.g.,"application/json".toMediaType()). - Use
getUrlWithoutDomaincarefully: It can be useful when parsing target source URLs, but note a current issue with spaces-replace them with URL-encoded characters (e.g.,%20). - Anime/episode URLs: Prefer storing just the ID or slug in
SAnime.urlandSEpisode.url. Storing the relative URL withsetUrlWithoutDomain()is also acceptable. Avoid absolute URLs to make future domain migrations easier. - Follow
AnimeHttpSourceworkflow: Stick to the general workflow from this base class when possible; deviating may introduce unnecessary complexity. - Separate custom headers: When adding custom headers to a request (e.g., for AJAX endpoints), avoid building them inline within the
GET()orPOST()call. Instead, assign the modified headers to a separate variable or define them as a class-level property. This improves readability and allows for reuse across multiple requests. - Do not override default
AnimeHttpSourcemethods: Avoid overriding methods likeanimeDetailsRequestorepisodeListRequestif they only replicate the default behavior (GET(baseUrl + anime.url, headers)). Only override them if the source requires a different URL structure or custom headers for those specific requests. - Configurable sources: By implementing
ConfigurableAnimeSource, you can add settings backed bySharedPreferences. - Code organization: For readability, group related methods together in your extension class (e.g., all popular anime methods, then all latest anime methods, then search methods, and so on). A logical ordering like Popular → Latest → Search → Details → Episodes → Videos → Filters → Utilities makes the class easier to navigate and maintain without needing explicit section header comments.
- DTO extensions: Move mapping extensions for DTOs (like
fun MyDto.toSAnime()) into the DTO file itself to keep the main source class clean.
Advanced Extension features
Extension logic and app features
- Mandatory fields: An anime's
titleandurlare mandatory. An episode'snameis also mandatory, though generic values like"Episode"are acceptable for sources that only provide a single episode (e.g., movie sources). Do not provide generic fallbacks like"Untitled","Unknown", or empty strings if the site fails to provide an anime's title or URL, as this breaks downloads and library management. Prefer failing loudly (e.g., throwing an exception or using!!) so broken selectors are detected early. Silent fallbacks or empty values can hide issues and make debugging harder. If a mandatory field is missing, it is better to throw or skip the entry entirely. - Optional fields: For all other fields, prefer safe calls (
?.) and avoid using the non-null assertion (!!). Missing data like thumbnails or descriptions should not crash the entire parsing process. Consider using Kotlin'smapNotNullwhen parsing lists of elements so that if a single item fails, the rest of the list can still be loaded successfully. - Extension
namefield: Do not add a language suffix or other qualifier toname(e.g.,"MySite EN"). The app already groups sources by languages. supportsLatestconvention: If a source only has a latest listing, use the latest listing in place for the popular listing and setsupportsLatest = false.- When to bump
versionId: TheversionIdproperty dictates how the app tracks the source. Only override and bumpversionIdif the source's URL structure fundamentally changes (e.g., old anime URLs no longer work and there is no way to create a redirect). Bumping this forces all users to re-migrate their bookmarks. - Self-hosted sources: If you are adding a source for a self-hosted server (e.g., StashApp, Komga, Suwayomi), make your class implement the
UnmeteredSourceinterface. This tells the app not to apply standard rate-limiting to the user's own local server. - Preference listeners: When implementing
ConfigurableAnimeSource, you do not need to manually save values insidesetOnPreferenceChangeListener. The Android preference framework saves the value toSharedPreferencesautomatically. - Update Strategy: For gallery sources or sources where entries are completed upon upload, set
update_strategy = UpdateStrategy.ONLY_FETCH_ONCEto prevent unnecessary update checks. - Preserving Source ID: If you change a source's
nameorlang, its auto-generatedidwill change, which disconnects existing users' libraries. To prevent this, overrideidwith the old value (found in the repository'sindex.json). - Avoid hardcoded host checks: When checking URLs in deep links or search overrides, avoid hardcoding the host string (e.g.,
queryUrl.host == "site.com"). This breaks if mirrors are added. Prefer checking against the source'sbaseUrldynamically. - Empty Lists vs Exceptions: If
videoListParseorepisodeListParsefinds no items (e.g., a locked or empty episode), returnemptyList()instead of throwing a hardcoded exception. The app will display a properly localized error message to the user. - Avoid excessive comments: Do not add verbose, redundant, or AI-generated comments that explain obvious code. Keep the code clean and self-documenting.
- UrlActivity exceptions: Catch
Throwableinstead ofExceptioninUrlActivityto ensure all potential crashes are handled gracefully.
Configurable Sources and Preferences
- Mirror selection preferences: When implementing a mirror selector, save the index of the mirror instead of the URL string. This allows code updates to change the list of mirrors, and users will automatically reflect those changes.
- Base URL getter: When
baseUrlis configurable via preferences, use a custom getter (e.g.,override val baseUrl: String get() = ...) instead ofby lazy. Usingby lazyrequires the user to restart the app for the domain change to take effect. - Preference migration for base URLs: To handle default URL changes in updates, use the
getPreferencesinline migration block to update the stored preference if the hardcoded default URL changes. - Coerce mirror index: When reading the mirror index from preferences, use
.coerceAtMost(mirrorUrls.size - 1)to preventArrayIndexOutOfBoundsExceptionif mirrors are removed in a code update.
URL intent filter
Extensions can define a URL pattern so that these URLs can be opened in Anikku.
To do this, you need two files:
AndroidManifest.xmlwhich must be placed in the root directory of your extension (Example:src/id/riztranslation/AndroidManifest.xml)UrlActivity.ktwhich should be placed next to your main file. (Example:src/all/nyaatorrent/src/eu/kanade/tachiyomi/animeextension/all/nyaatorrent/NyaaTorrentUrlActivity.kt)
AndroidManifest.xml example :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<activity
android:name=".id.riztranslation.UrlActivity"
android:excludeFromRecents="true"
android:exported="true"
android:theme="@android:style/Theme.NoDisplay">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="riztranslation.pages.dev"
android:pathPattern="/..*"
android:scheme="https" />
<data
android:host="riztranslation.rf.gd"
android:pathPattern="/..*"
android:scheme="https" />
</intent-filter>
</activity>
</application>
</manifest>
The AndroidManifest.xml file will contain an android:name attribute that refers to the path of your UrlActivity.kt file. For example, if the extension is Riztranslation, the android:name will be .id.riztranslation.UrlActivity.
Next, you have the <data android:scheme="https" android:host="host" android:pathPattern="/..*" /> element; you can have it multiple times, which allows you to specify the URL that can be opened in Anikku. You can read more about this in Android's <data> documentation.
Now, as for UrlActivity, you can just use the example below.
Caution
The activity does not support any Kotlin Intrinsics specific methods or calls, and using them will cause crashes in the activity. Consider using Java's equivalent methods instead, such as using
String'sequals()instead of using==.You can use Kotlin Intrinsics in the extension source class, this limitation only applies to the activity classes.
To explain how it works, it will trigger Anikku's ANIMESEARCH action, passing the URL as a query and specifying that it comes from your extension to narrow down the search. Avoid putting any logic in this file; instead, implement it in your extension's class.
class UrlActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intentData = intent?.data?.toString()
if (intentData != null) {
val mainIntent = Intent().apply {
action = "eu.kanade.tachiyomi.ANIMESEARCH"
putExtra("query", intentData)
putExtra("filter", packageName)
}
try {
startActivity(mainIntent)
} catch (e: Throwable) {
Log.e("RiztranslationUrl", e.toString())
}
} else {
Log.e("RiztranslationUrl", "could not parse uri from intent $intent")
}
finish()
exitProcess(0)
}
}
Now all you need to do is adapt the search function (getSearchAnime) in your extension so that, given a URL, it returns a single anime that matches that URL. For example:
if (query.startsWith("https://")) {
val url = query.toHttpUrlOrNull()
if (url != null && url.host == baseUrl.toHttpUrl().host) {
val typeIndex = url.pathSegments.indexOfFirst { it == "detail" || it == "view" }
if (typeIndex != -1 && typeIndex + 1 < url.pathSize) {
val id = url.pathSegments[typeIndex + 1]
return GET("$apiUrl/Book?select=id,judul,cover&type=not.ilike.*novel*&id=eq.$id", apiHeaders)
}
}
}
To test if the URL intent filter is working as expected, you can try opening the website in a browser
and navigating to the endpoint that was added as a filter or clicking a hyperlink. Alternatively,
you can use the adb command below.
adb shell am start -d "<your-link>" -a android.intent.action.VIEW
You can find a complete example of how URLs work in the Riztranslation extension.
Update strategy
In some cases, titles in a source will always have the same episode list (i.e., they are immutable).
These do not need to be included in global app updates. Excluding them saves a lot of network requests
and prevents unnecessary load on the source servers. To change the update strategy of a SAnime,
use the update_strategy field. You can find below a description of the current possible values.
UpdateStrategy.ALWAYS_UPDATE: Titles marked as always update will be included in the library update if they aren't excluded by additional restrictions.UpdateStrategy.ONLY_FETCH_ONCE: Titles marked as only fetch once will be automatically skipped during library updates. Useful for cases where the series is previously known to be finished and have only a single episode, for example.
If not set, it defaults to ALWAYS_UPDATE.
Renaming existing sources
There are some cases where existing sources change their names on the website. To correctly reflect
these changes in the extension, you need to explicitly set the id to the same old value, otherwise
it will get changed by the new name value and users will be forced to migrate back to the source.
To get the current id value before the name change, you can search the source name in the repository JSON file
by looking at the sources attribute of the extension. When you have the id copied, you can
override it in the source:
override val id: Long = <the-id>
Then the class name and the name attribute value can be changed. Also don't forget to update the
extension name and class name in the individual Gradle file.
Important
The package name needs to be the same (even if it has the old name), otherwise users will not receive the extension update when it gets published in the repository.
The id also needs to be explicitly set to the old value if you're changing the lang attribute.
Note
If the source has also changed their theme you can instead just change the
namefield in the source class and in the Gradle file. By doing so a newidwill be generated and users will be forced to migrate.
Multi-source themes
The lib-multisrc directory houses source code that is useful in situations where multiple source
sites use the same site generator tool (usually a CMS) for bootstrapping their website and this makes
them similar enough to prompt code reuse through inheritance/composition; which from now on we will
use the general theme term to refer to.
Themes are provided as libraries within lib-multisrc. You can apply a theme to an extension by specifying the themePkg property in its build.gradle file.
Creating a new theme
To create a new theme, you need to set up a new module inside the lib-multisrc directory. The structure is similar to a regular extension, but it acts as a base library that other extensions can depend on.
Theme directory structure
$ tree lib-multisrc/<theme_name>/
lib-multisrc/<theme_name>/
├── build.gradle.kts
└── src
└── main
└── java
└── eu
└── kanade
└── tachiyomi
└── multisrc
└── <theme_name>
└── <ThemeName>.kt
<theme_name> should be adapted from the CMS/theme name, and can only contain lowercase ASCII letters and digits. Your theme code must be placed in the package eu.kanade.tachiyomi.multisrc.<theme_name>.
Theme build.gradle.kts
Make sure that your new theme's build.gradle.kts file follows this structure:
plugins {
alias(kei.plugins.multisrc)
}
baseVersionCode = 1
| Field | Description |
|---|---|
baseVersionCode |
The base version code for the theme. This must be a positive integer and incremented whenever a change is made to the theme's implementation that affects the extensions. |
Theme main class
The main class of the theme (e.g., <ThemeName>.kt) contains the default implementation for the source sites. It should be declared as an abstract class extending AnimeHttpSource, allowing individual extensions to inherit and override its properties and methods.
package eu.kanade.tachiyomi.multisrc.<theme_name>
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
abstract class <ThemeName>(
override val name: String,
override val baseUrl: String,
override val lang: String,
) : AnimeHttpSource() {
// Theme default implementation...
}
Using a Theme
To use a theme in your extension, follow the regular extension creation steps and add the themePkg property to your build.gradle:
ext {
extName = '<My source name>'
extClass = '.<MySourceName>'
themePkg = '<theme_name>'
overrideVersionCode = 1
isNsfw = true
}
apply plugin: "kei.plugins.extension.legacy"
Notice that instead of extVersionCode, extensions using a theme must use overrideVersionCode. The final extension version code (extVersionCode) is automatically calculated during the build process as theme.baseVersionCode + ext.overrideVersionCode.
Because themes are provided as libraries, your extension's main class will directly inherit from the theme's base class.
Any site-specific overrides, custom functions, or custom icons are implemented directly in your extension's module (src/<lang>/<mysourcename>) by overriding the inherited theme properties and functions.
Running
For local development, use the following run configuration to launch the app directly into the Browse panel.
Copy the following into Launch Flags for the Debug build of Anikku:
Anikku:
-W -S -n app.anikku.dev/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES
Aniyomi:
-W -S -n xyz.jmir.tachiyomi.mi.debug/eu.kanade.tachiyomi.ui.main.MainActivity -a eu.kanade.tachiyomi.SHOW_CATALOGUES
For other builds, replace app.anikku.dev with the corresponding package IDs:
- Release build:
app.anikkuorxyz.jmir.tachiyomi.mi - Preview build:
app.anikku.preview
If the extension builds and runs successfully, then the code changes should be ready to test in your local app.
Important
If you're deploying to Android 11 or higher, enable the
Always install with package manageroption in the run configurations. Without this option enabled, you might face issues such as Android Studio running an older version of the extension without the modifications you might have done.
Debugging
Android Debugger
Note
It is generally recommended to rely on logging instead of the Android Debugger. Using standard logs (like
Log.dor viewing OkHttp logs) is typically much faster, easier to set up, and is more than sufficient for debugging web scraping logic.
Important
If you didn't build the main app from source with debug enabled and are using a release/beta APK, you need a rooted device. If you are using an emulator instead, make sure you choose a profile without Google Play.
Follow the steps above for building and running locally if you haven't already. Debugging will not work if you did not follow the steps above.
You can leverage the Android Debugger to add breakpoints and step through your extension while debugging.
You cannot simply use Android Studio's Debug 'module.name' -> this will most likely result in an
error while launching.
Instead, once you've built and installed your extension on the target device, use
Attach Debugger to Android Process to start debugging the app.
Inside the Attach Debugger to Android Process window, once the app is running on your device and Show all processes is checked, you should be able to select app.anikku.dev or xyz.jmir.tachiyomi.mi.debug and press OK.
Logs
You can also elect to simply rely on logs printed from your extension, which
show up in the Logcat panel of Android Studio.
Inspecting network calls
One of the easiest ways to inspect network issues (such as HTTP errors 404, 429, no episode found, etc.)
is to use the Logcat panel of Android Studio
and filter by the OkHttpClient tag.
To be able to check the calls made by OkHttp, you need to enable verbose logging in the app, which is not enabled by default. To enable it, go to More -> Settings -> Advanced -> Verbose logging. After enabling it, don't forget to restart the app.
Inspecting the Logcat allows you to get a good look at the call flow and is more than enough in most
cases where issues occur. However, alternatively, you can also use an external tool like mitm-proxy.
For that, refer to the subsequent sections.
On newer Android Studio versions, you can use its built-in Network Inspector inside the App Inspection tool window. This feature provides a nice GUI to inspect the requests made in the app.
To use it, follow the official documentation and select the app's package name in the process list.
Using external network inspecting tools
If you want a deeper look into the network flow, such as inspecting the request and response bodies
you can use an external tool like mitm-proxy.
Setup your proxy server
We are going to use mitm-proxy but you can replace it with any other Web Debugger (i.e. Charles, Burp Suite, Fiddler etc). To install and execute, follow the commands below.
# Install the tool.
$ sudo pip3 install mitmproxy
# Execute the web interface and the proxy.
$ mitmweb
Alternatively, you can also use the Docker image:
$ docker run --rm -it -p 8080:8080 \
-p 127.0.0.1:8081:8081 \
--web-host 0.0.0.0 \
mitmproxy/mitmproxy mitmweb
After installing and running, open your browser and navigate to http://127.0.0.1:8081.
OkHttp proxy setup
Since most of the anime sources are going to use HTTPS, we need to disable SSL verification in order to use the web debugger. For that, add this code to inside your source class:
package eu.kanade.tachiyomi.animeextension.en.mysource
import android.annotation.SuppressLint
import eu.kanade.tachiyomi.animesource.online.AnimeHttpSource
import okhttp3.OkHttpClient
import java.net.InetSocketAddress
import java.net.Proxy
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
class MySource : AnimeHttpSource() {
private fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
val naiveTrustManager = @SuppressLint("CustomX509TrustManager")
object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
}
val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
init(null, trustAllCerts, SecureRandom())
}.socketFactory
sslSocketFactory(insecureSocketFactory, naiveTrustManager)
hostnameVerifier { _, _ -> true }
return this
}
override val client: OkHttpClient = network.client.newBuilder()
.ignoreAllSSLErrors()
.proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("10.0.2.2", 8080)))
.build()
}
Note: 10.0.2.2 is usually the address of your loopback interface in the android emulator. If
the app tells you that it's unable to connect to 10.0.2.2:8080 you will likely need to change it
(the same if you are using hardware device).
If all went well, you should see all requests and responses made by the source in the web interface
of mitmweb.
Building
APKs can be created in Android Studio via Build > Build Bundle(s) / APK(s) > Build APK(s) or
Build > Generate Signed Bundle / APK.
If for some reason you decide to build the APK from the command line, you can use the following command (because you're doing things differently than expected, I assume you have some knowledge of gradlew and your OS):
// For a single apk, use this command
$ ./gradlew src:<lang>:<source>:assembleDebug
Submitting the changes
When you feel confident about your changes, submit a new Pull Request so your code can be reviewed
and merged if it's approved. We encourage following a GitHub Standard Fork & Pull Request Workflow
and following the good practices of the workflow, such as not committing directly to master: always
create a new branch for your changes.
If you are more comfortable about using Git GUI-based tools, you can refer to this guide about the Git integration inside Android Studio, specifically the "How to Contribute to an to Existing Git Repository in Android Studio" section of the guide.
Important
Make sure you have generated the extension icon using the linked Icon Generator tool in the Tools section. The icon must follow the pattern adopted by all other extensions: a square with rounded corners. Make sure to remove the generated
web_hi_res_512.png.
Please do test your changes by compiling it through Android Studio before submitting it. Obvious untested PRs will not be merged, such as ones created with the GitHub web interface. Also make sure to follow the PR checklist available in the PR body field when creating a new PR. As a reference, you can find it below.
Pull Request checklist
- Updated
extVersionCodevalue inbuild.gradlefor individual extensions - Updated
overrideVersionCodeorbaseVersionCodeas needed for all multisrc extensions - Referenced all related issues in the PR body (e.g. "Closes #xyz")
- Added the
isNsfw = trueflag inbuild.gradlewhen appropriate - Have not changed source names
- Have explicitly kept the
idif a source's name or language were changed - Have tested the modifications by compiling and running the extension through Android Studio
- Have removed
web_hi_res_512.pngwhen adding a new extension - This PR is AI-assisted, I have reviewed the changes manually and confirmed they are not slop

