Implementation chapter · Coverage index
Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.
Pinned baseline for comparison. Use the reviewed listings in the implementation chapters and the reviewed source archive when reconstructing the app. See the architecture review for changes.
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerAdapter.android.kt
- Source · implementation · 42 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: internal actual fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter {
20: private class AndroidExtensionServerAdapter(
27: override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig =
30: override suspend fun install(
38: override suspend fun detect(path: String): InstalledExtensionServerBundle = throw ExtensionServerException(
Exact file bytes / download · SHA-256 a552d394c421341e504f0de2f4f4a8698087f3ff27e7a25aabd8e00c95b48a1a.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.AndroidAppContext
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.ext.AndroidExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServerConfig
import eu.friedcutlet.yokan.ext.ExtensionServerException
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
internal actual fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter {
val context = AndroidAppContext.appContext
?: throw IllegalStateException("Android application context is not initialized")
return AndroidExtensionServerAdapter(AndroidExtensionServer(context, mihonBridgePreferencesPrefix(profileId)))
}
internal actual val defaultMihonProxyUrl: String = "http://127.0.0.1:8080"
private class AndroidExtensionServerAdapter(
override val server: ExtensionServer,
) : PlatformExtensionServerAdapter {
override val mode = ExtensionServerRuntimeMode.AndroidApkBridge
override val requiresBundleDownload = false
override val installationAvailable = false
override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig =
ExtensionServerConfig(port)
override suspend fun install(
release: ExtensionServerRelease,
onProgress: (Long, Long) -> Unit,
): InstalledExtensionServerBundle = throw ExtensionServerException(
"INSTALL_NOT_REQUIRED",
"Android runs the APK bridge in-process and needs no server bundle",
)
override suspend fun detect(path: String): InstalledExtensionServerBundle = throw ExtensionServerException(
"IMPORT_NOT_REQUIRED",
"Android runs the APK bridge in-process and does not import a server bundle",
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/CatalogEntryMappers.kt
- Source · implementation · 387 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: internal fun catalogEntrySources(repoUrl: String, entry: JsonObject): List<DbSource> =
28: internal fun mihonProtobufSources(repoUrl: String, extensions: List<PbExtension>): List<DbSource> =
67: internal fun stableHashId(value: String): Long {
76: internal fun JsonObject.array(key: String): JsonArray? = this[key] as? JsonArray
78: internal fun repositoryDirectoryUrl(repoUrl: String): String {
88: private fun mihonSources(repoUrl: String, entry: JsonObject): List<DbSource> {
125: private fun lnReaderSource(entry: JsonObject): DbSource {
147: private fun genericSource(repoUrl: String, entry: JsonObject): DbSource? {
193: private fun JsonObject.isMihonEntry(): Boolean {
209: private fun JsonObject.isLnReaderEntry(): Boolean =
218: private fun JsonObject.isAidokuEntry(): Boolean {
225: private fun aidokuSources(repoUrl: String, entry: JsonObject): List<DbSource> {
265: private fun JsonObject.versionString(): String =
268: private fun JsonObject.itemTypeValue(): DbItemType? {
279: private fun JsonObject.sourceCodeLanguageValue(): DbSourceCodeLanguage {
296: private fun JsonObject.isUnsupportedDartSource(): Boolean {
301: private fun JsonObject.toRepo(): DbRepo =
309: private fun repoFromUrl(repoUrl: String): DbRepo {
318: private fun JsonObject.booleanValue(key: String): Boolean? {
326: private fun JsonObject.longValue(key: String): Long? {
331: private fun JsonObject.obj(key: String): JsonObject? = this[key] as? JsonObject
333: private fun resolveRepositoryUrl(repoUrl: String, value: String?): String {
364: private fun normalizeUrlPath(path: String): String {
377: private fun normalizeLnReaderLanguage(lang: String?): String = when (lang) {
Exact file bytes / download · SHA-256 f7570f908a7960c436dddbad433e33686e0a56e56ea32231aaf73a12c36d438a.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.extensions.js.string
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.longOrNull
private val AbsoluteUriPattern = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")
/** Maps one JSON catalog entry (Mihon, LNReader, Aidoku or Mangayomi format) to its sources. */
internal fun catalogEntrySources(repoUrl: String, entry: JsonObject): List<DbSource> =
when {
entry.isMihonEntry() -> mihonSources(repoUrl, entry)
entry.isLnReaderEntry() -> listOf(lnReaderSource(entry))
entry.isAidokuEntry() -> aidokuSources(repoUrl, entry)
else -> listOfNotNull(genericSource(repoUrl, entry))
}
/** Maps the extensions of a Mihon protobuf repository index to their sources. */
internal fun mihonProtobufSources(repoUrl: String, extensions: List<PbExtension>): List<DbSource> =
extensions.flatMap { extension ->
val version = extension.versionName.ifBlank {
extension.versionCode?.toString().orEmpty().ifBlank { "0.0.1" }
}
val fallbackIcon = extension.packageName.takeIf { it.isNotBlank() }
?.let { resolveRepositoryUrl(repoUrl, "icon/$it.png") }
.orEmpty()
extension.sources.map { source ->
val payload = extension.resources.apkUrl.takeIf { it.isNotBlank() }
?: extension.resources.jarUrl
val icon = extension.resources.iconUrl.takeIf { it.isNotBlank() } ?: fallbackIcon
DbSource(
id = source.id ?: stableHashId("mihon-${source.name}-${source.language}"),
name = source.name.ifBlank { extension.name },
baseUrl = source.homeUrl,
lang = source.language,
isActive = true,
isAdded = false,
isPinned = false,
isNsfw = extension.contentWarning == 3,
sourceCodeUrl = resolveRepositoryUrl(repoUrl, payload),
additionalParams = source.id?.toString()?.let {
JsonObject(mapOf("sourceId" to JsonPrimitive(it))).toString()
}.orEmpty(),
iconUrl = resolveRepositoryUrl(repoUrl, icon),
version = version,
versionLast = version,
itemType = DbItemType.Manga,
isLocal = false,
isObsolete = false,
sourceCodeLanguage = DbSourceCodeLanguage.Mihon,
notes = "Requires ApkBridge for installing and running Mihon extensions.",
repo = repoFromUrl(repoUrl),
)
}
}
/** A positive id derived from [value], stable for the same catalog entry. */
internal fun stableHashId(value: String): Long {
val hash = value.hashCode().toLong()
return when {
hash < 0 -> -hash
hash > 0 -> hash
else -> 1L
}
}
internal fun JsonObject.array(key: String): JsonArray? = this[key] as? JsonArray
internal fun repositoryDirectoryUrl(repoUrl: String): String {
val clean = repoUrl.substringBefore('#').substringBefore('?')
val schemeEnd = clean.indexOf("://")
if (schemeEnd < 0) return clean.substringBeforeLast('/', missingDelimiterValue = clean).trimEnd('/') + "/"
val pathStart = clean.indexOf('/', startIndex = schemeEnd + 3)
if (pathStart < 0) return "$clean/"
if (clean.endsWith('/')) return clean
return clean.substringBeforeLast('/') + "/"
}
private fun mihonSources(repoUrl: String, entry: JsonObject): List<DbSource> {
val packageName = entry.string("pkg").orEmpty()
val extensionVersion = entry.versionString()
val itemType = if (packageName.startsWith("eu.kanade.tachiyomi.animeextension")) DbItemType.Anime else DbItemType.Manga
val apkName = entry.string("apk").orEmpty()
val iconUrl = packageName.takeIf { it.isNotBlank() }?.let { resolveRepositoryUrl(repoUrl, "icon/$it.png") }.orEmpty()
val sourceCodeUrl = apkName.takeIf { it.isNotBlank() }?.let { resolveRepositoryUrl(repoUrl, "apk/$it") }.orEmpty()
return entry.array("sources").orEmpty()
.mapNotNull { it as? JsonObject }
.map { source ->
DbSource(
id = stableHashId("mihon-${source.string("id") ?: source.string("name").orEmpty()}"),
name = source.string("name") ?: entry.string("name").orEmpty(),
baseUrl = source.string("baseUrl").orEmpty(),
lang = source.string("lang") ?: entry.string("lang").orEmpty(),
isActive = true,
isAdded = false,
isPinned = false,
isNsfw = entry.booleanValue("nsfw") ?: false,
sourceCodeUrl = sourceCodeUrl,
additionalParams = source.string("id")
?.let { JsonObject(mapOf("sourceId" to JsonPrimitive(it))).toString() }
.orEmpty(),
iconUrl = iconUrl,
version = extensionVersion,
versionLast = extensionVersion,
itemType = itemType,
appMinVerReq = entry.string("appMinVerReq", "minAppVersion", "minExtVersion").orEmpty(),
isLocal = false,
isObsolete = false,
sourceCodeLanguage = DbSourceCodeLanguage.Mihon,
notes = "Requires ApkBridge for installing and running Mihon extensions.",
repo = repoFromUrl(repoUrl),
)
}
}
private fun lnReaderSource(entry: JsonObject): DbSource {
val lang = normalizeLnReaderLanguage(entry.string("lang"))
val version = entry.versionString()
return DbSource(
id = stableHashId("lnreader-plugin-\"${entry.string("name").orEmpty()}\".\"$lang\""),
name = entry.string("name").orEmpty(),
baseUrl = entry.string("site").orEmpty(),
lang = lang,
isActive = true,
isAdded = false,
isPinned = false,
isNsfw = false,
sourceCodeUrl = entry.string("url").orEmpty(),
iconUrl = entry.string("iconUrl").orEmpty(),
version = version,
versionLast = version,
itemType = DbItemType.Novel,
sourceCodeLanguage = DbSourceCodeLanguage.LnReader,
notes = "Performance may be limited by the shared JavaScript runtime.",
)
}
private fun genericSource(repoUrl: String, entry: JsonObject): DbSource? {
val name = entry.string("name") ?: return null
val itemType = entry.itemTypeValue() ?: DbItemType.Manga
val version = entry.versionString()
val unsupportedDartSource = entry.isUnsupportedDartSource()
val sourceCodeUrl = resolveRepositoryUrl(repoUrl, entry.string("sourceCodeUrl"))
val notes = entry.string("notes").orEmpty().ifBlank {
if (unsupportedDartSource) "Dart source metadata imported; execution is unsupported in the KMP port." else ""
}
return DbSource(
id = entry.longValue("id") ?: stableHashId("$sourceCodeUrl-$name-${entry.string("lang").orEmpty()}"),
name = name,
baseUrl = entry.string("baseUrl").orEmpty(),
lang = entry.string("lang").orEmpty(),
isActive = if (unsupportedDartSource) false else entry.booleanValue("isActive") ?: true,
isAdded = entry.booleanValue("isAdded") ?: false,
isPinned = entry.booleanValue("isPinned") ?: false,
isNsfw = entry.booleanValue("isNsfw") ?: false,
sourceCode = entry.string("sourceCode").orEmpty(),
sourceCodeUrl = sourceCodeUrl,
typeSource = entry.string("typeSource").orEmpty(),
iconUrl = resolveRepositoryUrl(repoUrl, entry.string("iconUrl")),
isFullData = entry.booleanValue("isFullData") ?: false,
hasCloudflare = entry.booleanValue("hasCloudflare") ?: false,
lastUsed = entry.booleanValue("lastUsed") ?: false,
dateFormat = entry.string("dateFormat").orEmpty(),
dateFormatLocale = entry.string("dateFormatLocale").orEmpty(),
apiUrl = entry.string("apiUrl").orEmpty(),
version = version,
versionLast = entry.string("versionLast") ?: version,
headers = entry.string("headers").orEmpty(),
supportLatest = entry.booleanValue("supportLatest"),
filterList = entry.string("filterList"),
preferenceList = entry.string("preferenceList"),
itemType = itemType,
appMinVerReq = entry.string("appMinVerReq").orEmpty(),
additionalParams = entry.string("additionalParams").orEmpty(),
isLocal = entry.booleanValue("isLocal") ?: false,
isObsolete = entry.booleanValue("isObsolete") ?: false,
sourceCodeLanguage = entry.sourceCodeLanguageValue(),
notes = notes,
repo = entry.obj("repo")?.toRepo() ?: repoFromUrl(repoUrl),
updatedAt = entry.longValue("updatedAt") ?: 0L,
)
}
private fun JsonObject.isMihonEntry(): Boolean {
// Explicit `sourceCodeLanguage` declaration overrides shape detection.
// Mangayomi-format catalogs sometimes ship JavaScript entries that coincidentally carry
// `pkg`/`apk` fields left over from Mihon metadata. Without this check those entries get
// classified as Mihon and every call is incorrectly routed through ApkBridge.
val declared = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull?.lowercase()
if (declared != null && declared !in setOf("2", "mihon")) return false
return string("name") != null &&
string("pkg") != null &&
string("version", "code") != null &&
string("lang") != null &&
this["nsfw"] != null &&
array("sources") != null &&
string("apk") != null
}
private fun JsonObject.isLnReaderEntry(): Boolean =
string("id") != null &&
string("name") != null &&
string("site") != null &&
string("lang") != null &&
string("version") != null &&
string("url") != null &&
string("iconUrl") != null
private fun JsonObject.isAidokuEntry(): Boolean {
val declared = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull?.lowercase()
if (declared in setOf("4", "aidoku")) return true
val file = string("file", "downloadURL", "downloadUrl", "sourceCodeUrl").orEmpty().lowercase()
return file.endsWith(".aidx") || file.endsWith(".aix")
}
private fun aidokuSources(repoUrl: String, entry: JsonObject): List<DbSource> {
val id = entry.string("id") ?: entry.string("name").orEmpty()
val name = entry.string("name") ?: id
val rawDownload = entry.string("downloadURL", "downloadUrl", "file", "sourceCodeUrl").orEmpty()
val downloadUrl = if (rawDownload.isNotBlank()) resolveRepositoryUrl(repoUrl, rawDownload) else ""
val rawIcon = entry.string("iconURL", "iconUrl", "icon").orEmpty()
val iconUrl = if (rawIcon.isNotBlank()) {
resolveRepositoryUrl(repoUrl, rawIcon)
} else if (id.isNotBlank()) {
resolveRepositoryUrl(repoUrl, "icons/$id.png")
} else ""
val langs = entry.array("languages")?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
?: listOf(entry.string("lang") ?: "all")
val rating = (entry["contentRating"] as? JsonPrimitive)?.intOrNull ?: if (entry.booleanValue("nsfw") == true) 2 else 0
val isNsfw = rating >= 2
val baseUrl = entry.string("baseURL", "baseUrl", "url").orEmpty()
val version = entry.string("version") ?: "1.0.0"
return langs.map { lang ->
DbSource(
id = stableHashId("aidoku-$id-$lang"),
name = name,
baseUrl = baseUrl,
lang = lang,
isActive = true,
isAdded = false,
isPinned = false,
isNsfw = isNsfw,
sourceCodeUrl = downloadUrl,
iconUrl = iconUrl,
version = if (version.contains('.')) version else "$version.0.0",
versionLast = "0.0.1",
itemType = DbItemType.Manga,
sourceCodeLanguage = DbSourceCodeLanguage.Aidoku,
notes = "Aidoku WASM extension package",
repo = repoFromUrl(repoUrl),
)
}
}
private fun JsonObject.versionString(): String =
string("version", "versionName", "code", "versionCode").orEmpty().ifBlank { "0.0.1" }
private fun JsonObject.itemTypeValue(): DbItemType? {
val primitive = this["itemType"] as? JsonPrimitive ?: this["isManga"] as? JsonPrimitive
val raw = primitive?.contentOrNull ?: return null
return when (raw.lowercase()) {
"0", "manga", "true" -> DbItemType.Manga
"1", "anime" -> DbItemType.Anime
"2", "novel", "false" -> DbItemType.Novel
else -> null
}
}
private fun JsonObject.sourceCodeLanguageValue(): DbSourceCodeLanguage {
val raw = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull
return when (raw?.lowercase()) {
"2", "mihon" -> DbSourceCodeLanguage.Mihon
"3", "lnreader", "ln_reader", "ln-reader" -> DbSourceCodeLanguage.LnReader
"4", "aidoku" -> DbSourceCodeLanguage.Aidoku
else -> {
val file = string("file", "downloadURL", "downloadUrl", "sourceCodeUrl").orEmpty().lowercase()
if (file.endsWith(".aidx") || file.endsWith(".aix")) {
DbSourceCodeLanguage.Aidoku
} else {
DbSourceCodeLanguage.JavaScript
}
}
}
}
private fun JsonObject.isUnsupportedDartSource(): Boolean {
val raw = (this["sourceCodeLanguage"] as? JsonPrimitive)?.contentOrNull?.lowercase()
return raw == "0" || raw == "dart" || string("sourceCodeUrl").orEmpty().endsWith(".dart")
}
private fun JsonObject.toRepo(): DbRepo =
DbRepo(
name = string("name"),
website = string("website"),
jsonUrl = string("jsonUrl"),
hidden = booleanValue("hidden"),
)
private fun repoFromUrl(repoUrl: String): DbRepo {
val website = repositoryDirectoryUrl(repoUrl).trimEnd('/')
return DbRepo(
name = website.substringAfterLast('/').ifBlank { "Repository" },
website = website,
jsonUrl = repoUrl,
)
}
private fun JsonObject.booleanValue(key: String): Boolean? {
val primitive = this[key] as? JsonPrimitive ?: return null
return primitive.booleanOrNull
?: primitive.intOrNull?.let { it != 0 }
?: primitive.contentOrNull?.toBooleanStrictOrNull()
?: primitive.contentOrNull?.toIntOrNull()?.let { it != 0 }
}
private fun JsonObject.longValue(key: String): Long? {
val primitive = this[key] as? JsonPrimitive ?: return null
return primitive.longOrNull ?: primitive.contentOrNull?.toLongOrNull()
}
private fun JsonObject.obj(key: String): JsonObject? = this[key] as? JsonObject
private fun resolveRepositoryUrl(repoUrl: String, value: String?): String {
val reference = value?.trim().orEmpty()
if (reference.isBlank() || AbsoluteUriPattern.containsMatchIn(reference)) return reference
if (reference.startsWith("//")) {
val scheme = repoUrl.substringBefore("://", missingDelimiterValue = "https")
return "$scheme:$reference"
}
val suffixIndex = listOf(reference.indexOf('?'), reference.indexOf('#'))
.filter { it >= 0 }
.minOrNull()
?: reference.length
val referencePath = reference.substring(0, suffixIndex)
val suffix = reference.substring(suffixIndex)
val cleanBase = repoUrl.substringBefore('#').substringBefore('?')
if (referencePath.isEmpty()) return "$cleanBase$suffix"
val schemeEnd = cleanBase.indexOf("://")
if (schemeEnd < 0) return reference
val pathStart = cleanBase.indexOf('/', startIndex = schemeEnd + 3)
val origin = if (pathStart >= 0) cleanBase.substring(0, pathStart) else cleanBase
val basePath = if (pathStart >= 0) cleanBase.substring(pathStart) else "/"
val combinedPath = if (referencePath.startsWith('/')) {
referencePath
} else {
val directory = if (basePath.endsWith('/')) basePath else basePath.substringBeforeLast('/') + "/"
directory + referencePath
}
return origin + normalizeUrlPath(combinedPath) + suffix
}
private fun normalizeUrlPath(path: String): String {
val segments = mutableListOf<String>()
path.split('/').forEach { segment ->
when (segment) {
"", "." -> Unit
".." -> if (segments.isNotEmpty()) segments.removeAt(segments.lastIndex)
else -> segments += segment
}
}
val trailingSlash = path.endsWith('/') && segments.isNotEmpty()
return "/" + segments.joinToString("/") + if (trailingSlash) "/" else ""
}
private fun normalizeLnReaderLanguage(lang: String?): String = when (lang) {
"English" -> "en"
"Bahasa Indonesia" -> "id"
"Polski" -> "pl"
"Russian" -> "ru"
"Spanish" -> "es"
"Thai" -> "th"
"Turkish" -> "tr"
"Vietnamese" -> "vi"
else -> lang?.takeIf { it.length in 2..3 } ?: "all"
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ChapterPageResolver.kt
- Source · implementation · 134 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
22: class ChapterPageResolver(
33: suspend fun pages(chapter: DbChapter, sourceId: Long?, forceRefresh: Boolean = false): List<DbPageUrl> =
40: suspend fun pages(
49: fun savedPages(chapterId: Long, sourceId: Long?): List<DbPageUrl> {
55: fun invalidate(chapterId: Long) = database.removePageCache(listOf(chapterId))
58: fun invalidateSource(sourceId: Long) {
69: private suspend fun pages(
78: fun ensureCurrent() {
114: internal fun DbChapterPageUrls.isFresh(sourceId: Long?, sourceVersion: String?, now: Long): Boolean {
120: internal fun mergeSourcePageHeaders(
125: fun append(headers: Map<String, String>) {
Exact file bytes / download · SHA-256 9bd4b9f85258eab50d354d87add29132b833d0512f396ce963a3f34d6194cbda.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterPageUrls
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
/** How long a saved page list is served without asking the source again. */
// ponytail: one TTL for every source; make it per-source if a CDN signs page URLs for less.
const val PAGE_LIST_TTL_MS: Long = 12 * 60 * 60 * 1000L
/**
* Resolves a source chapter's page URLs for the reader and downloads: the saved list while it is
* fresh, otherwise the extension's, saved back. Local-archive chapters never come here; their
* callers list the files themselves.
*/
class ChapterPageResolver(
private val repository: YokanRepository,
private val database: YokanDatabase,
private val runtimeFactory: ExtensionRuntimeFactory,
private val clock: () -> Long = ::nowMillis,
) {
/**
* Saved list when it is still fresh (fetched within [PAGE_LIST_TTL_MS] by the same source version),
* otherwise fetched from the extension with the source's headers merged in and saved back.
* [forceRefresh] skips the saved list. Throws on fetch failure (callers wrap with catchingNonCancellation).
*/
suspend fun pages(chapter: DbChapter, sourceId: Long?, forceRefresh: Boolean = false): List<DbPageUrl> =
pages(chapter.id, chapter.url, sourceId, forceRefresh, onFallback = null)
/**
* Reader overload of [pages]. With [onFallback] a failing runtime is reported and the offline
* [DatabaseFallbackRuntimeService] answers instead, as in [withSourceRuntime]; its answer is never saved.
*/
suspend fun pages(
chapter: Chapter,
sourceId: Long?,
forceRefresh: Boolean = false,
onFallback: ((Throwable) -> Unit)? = null,
ensureRequestCurrent: () -> Unit = {},
): List<DbPageUrl> = pages(chapter.id, chapter.url, sourceId, forceRefresh, onFallback, ensureRequestCurrent)
/** The saved list of [chapterId] when it is fresh for [sourceId]'s installed version, else empty. */
fun savedPages(chapterId: Long, sourceId: Long?): List<DbPageUrl> {
val saved = database.pageCache(chapterId).firstOrNull() ?: return emptyList()
val version = sourceId?.let(database::source)?.version
return if (saved.isFresh(sourceId, version, clock())) repository.pageUrls(chapterId) else emptyList()
}
fun invalidate(chapterId: Long) = database.removePageCache(listOf(chapterId))
/** Drops every saved list of [sourceId]'s chapters, e.g. after the extension was updated or removed. */
fun invalidateSource(sourceId: Long) {
// Lists saved before they recorded their source are matched through their title.
val titleIds = database.mangas().filter { it.sourceId == sourceId }.mapTo(HashSet()) { it.id }
val chapterIds = database.pageCache().mapNotNull { saved ->
saved.chapterId?.takeIf { id ->
saved.sourceId == sourceId || (saved.sourceId == null && database.chapter(id)?.mangaId in titleIds)
}
}
database.removePageCache(chapterIds)
}
private suspend fun pages(
chapterId: Long,
chapterUrl: String,
sourceId: Long?,
forceRefresh: Boolean,
onFallback: ((Throwable) -> Unit)?,
ensureRequestCurrent: () -> Unit = {},
): List<DbPageUrl> {
val callContext = currentCoroutineContext()
fun ensureCurrent() {
callContext.ensureActive()
ensureRequestCurrent()
}
ensureCurrent()
if (!forceRefresh) savedPages(chapterId, sourceId).takeIf { it.isNotEmpty() }?.let {
ensureCurrent()
return it
}
val id = sourceId ?: error("Source is unavailable")
var live = true
val pages = runtimeFactory.withSourceRuntime(database, id, onFallback?.let { report ->
{ failure -> ensureCurrent(); report(failure) }
}) { runtime ->
ensureCurrent()
live = runtime !is DatabaseFallbackRuntimeService
val headers = runtime.headers()
ensureCurrent()
val urls = runtime.pageList(chapterUrl)
ensureCurrent()
mergeSourcePageHeaders(headers, urls)
}
ensureCurrent()
if (live && pages.isNotEmpty()) {
database.batch {
ensureCurrent()
if (database.chapter(chapterId) != null) {
repository.cachePageUrls(chapterId, chapterUrl, pages, database.source(id), fetchedAt = clock())
}
}
}
return pages
}
}
/** Fresh = fetched less than [PAGE_LIST_TTL_MS] before [now] by [sourceVersion] of [sourceId]; lists from before timestamps are stale. */
internal fun DbChapterPageUrls.isFresh(sourceId: Long?, sourceVersion: String?, now: Long): Boolean {
val fetched = fetchedAt ?: return false
return now - fetched in 0 until PAGE_LIST_TTL_MS && this.sourceId == sourceId && this.sourceVersion == sourceVersion
}
/** Source headers under each page's own; a page header replaces a source header of any case. */
internal fun mergeSourcePageHeaders(
sourceHeaders: Map<String, String>,
pages: List<DbPageUrl>,
): List<DbPageUrl> = pages.map { page ->
val merged = linkedMapOf<String, String>()
fun append(headers: Map<String, String>) {
headers.forEach { (name, value) ->
merged.keys.firstOrNull { it.equals(name, ignoreCase = true) }?.let(merged::remove)
merged[name] = value
}
}
append(sourceHeaders)
append(page.headers.orEmpty())
page.copy(headers = merged.ifEmpty { null })
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/DatabaseFallbackRuntimeService.kt
- Source · implementation · 112 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: class DatabaseFallbackRuntimeService(
19: override suspend fun supportsLatest(): Boolean = source.supportLatest == true
21: override suspend fun headers(): Map<String, String> = mapOf("User-Agent" to database.settings().userAgent)
23: override suspend fun popular(page: Int): SourceListing = listing(page)
25: override suspend fun latest(page: Int): SourceListing = listing(page)
27: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing {
35: override suspend fun detail(url: String): RemoteDetail {
66: override suspend fun pageList(url: String): List<DbPageUrl> {
75: override suspend fun htmlContent(name: String, url: String): String =
78: override suspend fun filterList(): List<SourceFilter> = listOf(
95: override suspend fun sourcePreferences(): List<SourcePreferenceValue> = listOf(
100: private fun listing(page: Int): SourceListing {
Exact file bytes / download · SHA-256 4923b060d810aeb17896f74fbed53fca02908328ac0f85e9961dc56db7543503.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.util.nowMillis
/**
* Offline stand-in used when a source's real runtime fails: serves what the database already
* knows about the source (saved titles, chapters and pages) without running extension code.
* It serves no videos: there is no database-backed video cache, and fabricating a stream would
* hand the episode page URL to the player and hide the extension failure from the UI.
*/
class DatabaseFallbackRuntimeService(
override val source: DbSource,
private val database: YokanDatabase,
) : ExtensionRuntimeService {
override suspend fun supportsLatest(): Boolean = source.supportLatest == true
override suspend fun headers(): Map<String, String> = mapOf("User-Agent" to database.settings().userAgent)
override suspend fun popular(page: Int): SourceListing = listing(page)
override suspend fun latest(page: Int): SourceListing = listing(page)
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing {
val normalized = query.trim().lowercase()
val items = database.mangas(source.itemType)
.filter { normalized.isBlank() || it.name.orEmpty().lowercase().contains(normalized) }
.map { RemoteManga(it.name.orEmpty(), it.link.orEmpty(), it.imageUrl, it.description, initialized = true) }
return SourceListing(items = items, hasNextPage = false)
}
override suspend fun detail(url: String): RemoteDetail {
val candidates = database.mangas(source.itemType).filter { it.link == url }
val manga = candidates.firstOrNull { it.sourceId == source.id }
?: candidates.firstOrNull { it.sourceId == null && it.source == source.name }
val chapters = manga?.let { database.chapters(it.id) }.orEmpty().map {
RemoteChapter(
title = it.name.orEmpty(),
url = it.url,
dateUpload = it.dateUpload,
scanlator = it.scanlator,
)
}
return RemoteDetail(
title = manga?.name ?: url,
url = url,
description = manga?.description.orEmpty(),
author = manga?.author,
artist = manga?.artist,
thumbnailUrl = manga?.imageUrl,
chapters = chapters,
cast = manga?.cast,
seasons = manga?.takeIf { it.fetchType == eu.friedcutlet.yokan.database.DbFetchType.Seasons }?.let { parent ->
database.mangas(source.itemType).filter { it.parentId == parent.id }.map {
RemoteManga(it.name.orEmpty(), it.link.orEmpty(), it.imageUrl, it.description, initialized = true,
seasonNumber = it.seasonNumber, fetchesSeasons = it.fetchType == eu.friedcutlet.yokan.database.DbFetchType.Seasons)
}
},
)
}
// Only a fresh saved list stands in for the source; a stale one would pass expired URLs off as live.
override suspend fun pageList(url: String): List<DbPageUrl> {
val now = nowMillis()
return database.pageCache()
.firstOrNull { (it.urls?.contains(url) == true || it.chapterUrl == url) && it.isFresh(source.id, source.version, now) }
?.urls
?.map { DbPageUrl(it) }
?: listOf(DbPageUrl(url))
}
override suspend fun htmlContent(name: String, url: String): String =
"<html><head><title>$name</title></head><body>$url</body></html>"
override suspend fun filterList(): List<SourceFilter> = listOf(
SourceFilter(
id = "genre",
name = "Genre",
type = "SelectFilter",
kind = SourceFilterKind.SingleSelect,
entries = listOf("Action", "Drama", "Fantasy").map { FilterEntry(it, it) },
),
SourceFilter(
id = "status",
name = "Status",
type = "SelectFilter",
kind = SourceFilterKind.SingleSelect,
entries = listOf("Ongoing", "Completed").map { FilterEntry(it, it) },
),
)
override suspend fun sourcePreferences(): List<SourcePreferenceValue> = listOf(
SourcePreferenceValue("baseUrl", "Base URL", source.baseUrl),
SourcePreferenceValue("lang", "Language", source.lang),
)
private fun listing(page: Int): SourceListing {
val items = database.mangas(source.itemType).map {
RemoteManga(
title = it.name.orEmpty(),
url = it.link.orEmpty(),
thumbnailUrl = it.imageUrl,
description = it.description,
initialized = true,
)
}
return SourceListing(items = items, hasNextPage = page < 2)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionLogger.kt
- Source · implementation · 36 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: object ExtensionLogger {
14: fun log(sourceName: String, message: String) {
23: fun error(sourceName: String, action: String, throwable: Throwable) {
Exact file bytes / download · SHA-256 cd5c51b50c4ae34161e1727eb7e892441ec515976ebc2d94da61478d962378ba.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
/**
* Logger for extension execution. JS `console.log/warn/error` calls flow
* through here via the `log` bridge channel, as do caught extension
* exceptions at the call boundary. Output goes through [LogSink] — stdout
* always, plus the opt-in log file.
*/
object ExtensionLogger {
fun log(sourceName: String, message: String) {
AppLogger.info("[ext $sourceName] $message")
}
/**
* Records that calling [action] on the given source's runtime threw. The
* caller is expected to be inside a `runCatching { ... }.getOrElse { ... }`
* or equivalent fallback — this method only logs, it does not rethrow.
*/
fun error(sourceName: String, action: String, throwable: Throwable) {
val cause = throwable.message.orEmpty()
.lineSequence()
.firstOrNull()
.orEmpty()
.ifBlank { throwable::class.simpleName.orEmpty() }
AppLogger.error("[ext $sourceName] $action failed: $cause")
InAppNotifications.post(
title = "$sourceName error",
message = "$action failed: $cause",
)
throwable.printStackTrace()
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionRuntimeFactory.kt
- Source · implementation · 153 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
32: class DynamicExtensionRuntimeFactory(
48: override fun create(source: DbSource): ExtensionRuntimeService =
74: override suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
86: override fun evict(sourceId: Long) = lock.withLock {
91: override fun clear() = lock.withLock {
96: private fun acquire(source: DbSource): CachedRuntime = lock.withLock {
113: private fun retire(entry: CachedRuntime) {
118: private fun recipeRuntime(source: DbSource): ExtensionRuntimeService {
128: private class CachedRuntime(val runtime: ExtensionRuntimeService) {
140: private class UnavailableRecipeRuntimeService(
143: override suspend fun popular(page: Int) = SourceListing(emptyList(), false)
144: override suspend fun latest(page: Int) = SourceListing(emptyList(), false)
145: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>) = SourceListing(emptyList(), false)
146: override suspend fun detail(url: String) = RemoteDetail("", url)
150: private fun DbSource.isLegacyLnReaderPlugin(): Boolean =
Exact file bytes / download · SHA-256 e6b2af155d1a89e30bee0e924fb60c5f4460c76b488739ab95e2612f959a6ffc.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.extensions.aidoku.AidokuExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptEngine
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptMessageBridge
import eu.friedcutlet.yokan.services.extensions.js.createJavaScriptEngine
import eu.friedcutlet.yokan.services.extensions.lnreader.LnReaderExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.mihon.defaultMihonProxyUrl
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeRuntimeBindings
import eu.friedcutlet.yokan.services.extensions.recipe.RecipeSourceDiscriminator
import eu.friedcutlet.yokan.services.extensions.recipe.parseRecipeSourceReference
import eu.friedcutlet.yokan.services.extensions.recipe.recipeSourceId
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.webview.WebViewService
import eu.friedcutlet.yokan.util.PlatformLock
/**
* Builds runtimes per source language and keeps the most recently used ones alive, so browsing a
* source boots its engine and evaluates its code once instead of on every call. A cached runtime
* is disposed when it is evicted, when its [DbSource] changed (update), on [evict] (uninstall) and
* on [clear] — but never while a [withRuntime] block is still using it.
*/
class DynamicExtensionRuntimeFactory(
private val database: YokanDatabase,
private val http: HttpService,
private val javaScriptEngineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine = ::createJavaScriptEngine,
private val prepareMihonProxy: suspend (String) -> String = { it },
private val recipeRuntime: RecipeRuntimeBindings? = null,
// Host services behind JavaScript extension bridge channels (EPUB parsing, WebView scripts, video extractors).
private val archives: LocalArchiveService? = null,
private val webView: WebViewService? = null,
private val animeExtractors: List<AnimeExtractorService> = emptyList(),
) : ExtensionRuntimeFactory {
private val lock = PlatformLock()
// Insertion order is the LRU order: a hit is removed and re-inserted as the newest entry.
private val cached = LinkedHashMap<Long, CachedRuntime>()
override fun create(source: DbSource): ExtensionRuntimeService =
if (source.typeSource == RecipeSourceDiscriminator) {
recipeRuntime(source)
} else when (source.sourceCodeLanguage) {
DbSourceCodeLanguage.JavaScript -> if (source.isLegacyLnReaderPlugin()) {
LnReaderExtensionRuntimeService(source, http, javaScriptEngineFactory)
} else JavaScriptExtensionRuntimeService(
source = source,
http = http,
database = database,
engineFactory = javaScriptEngineFactory,
archives = archives,
webView = webView,
animeExtractors = animeExtractors,
)
DbSourceCodeLanguage.Mihon -> MihonExtensionRuntimeService(
source = source,
http = http,
androidProxyServer = database.settings().androidProxyServer ?: defaultMihonProxyUrl,
prepareProxy = { prepareMihonProxy(database.settings().androidProxyServer ?: defaultMihonProxyUrl) },
database = database,
)
DbSourceCodeLanguage.LnReader -> LnReaderExtensionRuntimeService(source, http, javaScriptEngineFactory)
DbSourceCodeLanguage.Aidoku -> AidokuExtensionRuntimeService(source, http, database)
}
override suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
val entry = acquire(source)
try {
return block(entry.runtime)
} finally {
lock.withLock {
entry.users -= 1
if (entry.retired && entry.users == 0) entry.runtime.dispose()
}
}
}
override fun evict(sourceId: Long) = lock.withLock {
cached.remove(sourceId)?.let(::retire)
Unit
}
override fun clear() = lock.withLock {
cached.values.forEach(::retire)
cached.clear()
}
private fun acquire(source: DbSource): CachedRuntime = lock.withLock {
val previous = cached.remove(source.id)
val entry = if (previous != null && previous.runtime.source == source) {
previous
} else {
// A changed DbSource means the extension was updated; never reuse the old code.
previous?.let(::retire)
CachedRuntime(create(source))
}
entry.users += 1
cached[source.id] = entry
while (cached.size > RuntimeCacheCapacity) {
cached.remove(cached.keys.first())?.let(::retire)
}
entry
}
private fun retire(entry: CachedRuntime) {
entry.retired = true
if (entry.users == 0) entry.runtime.dispose()
}
private fun recipeRuntime(source: DbSource): ExtensionRuntimeService {
val reference = parseRecipeSourceReference(source.additionalParams)
val runtime = recipeRuntime
return if (reference != null && runtime != null && source.id == recipeSourceId(reference.catalogId, reference.stableId)) {
RecipeExtensionRuntimeService(source, reference.catalogId, reference.stableId, runtime.resolver, runtime.broker, runtime.policy)
} else {
UnavailableRecipeRuntimeService(source)
}
}
private class CachedRuntime(val runtime: ExtensionRuntimeService) {
var users = 0
var retired = false
}
private companion object {
// ponytail: fixed small LRU; make it configurable only if memory profiling asks for it.
const val RuntimeCacheCapacity = 4
}
}
/** A malformed or unbound recipe source has no legacy fallback and performs no I/O. */
private class UnavailableRecipeRuntimeService(
override val source: DbSource,
) : ExtensionRuntimeService {
override suspend fun popular(page: Int) = SourceListing(emptyList(), false)
override suspend fun latest(page: Int) = SourceListing(emptyList(), false)
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>) = SourceListing(emptyList(), false)
override suspend fun detail(url: String) = RemoteDetail("", url)
}
/** Older imports may label CommonJS novel plugins as generic JavaScript. */
private fun DbSource.isLegacyLnReaderPlugin(): Boolean =
itemType == DbItemType.Novel && !sourceCode.contains("DefaultExtension") &&
(sourceCode.contains("exports.default") || sourceCode.contains("module.exports")) &&
sourceCode.contains("popularNovels") && sourceCode.contains("parseNovel")
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionRuntimeService.kt
- Source · implementation · 205 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
14: interface ExtensionRuntimeService {
18: fun dispose() = Unit
19: suspend fun supportsLatest(): Boolean = false
20: suspend fun headers(): Map<String, String> = emptyMap()
21: suspend fun popular(page: Int): SourceListing
22: suspend fun latest(page: Int): SourceListing
23: suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing
24: suspend fun detail(url: String): RemoteDetail
26: suspend fun related(url: String): SourceRelations = SourceRelations(supported = false)
27: suspend fun pageList(url: String): List<DbPageUrl> = emptyList()
28: suspend fun videoList(url: String): List<DbVideo> = emptyList()
29: suspend fun htmlContent(name: String, url: String): String = ""
30: suspend fun cleanHtmlContent(html: String): String = html
31: suspend fun filterList(): List<SourceFilter> = emptyList()
32: suspend fun sourcePreferences(): List<SourcePreferenceValue> = emptyList()
35: interface ExtensionRuntimeFactory {
37: fun create(source: DbSource): ExtensionRuntimeService
43: suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
53: fun evict(sourceId: Long) = Unit
56: fun clear() = Unit
65: suspend fun <T> ExtensionRuntimeFactory.withSourceRuntime(
82: data class SourceListing(
87: data class SourceRelatedGroup(val name: String, val items: List<RemoteManga>)
88: data class SourceRelations(val supported: Boolean, val groups: List<SourceRelatedGroup> = emptyList())
90: data class RemoteManga(
102: data class RemoteChapter(
109: data class RemoteDetail(
140: data class SourceFilter(
157: enum class SourceFilterKind {
172: data class FilterEntry(
182: sealed interface FilterSelection {
183: data class Toggle(val checked: Boolean) : FilterSelection
184: data class Single(val value: String) : FilterSelection
185: data class Multi(val values: Set<String>) : FilterSelection
187: data class TriState(val state: Int) : FilterSelection
188: data class Text(val value: String) : FilterSelection
189: data class Sort(val value: String, val ascending: Boolean) : FilterSelection
192: data class SourcePreferenceValue(
200: data class MihonSourceMetadata(
Exact file bytes / download · SHA-256 73573fb7e31c909aa9d7d8bdf433b9855813f83e2249e22a2b023d125eddd520.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.catchingNonCancellation
/**
* One installed source's extension code. Implementations own their threading: engine work is
* confined to background dispatchers, so every member is safe to call from the main thread.
*/
interface ExtensionRuntimeService {
val source: DbSource
/** Releases the engine; never called while another call on this runtime is still running. */
fun dispose() = Unit
suspend fun supportsLatest(): Boolean = false
suspend fun headers(): Map<String, String> = emptyMap()
suspend fun popular(page: Int): SourceListing
suspend fun latest(page: Int): SourceListing
suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing
suspend fun detail(url: String): RemoteDetail
/** Source-provided relations, kept separate from tracker recommendations. */
suspend fun related(url: String): SourceRelations = SourceRelations(supported = false)
suspend fun pageList(url: String): List<DbPageUrl> = emptyList()
suspend fun videoList(url: String): List<DbVideo> = emptyList()
suspend fun htmlContent(name: String, url: String): String = ""
suspend fun cleanHtmlContent(html: String): String = html
suspend fun filterList(): List<SourceFilter> = emptyList()
suspend fun sourcePreferences(): List<SourcePreferenceValue> = emptyList()
}
interface ExtensionRuntimeFactory {
/** Builds a fresh runtime owned by the caller, who must [ExtensionRuntimeService.dispose] it. */
fun create(source: DbSource): ExtensionRuntimeService
/**
* Runs [block] against a runtime for [source]. This default builds and disposes one per call;
* [DynamicExtensionRuntimeFactory] reuses cached runtimes instead.
*/
suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
val runtime = create(source)
try {
return block(runtime)
} finally {
runtime.dispose()
}
}
/** Drops any runtime kept for [sourceId], e.g. after the source was uninstalled. */
fun evict(sourceId: Long) = Unit
/** Drops every kept runtime. */
fun clear() = Unit
}
/**
* The entry point for running extension code of an installed source: looks [sourceId] up in
* [database] and runs [block] on the factory's runtime for it. With [onFallback], a failing runtime
* is reported to it and [block] is retried against the offline [DatabaseFallbackRuntimeService].
* Cancellation always propagates and is never turned into a fallback.
*/
suspend fun <T> ExtensionRuntimeFactory.withSourceRuntime(
database: YokanDatabase,
sourceId: Long,
onFallback: ((Throwable) -> Unit)? = null,
block: suspend (ExtensionRuntimeService) -> T,
): T {
val source = database.source(sourceId) ?: run {
evict(sourceId)
error("This source is no longer installed")
}
if (onFallback == null) return withRuntime(source, block)
return catchingNonCancellation { withRuntime(source, block) }.getOrElse { error ->
onFallback(error)
block(DatabaseFallbackRuntimeService(source, database))
}
}
data class SourceListing(
val items: List<RemoteManga>,
val hasNextPage: Boolean,
)
data class SourceRelatedGroup(val name: String, val items: List<RemoteManga>)
data class SourceRelations(val supported: Boolean, val groups: List<SourceRelatedGroup> = emptyList())
data class RemoteManga(
val title: String,
val url: String,
val thumbnailUrl: String? = null,
val description: String? = null,
val initialized: Boolean = false,
/** Animetail `season_number` when this entry is a season; null when unknown. */
val seasonNumber: Double? = null,
/** Animetail `FetchType.Seasons`: the entry lists seasons rather than episodes. */
val fetchesSeasons: Boolean = false,
)
data class RemoteChapter(
val title: String,
val url: String,
val dateUpload: String = "",
val scanlator: String = "",
)
data class RemoteDetail(
val title: String,
val url: String,
val description: String = "",
val author: String? = null,
val artist: String? = null,
val thumbnailUrl: String? = null,
val chapters: List<RemoteChapter> = emptyList(),
/** Null preserves saved credits; an empty list explicitly clears them. */
val cast: List<TitleCredit>? = null,
/** Non-null for an Animetail Seasons-type title: its season entries replace the episode list. */
val seasons: List<RemoteManga>? = null,
)
/**
* Schema-side representation of a source filter as returned by `extension.filterList()`.
*
* Filters originating from JavaScript extensions arrive as heterogenous shapes:
* - `CheckBox` — single toggle.
* - `GroupFilter` — header with a `state` array of typed children (commonly
* CheckBoxes), each carrying its own `name` / `value`. Renders as a
* multi-select list.
* - `SelectFilter` / `ListFilter` — single-select from a list of entries.
* - `TriStateFilter` — three-state checkbox (off / include / exclude).
* - `TextFilter` / `EditTextFilter` — free-form text input.
* - `SortFilter` — single-select among sort options.
*
* [kind] is the dominant classification used by the UI. [entries] carries the
* displayable label / outbound value pairs (empty for free-form/text filters).
* Selection state is held outside the schema, in `Map<String, FilterSelection>`.
*/
data class SourceFilter(
val id: String,
val name: String,
val type: String,
val kind: SourceFilterKind = SourceFilterKind.Toggle,
val entries: List<FilterEntry> = emptyList(),
val defaultValue: String? = null,
/** Current runtime selection. Carried on the schema so existing `search(filters)` signatures stay stable. */
val selection: FilterSelection? = null,
/** True only when the extension exposes an ID independent of labels/positions. */
val hasStableId: Boolean = false,
val defaultAscending: Boolean = true,
) {
/** Back-compat shim: callers that only need labels still get the entry names. */
val values: List<String> get() = entries.map { it.label }
}
enum class SourceFilterKind {
/** Single boolean filter (JavaScript `CheckBox`). */
Toggle,
/** One-of selection from [SourceFilter.entries]. */
SingleSelect,
/** Many-of selection from [SourceFilter.entries]. */
MultiSelect,
/** Three-state checkbox: Ignore (default) / Include / Exclude. */
TriState,
/** Free-form text input. */
Text,
/** Sort option and direction, kept together for faithful runtime requests. */
Sort,
}
data class FilterEntry(
val label: String,
val value: String,
)
/**
* Runtime selection for a single [SourceFilter]. Stored in the UI's selection
* map; the runtime layer translates this back into the extension's filter
* payload via `sourceFiltersToJson`.
*/
sealed interface FilterSelection {
data class Toggle(val checked: Boolean) : FilterSelection
data class Single(val value: String) : FilterSelection
data class Multi(val values: Set<String>) : FilterSelection
/** -1 = exclude, 0 = ignore, 1 = include. */
data class TriState(val state: Int) : FilterSelection
data class Text(val value: String) : FilterSelection
data class Sort(val value: String, val ascending: Boolean) : FilterSelection
}
data class SourcePreferenceValue(
val key: String,
val title: String,
val value: String,
val type: String = "editTextPreference",
val values: List<String> = emptyList(),
)
data class MihonSourceMetadata(
val headers: String? = null,
val supportLatest: Boolean? = null,
val filterList: String? = null,
val preferenceList: String? = null,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/GzipDecompress.kt
- Source · implementation · 6 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
6: internal expect suspend fun gzipDecompress(bytes: ByteArray): ByteArray
Exact file bytes / download · SHA-256 48af3c9b868512a634a14e4df2d9ddcdccfc00ffdb1b3bafda8c80492d6dbc77.
Complete file
package eu.friedcutlet.yokan.services.extensions
/** Cap for inflated protobuf repository indexes; actuals fail instead of exceeding it. */
internal const val MaxProtobufDecompressedBytes = 64 * 1024 * 1024
internal expect suspend fun gzipDecompress(bytes: ByteArray): ByteArray
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/LanguageNames.kt
- Source · implementation · 36 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: internal fun languageName(code: String): String = when (code.lowercase().trim()) {
33: internal fun normalizedLanguageCode(code: String): String = when (val normalized = code.trim().lowercase()) {
Exact file bytes / download · SHA-256 af2d20e99c8a687b73ebf9902924f27c95afd126a7242845dbf5f021d692dc0d.
Complete file
package eu.friedcutlet.yokan.services.extensions
/** Display name for an extension language code; unknown codes are shown upper-cased. */
internal fun languageName(code: String): String = when (code.lowercase().trim()) {
"", "all" -> "All languages"
"other" -> "Other"
"en" -> "English"
"ja" -> "Japanese"
"ko" -> "Korean"
"zh", "zh-cn", "zh-hans" -> "Chinese (Simplified)"
"zh-tw", "zh-hant" -> "Chinese (Traditional)"
"fr" -> "French"
"de" -> "German"
"es" -> "Spanish"
"es-419" -> "Spanish (Latin America)"
"pt" -> "Portuguese"
"pt-br" -> "Portuguese (Brazil)"
"ru" -> "Russian"
"it" -> "Italian"
"id" -> "Indonesian"
"ar" -> "Arabic"
"hi" -> "Hindi"
"th" -> "Thai"
"tr" -> "Turkish"
"vi" -> "Vietnamese"
"pl" -> "Polish"
"uk" -> "Ukrainian"
"unknown" -> "Unknown"
else -> code.uppercase()
}
/** Folds blank and "all" into one bucket so language groups never repeat. */
internal fun normalizedLanguageCode(code: String): String = when (val normalized = code.trim().lowercase()) {
"", "all" -> "all"
else -> normalized
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/MihonRepoProtobuf.kt
- Source · implementation · 187 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: internal class ProtobufReader(private val bytes: ByteArray) {
7: fun readExtensions(): List<PbExtension> {
21: private fun readExtensionList(bytes: ByteArray): List<PbExtension> {
36: private fun readExtension(bytes: ByteArray): PbExtension {
61: private fun readResources(bytes: ByteArray): PbResources {
78: private fun readSource(bytes: ByteArray): PbSource {
97: private fun hasNext(): Boolean = position < bytes.size
99: private fun readField(): PbField {
108: private fun readString(): String = readBytes().decodeToString(throwOnInvalidSequence = true)
110: private fun readBytes(): ByteArray {
118: private fun skipField(wireType: Int) {
140: private fun skipBytes(count: Int) {
145: private fun readVarint(): Long {
158: private fun readByte(): Int {
164: private data class PbField(val number: Int, val wireType: Int)
166: internal data class PbExtension(
176: internal data class PbResources(
182: internal data class PbSource(
Exact file bytes / download · SHA-256 cafe24fc1ad4ccabc4af8abae6c76df204e488004b3b49d26202da7a489bc681.
Complete file
package eu.friedcutlet.yokan.services.extensions
/** Minimal reader for the Mihon `index.pb` repository format (the fields Yokan maps, all else skipped). */
internal class ProtobufReader(private val bytes: ByteArray) {
private var position = 0
fun readExtensions(): List<PbExtension> {
val extensions = mutableListOf<PbExtension>()
while (hasNext()) {
val field = readField()
require(field.wireType != 4) { "Unexpected protobuf end group" }
when {
field.number == 101 && field.wireType == 2 ->
extensions += readExtensionList(readBytes())
else -> skipField(field.wireType)
}
}
return extensions
}
private fun readExtensionList(bytes: ByteArray): List<PbExtension> {
val reader = ProtobufReader(bytes)
val extensions = mutableListOf<PbExtension>()
while (reader.hasNext()) {
val field = reader.readField()
if (field.wireType == 4) error("Unexpected protobuf end group")
if (field.number == 1 && field.wireType == 2) {
extensions += reader.readExtension(reader.readBytes())
} else {
reader.skipField(field.wireType)
}
}
return extensions
}
private fun readExtension(bytes: ByteArray): PbExtension {
val reader = ProtobufReader(bytes)
var name = ""
var packageName = ""
var resources = PbResources()
var versionCode: Long? = null
var versionName = ""
var contentWarning = 0
val sources = mutableListOf<PbSource>()
while (reader.hasNext()) {
val field = reader.readField()
when {
field.number == 1 && field.wireType == 2 -> name = reader.readString()
field.number == 2 && field.wireType == 2 -> packageName = reader.readString()
field.number == 3 && field.wireType == 2 -> resources = reader.readResources(reader.readBytes())
field.number == 5 && field.wireType == 0 -> versionCode = reader.readVarint()
field.number == 6 && field.wireType == 2 -> versionName = reader.readString()
field.number == 7 && field.wireType == 0 -> contentWarning = reader.readVarint().toInt()
field.number == 8 && field.wireType == 2 -> sources += reader.readSource(reader.readBytes())
else -> reader.skipField(field.wireType)
}
}
return PbExtension(name, packageName, resources, versionCode, versionName, contentWarning, sources)
}
private fun readResources(bytes: ByteArray): PbResources {
val reader = ProtobufReader(bytes)
var apkUrl = ""
var iconUrl = ""
var jarUrl = ""
while (reader.hasNext()) {
val field = reader.readField()
when {
field.number == 1 && field.wireType == 2 -> apkUrl = reader.readString()
field.number == 2 && field.wireType == 2 -> iconUrl = reader.readString()
field.number == 501 && field.wireType == 2 -> jarUrl = reader.readString()
else -> reader.skipField(field.wireType)
}
}
return PbResources(apkUrl, iconUrl, jarUrl)
}
private fun readSource(bytes: ByteArray): PbSource {
val reader = ProtobufReader(bytes)
var id: Long? = null
var name = ""
var language = ""
var homeUrl = ""
while (reader.hasNext()) {
val field = reader.readField()
when {
field.number == 1 && field.wireType == 0 -> id = reader.readVarint()
field.number == 2 && field.wireType == 2 -> name = reader.readString()
field.number == 3 && field.wireType == 2 -> language = reader.readString()
field.number == 4 && field.wireType == 2 -> homeUrl = reader.readString()
else -> reader.skipField(field.wireType)
}
}
return PbSource(id, name, language, homeUrl)
}
private fun hasNext(): Boolean = position < bytes.size
private fun readField(): PbField {
val tag = readVarint()
require(tag != 0L) { "Invalid protobuf tag" }
val wireType = (tag and 7L).toInt()
val number = tag ushr 3
require(number in 1..0x1fffffff) { "Invalid protobuf field number" }
return PbField(number.toInt(), wireType)
}
private fun readString(): String = readBytes().decodeToString(throwOnInvalidSequence = true)
private fun readBytes(): ByteArray {
val length = readVarint()
require(length >= 0L && length <= bytes.size - position) { "Invalid protobuf length" }
val start = position
position += length.toInt()
return bytes.copyOfRange(start, position)
}
private fun skipField(wireType: Int) {
when (wireType) {
0 -> readVarint()
1 -> skipBytes(8)
2 -> {
val length = readVarint()
require(length >= 0L && length <= bytes.size - position) { "Invalid protobuf length" }
skipBytes(length.toInt())
}
3 -> {
while (hasNext()) {
val field = readField()
if (field.wireType == 4) return
skipField(field.wireType)
}
error("Unterminated protobuf group")
}
5 -> skipBytes(4)
else -> error("Invalid protobuf wire type: $wireType")
}
}
private fun skipBytes(count: Int) {
require(count >= 0 && count <= bytes.size - position) { "Invalid protobuf length" }
position += count
}
private fun readVarint(): Long {
var result = 0L
var shift = 0
repeat(10) {
val byte = readByte()
if (shift == 63) require(byte <= 1) { "Invalid protobuf varint" }
result = result or ((byte and 0x7f).toLong() shl shift)
if ((byte and 0x80) == 0) return result
shift += 7
}
error("Unterminated protobuf varint")
}
private fun readByte(): Int {
require(position < bytes.size) { "Unexpected end of protobuf" }
return bytes[position++].toInt() and 0xff
}
}
private data class PbField(val number: Int, val wireType: Int)
internal data class PbExtension(
val name: String,
val packageName: String,
val resources: PbResources,
val versionCode: Long?,
val versionName: String,
val contentWarning: Int,
val sources: List<PbSource>,
)
internal data class PbResources(
val apkUrl: String = "",
val iconUrl: String = "",
val jarUrl: String = "",
)
internal data class PbSource(
val id: Long?,
val name: String,
val language: String,
val homeUrl: String,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/ProfileReaderContent.kt
- Source · implementation · 222 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
26: class ProfileReaderContent internal constructor(
45: private fun ensureCurrent(callJob: Job) {
52: private suspend fun <T> runOwned(action: suspend (Job) -> T): T {
65: suspend fun pages(source: Source?, chapter: Chapter, forceRefresh: Boolean): List<DbPageUrl> = runOwned { call ->
81: suspend fun headers(source: Source): Map<String, String> = runOwned { call ->
92: suspend fun videos(source: Source?, chapter: Chapter): List<DbVideo> = runOwned { call ->
116: suspend fun novelText(source: Source?, name: String, url: String): String = runOwned { call ->
121: internal suspend fun <T> novelContent(
167: private suspend fun extractNovelText(source: Source?, name: String, url: String, call: Job): String {
179: private data class LocalNovelChapter(val path: String, val href: String?, val html: String)
181: private suspend fun localPages(source: Source?, chapter: Chapter, call: Job): List<DbPageUrl> {
201: internal suspend fun closeAndJoin() {
207: internal class ProfileNovelContent(
213: internal fun directEpisodeVideo(chapter: Chapter): List<DbVideo> {
Exact file bytes / download · SHA-256 8f0c50a3732e900509060259133bd2ec81eb905710a749d2913de564db4b2b0b.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.files.resolveConfiguredLocalArchivePath
import eu.friedcutlet.yokan.services.files.resolveLocalEpisodeVideo
import eu.friedcutlet.yokan.services.runJoined
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.withContext
/** Reader extraction retains one owner, including local files and runtime cleanup. */
class ProfileReaderContent internal constructor(
val profileId: ProfileId,
private val database: YokanDatabase,
private val runtimeFactory: ExtensionRuntimeFactory,
private val chapterPages: ChapterPageResolver,
private val files: LocalFileService,
private val archives: LocalArchiveService,
ownerScope: CoroutineScope,
private val fileDispatcher: CoroutineDispatcher = Dispatchers.Default,
private val isOwnerOpen: () -> Boolean = { true },
private val torrents: eu.friedcutlet.yokan.services.torrent.TorrentStreams? = null,
) {
private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job])
private val job = SupervisorJob(ownerJob)
private val scope = CoroutineScope(ownerScope.coroutineContext + job)
internal val isAvailable: Boolean
get() = ownerJob.isActive && job.isActive && isOwnerOpen()
private fun ensureCurrent(callJob: Job) {
callJob.ensureActive()
ownerJob.ensureActive()
job.ensureActive()
if (!isOwnerOpen()) throw CancellationException("Reader owner is retiring.")
}
private suspend fun <T> runOwned(action: suspend (Job) -> T): T {
val caller = requireNotNull(currentCoroutineContext()[Job])
try {
return scope.runJoined(admit = { ensureCurrent(caller) }) { call ->
ensureCurrent(call)
action(call).also { ensureCurrent(call) }
}
} finally {
// Expired calls must not publish failures to a screen's error/fallback handlers either.
ensureCurrent(caller)
}
}
suspend fun pages(source: Source?, chapter: Chapter, forceRefresh: Boolean): List<DbPageUrl> = runOwned { call ->
val local = withContext(fileDispatcher) { localPages(source, chapter, call) }
ensureCurrent(call)
if (local.isNotEmpty()) local else {
val titleSource = source ?: error("Source is unavailable")
chapterPages.pages(
chapter, titleSource.id, forceRefresh,
onFallback = {
ensureCurrent(call)
ExtensionLogger.error(titleSource.name, "pageList", it)
},
ensureRequestCurrent = { ensureCurrent(call) },
)
}
}
suspend fun headers(source: Source): Map<String, String> = runOwned { call ->
runtimeFactory.withSourceRuntime(database, source.id, onFallback = {
ensureCurrent(call)
ExtensionLogger.error(source.name, "headers", it)
}) { runtime ->
ensureCurrent(call)
runtime.headers().also { ensureCurrent(call) }
}
}
/** An extension failure never turns its episode HTML URL into a playable stream. Torrents play through TorrServer. */
suspend fun videos(source: Source?, chapter: Chapter): List<DbVideo> = runOwned { call ->
if (source == null && eu.friedcutlet.yokan.services.library.TorrentUtils.isTorrentLink(chapter.url)) {
return@runOwned checkNotNull(torrents) { "Torrent streaming is unavailable" }.videos(chapter.url, chapter.name)
.also { ensureCurrent(call) }
}
val local = withContext(fileDispatcher) {
ensureCurrent(call)
chapter.archivePath.ifBlank {
if (source == null && !chapter.url.startsWith("http", true) && !chapter.url.startsWith("//")) chapter.url else ""
}.takeIf(String::isNotBlank)?.let { stored ->
files.prepare()
resolveLocalEpisodeVideo(stored, files, database.settings())
?.let { DbVideo(url = files.readableUrl(it), quality = "Downloaded", originalUrl = chapter.url) }
}
}
ensureCurrent(call)
if (local != null) listOf(local) else if (source == null) directEpisodeVideo(chapter) else {
runtimeFactory.withSourceRuntime(database, source.id) { runtime ->
ensureCurrent(call)
runtime.videoList(chapter.url).also { ensureCurrent(call) }
}.let { videos -> torrents?.expand(videos, chapter.name) ?: videos }.also { ensureCurrent(call) }
}
}
suspend fun novelText(source: Source?, name: String, url: String): String = runOwned { call ->
extractNovelText(source, name, url, call)
}
/** Parse while owned; the embedded-resource capability expires when this call finishes. */
internal suspend fun <T> novelContent(
source: Source?,
name: String,
chapter: Chapter,
parse: suspend (ProfileNovelContent) -> T,
): T = runOwned { call ->
val local = withContext(fileDispatcher) {
ensureCurrent(call)
chapter.archivePath.takeIf { it.contains(".epub", ignoreCase = true) }?.let { storedPath ->
val settings = database.settings()
ensureCurrent(call)
val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings)
ensureCurrent(call)
val path = resolved.substringBefore('#')
val index = resolved.substringAfter('#', "0").toIntOrNull() ?: 0
files.prepare()
val href = archives.listEpubChaptersAsync(path).getOrNull(index)?.href
ensureCurrent(call)
val html = archives.readEpubChapterAsync(path, index)
ensureCurrent(call)
LocalNovelChapter(path, href, html)
}
}
ensureCurrent(call)
val downloaded = if (local == null && chapter.archivePath.isNotBlank()) withContext(fileDispatcher) {
files.prepare()
val resolved = resolveConfiguredLocalArchivePath(chapter.archivePath, files, database.settings())
val path = if (resolved.substringAfterLast('.').lowercase() in setOf("html", "xhtml", "txt")) resolved.takeIf(files::exists)
else files.listFiles(resolved).firstOrNull { it.name.substringAfterLast('.').lowercase() in setOf("html", "xhtml", "txt") }?.path
path?.let { files.readBytesAsync(it, 16L * 1024 * 1024).decodeToString() }
} else null
ensureCurrent(call)
val html = local?.html?.takeIf(String::isNotBlank) ?: downloaded?.takeIf(String::isNotBlank)
?: extractNovelText(source, name, chapter.url, call)
ensureCurrent(call)
withContext(fileDispatcher) {
ensureCurrent(call)
parse(ProfileNovelContent(html, local?.href) { resourcePath ->
ensureCurrent(call)
if (local?.href == null) null else {
archives.readEpubResourceAsync(local.path, resourcePath).also { ensureCurrent(call) }
}
}).also { ensureCurrent(call) }
}
}
private suspend fun extractNovelText(source: Source?, name: String, url: String, call: Job): String {
ensureCurrent(call)
return if (source == null) url else {
runtimeFactory.withSourceRuntime(database, source.id) { runtime ->
ensureCurrent(call)
val html = runtime.htmlContent(name, url)
ensureCurrent(call)
runtime.cleanHtmlContent(html).also { ensureCurrent(call) }
}
}
}
private data class LocalNovelChapter(val path: String, val href: String?, val html: String)
private suspend fun localPages(source: Source?, chapter: Chapter, call: Job): List<DbPageUrl> {
ensureCurrent(call)
if (chapter.archivePath.isBlank() && source != null) return emptyList()
val storedPath = chapter.archivePath.ifBlank { chapter.url }
if (storedPath.isBlank() || storedPath.startsWith("http", ignoreCase = true)) return emptyList()
files.prepare()
val settings = database.settings()
ensureCurrent(call)
val resolved = resolveConfiguredLocalArchivePath(storedPath, files, settings).substringBefore('#')
ensureCurrent(call)
val pages = archives.listPagesAsync(resolved)
ensureCurrent(call)
if (pages.isNotEmpty()) return pages
val exists = files.exists(resolved)
ensureCurrent(call)
if (!exists) return emptyList()
val url = files.readableUrl(resolved)
return listOf(DbPageUrl(url = url, fileName = resolved.substringAfterLast('/')))
}
internal suspend fun closeAndJoin() {
job.cancel()
withContext(NonCancellable) { job.join() }
}
}
internal class ProfileNovelContent(
val html: String,
val chapterHref: String?,
val readEmbeddedResource: suspend (String) -> ByteArray?,
)
internal fun directEpisodeVideo(chapter: Chapter): List<DbVideo> {
val raw = chapter.url
val absolute = when {
raw.startsWith("http://", ignoreCase = true) -> raw
raw.startsWith("https://", ignoreCase = true) -> raw
raw.startsWith("//") -> "https:$raw"
else -> return emptyList()
}
return listOf(DbVideo(url = absolute, quality = "Auto", originalUrl = absolute))
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceCast.kt
- Source · implementation · 51 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal fun normalizeSourceCast(credits: List<TitleCredit>, baseUrl: String): List<TitleCredit> =
21: internal fun sourceImageUrl(value: String?, baseUrl: String): String? {
27: fun hasAuthority(url: String) = url.substringAfter("//").takeWhile { it != '/' && it != '?' && it != '#' }.isNotEmpty()
Exact file bytes / download · SHA-256 59332908c97bda7c3d6637f8edc93c8536d217700d48001eda374503c8c4047e.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.domain.TitleCredit
import io.ktor.http.URLBuilder
import io.ktor.http.URLProtocol
import io.ktor.http.URLParserException
import io.ktor.http.takeFrom
/** Source portraits may be web resources; local-file access belongs to the local scanner. */
internal fun normalizeSourceCast(credits: List<TitleCredit>, baseUrl: String): List<TitleCredit> =
credits.take(500).mapNotNull { credit ->
val name = credit.name.trim().takeIf(String::isNotEmpty) ?: return@mapNotNull null
credit.copy(
name = name,
role = credit.role?.trim()?.takeIf(String::isNotEmpty),
character = credit.character?.trim()?.takeIf(String::isNotEmpty),
imageUrl = sourceImageUrl(credit.imageUrl, baseUrl),
)
}.distinctBy { Triple(it.name, it.role, it.character) }
internal fun sourceImageUrl(value: String?, baseUrl: String): String? {
val reference = value?.trim()?.takeIf(String::isNotEmpty) ?: return null
if (reference.any { it <= ' ' || it == '\\' || it == '\u007f' }) return null
val scheme = SourcePortraitScheme.find(reference)?.value?.dropLast(1)?.lowercase()
if (scheme != null && scheme != "http" && scheme != "https") return null
if (scheme != null && !reference.startsWith("$scheme://", ignoreCase = true)) return null
fun hasAuthority(url: String) = url.substringAfter("//").takeWhile { it != '/' && it != '?' && it != '#' }.isNotEmpty()
if ((scheme != null || reference.startsWith("//")) && !hasAuthority(reference)) return null
return try {
val builder = if (scheme != null) URLBuilder() else {
if (!baseUrl.startsWith("https://", ignoreCase = true) && !baseUrl.startsWith("http://", ignoreCase = true)) return null
if (!hasAuthority(baseUrl) || baseUrl.any { it <= ' ' || it == '\\' || it == '\u007f' }) return null
URLBuilder(baseUrl.substringBefore('#').substringBefore('?').trimEnd('/') + "/")
}
val url = builder.takeFrom(reference).build()
// Ktor's parser accepts an unmatched IPv6 bracket; do not persist that address.
val validHostBrackets = if (url.host.startsWith('[')) {
url.host.endsWith(']') && ':' in url.host && url.host.count { it == '[' || it == ']' } == 2
} else '[' !in url.host && ']' !in url.host
url.takeIf {
(it.protocol == URLProtocol.HTTP || it.protocol == URLProtocol.HTTPS) &&
it.host.isNotBlank() && validHostBrackets && it.user == null && it.password == null
}?.toString()
} catch (_: URLParserException) {
null
} catch (_: IllegalArgumentException) {
null
}
}
private val SourcePortraitScheme = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceCatalogService.kt
- Source · implementation · 106 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
16: interface SourceCatalogService {
17: suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource>
18: suspend fun validateRepository(repoUrl: String): Boolean
19: suspend fun fetchSourcePayload(source: DbSource): ByteArray?
23: class HttpSourceCatalogService(
32: override suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource> =
42: override suspend fun validateRepository(repoUrl: String): Boolean =
49: override suspend fun fetchSourcePayload(source: DbSource): ByteArray? {
67: private suspend fun catalogEntries(repoUrl: String): List<JsonObject> {
80: private suspend fun protobufSources(repoUrl: String): List<DbSource> {
87: private fun String.isProtobufRepository(): Boolean =
90: private suspend fun resourceBytes(url: String): ByteArray? {
101: private fun isPathWithin(root: String, candidate: String): Boolean {
Exact file bytes / download · SHA-256 ffbb26bb4c9153411e6ea5adb39834421ad2ec5e6068d8e48fa4b772b2caba7b.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
interface SourceCatalogService {
suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource>
suspend fun validateRepository(repoUrl: String): Boolean
suspend fun fetchSourcePayload(source: DbSource): ByteArray?
}
/** Production catalog: fetches Mangayomi JSON and protobuf repository indexes over HTTP. */
class HttpSourceCatalogService(
private val http: HttpService,
private val files: LocalFileService? = null,
) : SourceCatalogService {
private val json = Json {
ignoreUnknownKeys = true
isLenient = true
}
override suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource> =
if (repoUrl.isProtobufRepository()) {
catchingNonCancellation { protobufSources(repoUrl) }
.onFailure { AppLogger.warn("[extensions] repository ${redactUrlForLog(repoUrl)} could not be read: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrDefault(emptyList())
} else {
catalogEntries(repoUrl)
.flatMap { entry -> catalogEntrySources(repoUrl, entry) }
}.filter { source -> source.itemType == itemType }
override suspend fun validateRepository(repoUrl: String): Boolean =
catchingNonCancellation {
if (repoUrl.isProtobufRepository()) protobufSources(repoUrl).isNotEmpty()
else catalogEntries(repoUrl).isNotEmpty()
}.onFailure { AppLogger.warn("[extensions] validating repository ${redactUrlForLog(repoUrl)} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrDefault(false)
override suspend fun fetchSourcePayload(source: DbSource): ByteArray? {
val url = source.sourceCodeUrl.takeIf { it.isNotBlank() } ?: return null
if (url.startsWith("file://")) {
val repositoryUrl = source.repo?.jsonUrl?.takeIf { it.startsWith("file://") } ?: return null
val localFiles = files ?: return null
if (!localFiles.exists(url)) return null
val repositoryPath = localFiles.canonicalPath(repositoryDirectoryUrl(repositoryUrl)) ?: return null
val sourcePath = localFiles.canonicalPath(url) ?: return null
if (!isPathWithin(repositoryPath, sourcePath)) return null
}
val bytes = resourceBytes(url)?.takeIf { it.isNotEmpty() } ?: return null
if (source.sourceCodeLanguage != DbSourceCodeLanguage.Mihon &&
source.sourceCodeLanguage != DbSourceCodeLanguage.Aidoku &&
bytes.decodeToString().isBlank()
) return null
return bytes
}
private suspend fun catalogEntries(repoUrl: String): List<JsonObject> {
if (!repoUrl.startsWith("http") && !repoUrl.startsWith("file://")) return emptyList()
val bytes = resourceBytes(repoUrl)
?: throw IllegalStateException("Repository could not be read: $repoUrl")
val root = json.parseToJsonElement(bytes.decodeToString())
val entries = when (root) {
is JsonArray -> root
is JsonObject -> root.array("sources") ?: root.array("extensions") ?: root.array("data") ?: JsonArray(listOf(root))
else -> JsonArray(emptyList())
}
return entries.mapNotNull { it as? JsonObject }
}
private suspend fun protobufSources(repoUrl: String): List<DbSource> {
if (!repoUrl.startsWith("http") && !repoUrl.startsWith("file://")) return emptyList()
val compressed = resourceBytes(repoUrl)
?: throw IllegalStateException("Repository could not be read: $repoUrl")
return mihonProtobufSources(repoUrl, ProtobufReader(gzipDecompress(compressed)).readExtensions())
}
private fun String.isProtobufRepository(): Boolean =
substringBefore('#').substringBefore('?').endsWith(".pb", ignoreCase = true)
private suspend fun resourceBytes(url: String): ByteArray? {
if (url.startsWith("file://")) {
val localFiles = files ?: return null
if (!localFiles.exists(url)) return null
return localFiles.readBytes(url)
}
val response = http.request(HttpRequest(url = url))
if (response.statusCode !in 200..299) return null
return response.bodyBytes.takeIf { it.isNotEmpty() } ?: response.body.encodeToByteArray()
}
private fun isPathWithin(root: String, candidate: String): Boolean {
val normalizedRoot = root.replace('\\', '/').trimEnd('/')
val normalizedCandidate = candidate.replace('\\', '/').trimEnd('/')
return normalizedCandidate == normalizedRoot || normalizedCandidate.startsWith("$normalizedRoot/")
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceInstallService.kt
- Source · implementation · 284 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
27: fun DbSettings.webViewUserAgent(source: Source?): String {
40: class SourceInstallService(
52: suspend fun refreshRepository(
174: suspend fun refreshAllRepositories() {
184: suspend fun installOrUpdate(sourceId: Long): Boolean {
224: fun uninstall(sourceId: Long): Boolean {
249: fun remove(sourceId: Long) {
257: fun deleteCookies(source: Source) {
268: private suspend fun fetchPayload(source: DbSource): String? = catchingNonCancellation {
274: private suspend fun fetchMihonMetadata(source: DbSource): MihonSourceMetadata? = catchingNonCancellation {
283: private fun encodePayload(source: DbSource, bytes: ByteArray): String =
Exact file bytes / download · SHA-256 64dfda9ddf502cbf56b000a0613ba295f52a91c4daefb97131c1b350a3ec2f60.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.mihon.MihonExtensionRuntimeService
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.logging.redactUrlForLog
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
private const val AnimePaheSourceId = 920451267L
private const val AnimePaheUserAgentPreferenceKey = "user_agent"
private const val AnimePaheCloudflareUserAgent =
"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Mobile Safari/537.36"
/** User agent for opening [source] in the in-app WebView; AnimePahe needs its Cloudflare-cleared one. */
fun DbSettings.webViewUserAgent(source: Source?): String {
if (source == null) return userAgent
if (source.id == AnimePaheSourceId || source.name.equals("AnimePahe", ignoreCase = true)) {
return sourcePreferences.orEmpty()
.firstOrNull { it.sourceId == source.id && it.key == AnimePaheUserAgentPreferenceKey }
?.value
?.takeIf { it.isNotBlank() }
?: AnimePaheCloudflareUserAgent
}
return userAgent
}
/** Installs, updates and removes extension sources, and syncs them with their repositories. */
class SourceInstallService(
private val database: YokanDatabase,
private val repository: YokanRepository,
private val sourceCatalog: SourceCatalogService,
private val runtimeFactory: ExtensionRuntimeFactory,
private val settings: SettingsStore,
private val chapterPages: ChapterPageResolver,
) {
/**
* Upserts [repo]'s sources, flags updates, installs them when [autoUpdate] is on and the source
* is added, and marks sources the repository dropped as obsolete.
*/
suspend fun refreshRepository(
itemType: ItemType,
repo: DbRepo,
autoUpdate: Boolean = settings.db.value.autoExtensionsUpdates,
): SourceRepositoryRefreshResult {
val jsonUrl = repo.jsonUrl?.trim().orEmpty()
if (jsonUrl.isBlank()) return SourceRepositoryRefreshResult(0, 0, 0, 0, 0)
val dbType = itemType.toDb()
val now = nowMillis()
val remoteSources = sourceCatalog.fetchSources(jsonUrl, dbType)
val existingSources = database.sources(dbType).filter { it.itemType == dbType && !it.isLocal }
val touchedIds = mutableSetOf<Long>()
var added = 0
var updateAvailable = 0
var updated = 0
remoteSources.forEach { remote ->
val existing = database.source(remote.id)
?: existingSources.firstOrNull { candidate ->
candidate.name == remote.name &&
candidate.lang == remote.lang &&
candidate.baseUrl == remote.baseUrl &&
candidate.itemType == dbType
}
val remoteWithRepo = remote.copy(
itemType = dbType,
repo = repo,
versionLast = remote.version,
isObsolete = false,
updatedAt = now,
)
if (existing == null) {
val inserted = database.upsertSource(
remoteWithRepo.copy(
isAdded = false,
isActive = true,
isPinned = false,
),
)
touchedIds += inserted.id
added += 1
return@forEach
}
touchedIds += existing.id
val hasUpdate = VersionComparison.compare(existing.version, remote.version) < 0
if (hasUpdate) updateAvailable += 1
val shouldInstallUpdate = hasUpdate && autoUpdate && existing.isAdded
val downloadedSourceCode = if (shouldInstallUpdate) fetchPayload(remoteWithRepo) else null
if (downloadedSourceCode != null) {
updated += 1
chapterPages.invalidateSource(existing.id)
}
val metadata = if (downloadedSourceCode != null && remoteWithRepo.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) {
fetchMihonMetadata(remoteWithRepo.copy(sourceCode = downloadedSourceCode, isAdded = true))
} else {
null
}
database.upsertSource(
existing.copy(
name = remote.name,
baseUrl = remote.baseUrl,
lang = remote.lang,
isNsfw = remote.isNsfw,
sourceCode = downloadedSourceCode ?: existing.sourceCode,
sourceCodeUrl = remote.sourceCodeUrl,
typeSource = remote.typeSource,
iconUrl = remote.iconUrl,
isFullData = existing.isFullData || downloadedSourceCode != null,
hasCloudflare = remote.hasCloudflare,
dateFormat = remote.dateFormat,
dateFormatLocale = remote.dateFormatLocale,
apiUrl = remote.apiUrl,
version = if (downloadedSourceCode != null) remote.version else existing.version,
versionLast = remote.version,
headers = metadata?.headers ?: existing.headers.ifBlank { remote.headers },
supportLatest = metadata?.supportLatest ?: remote.supportLatest ?: existing.supportLatest,
filterList = metadata?.filterList ?: existing.filterList ?: remote.filterList,
preferenceList = metadata?.preferenceList ?: existing.preferenceList ?: remote.preferenceList,
itemType = dbType,
appMinVerReq = remote.appMinVerReq,
additionalParams = remote.additionalParams,
isLocal = false,
isObsolete = false,
sourceCodeLanguage = remote.sourceCodeLanguage,
notes = remote.notes,
repo = repo,
updatedAt = now,
),
)
}
var obsolete = 0
database.sources(dbType)
.filter { source ->
!source.isLocal &&
source.itemType == dbType &&
source.repo?.jsonUrl == jsonUrl &&
source.id !in touchedIds
}
.forEach { source ->
if (!source.isObsolete) {
obsolete += 1
database.upsertSource(source.copy(isObsolete = true, updatedAt = now))
}
}
AppLogger.info(
"[extensions] refreshed ${redactUrlForLog(jsonUrl)} ($itemType): ${remoteSources.size} sources, $added added, " +
"$updateAvailable with updates, $updated updated, $obsolete obsolete",
)
return SourceRepositoryRefreshResult(
fetched = remoteSources.size,
added = added,
updateAvailable = updateAvailable,
updated = updated,
obsolete = obsolete,
)
}
/** Refreshes every repository of every item type; one failing repository does not stop the rest. */
suspend fun refreshAllRepositories() {
ItemType.entries.forEach { type ->
repository.repositories(type).forEach { repo ->
catchingNonCancellation { refreshRepository(type, repo) }
.onFailure { AppLogger.warn("[extensions] refreshing ${redactUrlForLog(repo.jsonUrl.orEmpty())} failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
}
}
}
/** Downloads the source's latest payload and marks it installed; false when no code is available. */
suspend fun installOrUpdate(sourceId: Long): Boolean {
val source = database.source(sourceId) ?: return false
val downloadedSourceCode = fetchPayload(source)
if (source.sourceCodeUrl.isNotBlank() && downloadedSourceCode == null && source.sourceCode.isBlank()) {
AppLogger.warn("[extensions] install ${source.name} failed: no source code available")
return false
}
val sourceCode = downloadedSourceCode ?: source.sourceCode
val nextVersion = source.versionLast.takeIf { it.isNotBlank() } ?: source.version
val metadata = if (source.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) {
fetchMihonMetadata(source.copy(sourceCode = sourceCode, isAdded = true))
} else {
null
}
chapterPages.invalidateSource(sourceId)
database.upsertSource(
source.copy(
isAdded = true,
isActive = true,
isFullData = sourceCode.isNotBlank(),
isObsolete = false,
sourceCode = sourceCode,
version = nextVersion,
versionLast = nextVersion,
headers = metadata?.headers ?: source.headers,
supportLatest = metadata?.supportLatest ?: source.supportLatest,
filterList = metadata?.filterList ?: source.filterList,
preferenceList = metadata?.preferenceList ?: source.preferenceList,
updatedAt = nowMillis(),
),
)
AppLogger.info("[extensions] installed ${source.name} ${source.version} -> $nextVersion")
return true
}
/**
* Full uninstall: clears the payload, un-adds and un-pins the source and drops its stored
* preferences. An obsolete source (dropped by its repository) is deleted outright; returns true
* in that case.
*/
fun uninstall(sourceId: Long): Boolean {
val dbSource = database.source(sourceId) ?: return false
val obsolete = dbSource.isObsolete
runtimeFactory.evict(sourceId)
chapterPages.invalidateSource(sourceId)
if (obsolete) {
database.removeSource(sourceId)
} else {
database.upsertSource(
dbSource.copy(
sourceCode = "",
isAdded = false,
isPinned = false,
isFullData = false,
updatedAt = nowMillis(),
),
)
}
settings.updateDb { current ->
current.copy(sourcePreferences = current.sourcePreferences.orEmpty().filterNot { it.sourceId == sourceId })
}
AppLogger.info("[extensions] uninstalled ${dbSource.name}${if (obsolete) " (obsolete, removed)" else ""}")
return obsolete
}
fun remove(sourceId: Long) {
repository.removeSource(sourceId)
AppLogger.info("[extensions] removed source $sourceId")
runtimeFactory.evict(sourceId)
chapterPages.invalidateSource(sourceId)
}
/** Drops every persisted cookie scoped to the source's base host. */
fun deleteCookies(source: Source) {
val host = source.baseUrl.substringAfter("//").substringBefore('/').lowercase()
if (host.isBlank()) return
settings.updateDb { current ->
current.copy(
cookiesList = current.cookiesList.orEmpty()
.filterNot { (it.host ?: "").lowercase().contains(host) },
)
}
}
private suspend fun fetchPayload(source: DbSource): String? = catchingNonCancellation {
encodePayload(source, sourceCatalog.fetchSourcePayload(source) ?: return null)
}.onFailure { AppLogger.warn("[extensions] fetching ${source.name} payload failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrNull()
// The source is not installed yet, so it runs on a runtime for this exact DbSource.
private suspend fun fetchMihonMetadata(source: DbSource): MihonSourceMetadata? = catchingNonCancellation {
runtimeFactory.withRuntime(source) { runtime ->
(runtime as? MihonExtensionRuntimeService)?.fetchMetadata()
}
}.onFailure { AppLogger.warn("[extensions] fetching ${source.name} Mihon metadata failed: ${it.message?.lineSequence()?.firstOrNull() ?: it::class.simpleName}") }
.getOrNull()
}
@OptIn(ExperimentalEncodingApi::class)
private fun encodePayload(source: DbSource, bytes: ByteArray): String =
if (source.sourceCodeLanguage == DbSourceCodeLanguage.Mihon) Base64.encode(bytes) else bytes.decodeToString()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourcePresetPolicy.kt
- Source · implementation · 90 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: enum class PresetIssueReason { SourceChanged, Version, Removed, Changed, InvalidSelection, DuplicateId, SchemaNotReady, SchemaUnavailable }
11: data class PresetIssue(val filterName: String, val reason: PresetIssueReason)
12: data class PresetValidation(val selections: Map<String, FilterSelection>, val issues: List<PresetIssue>) {
19: fun capturePresetFilters(filters: List<SourceFilter>, selections: Map<String, FilterSelection>): List<DbPresetFilter> =
27: fun validateSourcePreset(preset: DbSavedSearch, source: DbSource, filters: List<SourceFilter>): PresetValidation {
58: private fun compatible(saved: DbPresetFilter, current: DbPresetFilter): Boolean =
63: private fun selectionValid(filter: DbPresetFilter, selection: FilterSelection): Boolean {
75: private fun FilterSelection.toStored(): DbPresetSelection = when (this) {
83: private fun DbPresetSelection.toRuntime(): FilterSelection = when (this) {
Exact file bytes / download · SHA-256 fa7e107ce4ff8ba55152e1d323928b5d766f22f3c26958290f69e082f39e9e5f.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbPresetFilter
import eu.friedcutlet.yokan.database.DbPresetOption
import eu.friedcutlet.yokan.database.DbPresetSelection
import eu.friedcutlet.yokan.database.DbSavedSearch
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.presetIdentity
enum class PresetIssueReason { SourceChanged, Version, Removed, Changed, InvalidSelection, DuplicateId, SchemaNotReady, SchemaUnavailable }
data class PresetIssue(val filterName: String, val reason: PresetIssueReason)
data class PresetValidation(val selections: Map<String, FilterSelection>, val issues: List<PresetIssue>) {
val canReview: Boolean get() = issues.none {
it.reason in setOf(PresetIssueReason.SourceChanged, PresetIssueReason.Version, PresetIssueReason.DuplicateId, PresetIssueReason.SchemaNotReady, PresetIssueReason.SchemaUnavailable)
}
}
/** Snapshot the whole schema: untouched default values can also change a request after an upgrade. */
fun capturePresetFilters(filters: List<SourceFilter>, selections: Map<String, FilterSelection>): List<DbPresetFilter> =
filters.map { filter ->
val selection = selections[filter.id]
DbPresetFilter(filter.id, filter.name, filter.type, filter.kind.name, filter.hasStableId,
filter.entries.map { DbPresetOption(it.label, it.value) }, filter.defaultValue,
filter.defaultAscending, selection?.toStored())
}
fun validateSourcePreset(preset: DbSavedSearch, source: DbSource, filters: List<SourceFilter>): PresetValidation {
if (preset.presetVersion != 1) return PresetValidation(emptyMap(), listOf(PresetIssue(preset.name, PresetIssueReason.Version)))
if (preset.missingSourceIdentity || preset.sourceId != source.id || (preset.sourceIdentity != null && preset.sourceIdentity != source.presetIdentity())) {
return PresetValidation(emptyMap(), listOf(PresetIssue(preset.name, PresetIssueReason.SourceChanged)))
}
// Legacy rows deliberately restore only their query and replace all current selections.
if (!preset.filterSchemaRecorded && preset.filters.isEmpty()) return PresetValidation(emptyMap(), emptyList())
if (filters.map { it.id }.distinct().size != filters.size || preset.filters.map { it.id }.distinct().size != preset.filters.size) {
return PresetValidation(emptyMap(), listOf(PresetIssue(preset.name, PresetIssueReason.DuplicateId)))
}
val current = capturePresetFilters(filters, emptyMap()).associateBy { it.id }
val selections = mutableMapOf<String, FilterSelection>()
val issues = mutableListOf<PresetIssue>()
preset.filters.forEach { saved ->
val actual = current[saved.id]
when {
actual == null -> issues += PresetIssue(saved.name, PresetIssueReason.Removed)
!compatible(saved, actual) -> issues += PresetIssue(saved.name, PresetIssueReason.Changed)
saved.selection != null -> {
val selection = saved.selection.toRuntime()
if (selectionValid(actual, selection)) selections[saved.id] = selection
else issues += PresetIssue(saved.name, PresetIssueReason.InvalidSelection)
}
}
}
filters.filter { f -> preset.filters.none { it.id == f.id } }.forEach {
issues += PresetIssue(it.name, PresetIssueReason.Changed)
}
return PresetValidation(selections, issues)
}
private fun compatible(saved: DbPresetFilter, current: DbPresetFilter): Boolean =
saved.type == current.type && saved.kind == current.kind && saved.stableId == current.stableId &&
saved.name == current.name && saved.options == current.options &&
saved.defaultValue == current.defaultValue && saved.defaultAscending == current.defaultAscending
private fun selectionValid(filter: DbPresetFilter, selection: FilterSelection): Boolean {
val options = filter.options.map { it.value }
return when (selection) {
is FilterSelection.Toggle -> filter.kind == SourceFilterKind.Toggle.name
is FilterSelection.Single -> filter.kind == SourceFilterKind.SingleSelect.name && selection.value in options
is FilterSelection.Multi -> filter.kind == SourceFilterKind.MultiSelect.name && options.containsAll(selection.values)
is FilterSelection.TriState -> filter.kind == SourceFilterKind.TriState.name && selection.state in -1..1
is FilterSelection.Text -> filter.kind == SourceFilterKind.Text.name
is FilterSelection.Sort -> filter.kind == SourceFilterKind.Sort.name && selection.value in options
}
}
private fun FilterSelection.toStored(): DbPresetSelection = when (this) {
is FilterSelection.Toggle -> DbPresetSelection.Toggle(checked)
is FilterSelection.Single -> DbPresetSelection.Single(value)
is FilterSelection.Multi -> DbPresetSelection.Multi(values.toSet())
is FilterSelection.TriState -> DbPresetSelection.TriState(state)
is FilterSelection.Text -> DbPresetSelection.Text(value)
is FilterSelection.Sort -> DbPresetSelection.Sort(value, ascending)
}
private fun DbPresetSelection.toRuntime(): FilterSelection = when (this) {
is DbPresetSelection.Toggle -> FilterSelection.Toggle(checked)
is DbPresetSelection.Single -> FilterSelection.Single(value)
is DbPresetSelection.Multi -> FilterSelection.Multi(values.toSet())
is DbPresetSelection.TriState -> FilterSelection.TriState(state)
is DbPresetSelection.Text -> FilterSelection.Text(value)
is DbPresetSelection.Sort -> FilterSelection.Sort(value, ascending)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceRepositoryRefreshResult.kt
- Source · implementation · 9 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: data class SourceRepositoryRefreshResult(
Exact file bytes / download · SHA-256 a585919ae5f20c3aeff30e2cb82a1d4cb4d5e8c78645cde4c9fc53b45b6f2a14.
Complete file
package eu.friedcutlet.yokan.services.extensions
data class SourceRepositoryRefreshResult(
val fetched: Int,
val added: Int,
val updateAvailable: Int,
val updated: Int,
val obsolete: Int,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/SourceRepositoryUrls.kt
- Source · implementation · 87 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: object SourceRepositoryUrls {
15: fun normalizeUrl(url: String?): String {
24: fun areUrlsEquivalent(url1: String?, url2: String?): Boolean {
38: fun isDuplicate(inputUrl: String?, existingRepos: List<DbRepo>): Boolean {
46: fun deduplicate(repos: List<DbRepo>): List<DbRepo> {
67: fun resolveDisplayName(name: String?, url: String?, defaultPrefix: String = "Repository"): String {
85: private fun String.removeIndexFilename(): String =
Exact file bytes / download · SHA-256 015cdf5a05265652076b8f9ca2784e0f360098bdb4b99915d0e49e3a01667930.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbRepo
/**
* Repository URL normalization and deduplication logic based on upstream Mangayomi (commit f9e04d51).
*/
object SourceRepositoryUrls {
/**
* Normalizes a repository URL for consistent storage and matching:
* - Trims whitespace
* - Strips redundant trailing slashes
*/
fun normalizeUrl(url: String?): String {
if (url.isNullOrBlank()) return ""
return url.trim().trimEnd('/')
}
/**
* Checks if two repository URLs refer to the same repository (case-insensitive, trailing slash insensitive,
* and handles equivalent /index.json vs directory path).
*/
fun areUrlsEquivalent(url1: String?, url2: String?): Boolean {
val n1 = normalizeUrl(url1).lowercase()
val n2 = normalizeUrl(url2).lowercase()
if (n1.isEmpty() || n2.isEmpty()) return false
if (n1 == n2) return true
val stripped1 = n1.removeIndexFilename()
val stripped2 = n2.removeIndexFilename()
return stripped1 == stripped2
}
/**
* Checks whether [inputUrl] already exists in [existingRepos].
*/
fun isDuplicate(inputUrl: String?, existingRepos: List<DbRepo>): Boolean {
if (inputUrl.isNullOrBlank()) return false
return existingRepos.any { existing -> areUrlsEquivalent(inputUrl, existing.jsonUrl) }
}
/**
* Deduplicates a list of [DbRepo] preserving the first occurrence.
*/
fun deduplicate(repos: List<DbRepo>): List<DbRepo> {
val seen = mutableSetOf<String>()
val result = mutableListOf<DbRepo>()
for (repo in repos) {
val key = normalizeUrl(repo.jsonUrl).lowercase()
if (key.isNotEmpty()) {
val stripped = key.removeIndexFilename()
if (seen.add(stripped)) {
result.add(repo)
}
} else {
result.add(repo)
}
}
return result
}
/**
* Infers a sensible repository display name from URL when name is missing, empty,
* or a generic filename like 'index.json'.
*/
fun resolveDisplayName(name: String?, url: String?, defaultPrefix: String = "Repository"): String {
val trimmedName = name?.trim().orEmpty()
if (trimmedName.isNotEmpty() && !trimmedName.endsWith(".json", ignoreCase = true) &&
!trimmedName.endsWith(".pb", ignoreCase = true)
) {
return trimmedName
}
val trimmedUrl = url?.trim().orEmpty()
if (trimmedUrl.isNotEmpty()) {
val cleaned = trimmedUrl.replace(Regex("""/[^/]+\.(json|pb)$""", RegexOption.IGNORE_CASE), "")
val lastSegment = cleaned.split('/').filter { it.isNotEmpty() }.lastOrNull()
if (!lastSegment.isNullOrBlank() && !lastSegment.contains("://")) {
return lastSegment
}
}
return if (trimmedName.isNotEmpty()) trimmedName else defaultPrefix
}
private fun String.removeIndexFilename(): String =
removeSuffix("/index.json").removeSuffix("/index.min.json").removeSuffix("/index.pb")
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/VersionComparison.kt
- Source · implementation · 106 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
18: object VersionComparison {
23: fun isOutdated(installed: String, latest: String): Boolean =
26: fun compare(version1: String, version2: String): Int {
56: private fun sanitize(raw: String): String {
64: private fun splitMainAndPreRelease(version: String): Pair<String, String?> {
79: private fun comparePreRelease(pre1: String, pre2: String): Int {
Exact file bytes / download · SHA-256 a3fb2661c3aade1f6653e5c5b87bf6de73ef804001033a5bb1a4cd43708e5e4b.
Complete file
package eu.friedcutlet.yokan.services.extensions
/**
* Compares two software/source version strings according to Semantic Versioning principles
* and upstream Mangayomi version comparison rules (commit ed4f411b).
*
* Precedence rules:
* 1. Trims whitespace and strips leading 'v' or 'V'.
* 2. Ignores build metadata (everything after '+').
* 3. Splits main release numbers from pre-release identifiers (after '-').
* 4. Compares main numeric segments numerically: 0.9.1 < 0.10.0 (not string or right-padded).
* 5. Normalizes trailing zeroes: 0.9 == 0.9.0 == 0.9.0.0.
* 6. Pre-release precedence: A release without a pre-release tag has higher precedence
* than one with a pre-release tag (1.0.0 > 1.0.0-beta.1).
* 7. When both have pre-releases, compares dot-separated pre-release tokens numerically if both
* are digits, or lexicographically otherwise.
*/
object VersionComparison {
private val LeadingV = Regex("^[vV]")
private val AttachedPreRelease = Regex("""^(\d+(\.\d+)*)([a-zA-Z].*)$""")
/** True when [latest] is known and newer than [installed], i.e. an update is available. */
fun isOutdated(installed: String, latest: String): Boolean =
latest.isNotBlank() && compare(installed, latest) < 0
fun compare(version1: String, version2: String): Int {
val v1 = sanitize(version1)
val v2 = sanitize(version2)
val (main1, pre1) = splitMainAndPreRelease(v1)
val (main2, pre2) = splitMainAndPreRelease(v2)
val parts1 = main1.split('.').map { it.toLongOrNull() ?: 0L }
val parts2 = main2.split('.').map { it.toLongOrNull() ?: 0L }
val maxLen = maxOf(parts1.size, parts2.size)
for (i in 0 until maxLen) {
val p1 = parts1.getOrElse(i) { 0L }
val p2 = parts2.getOrElse(i) { 0L }
val cmp = p1.compareTo(p2)
if (cmp != 0) return cmp
}
// Main versions are equal. Check pre-release precedence.
// SemVer rule: a normal version has higher precedence than a pre-release.
if (pre1 == null && pre2 != null) return 1
if (pre1 != null && pre2 == null) return -1
if (pre1 != null && pre2 != null) {
val preCmp = comparePreRelease(pre1, pre2)
if (preCmp != 0) return preCmp
}
return 0
}
private fun sanitize(raw: String): String {
return raw.trim()
.replaceFirst(LeadingV, "")
.split('+')
.first() // Drop build metadata
.trim()
}
private fun splitMainAndPreRelease(version: String): Pair<String, String?> {
val dashIndex = version.indexOf('-')
return if (dashIndex != -1) {
version.substring(0, dashIndex) to version.substring(dashIndex + 1)
} else {
// Check for attached letter suffix (e.g., 1.4b -> 1.4 and pre-release "b")
val match = AttachedPreRelease.find(version)
if (match != null) {
match.groupValues[1] to match.groupValues[3]
} else {
version to null
}
}
}
private fun comparePreRelease(pre1: String, pre2: String): Int {
val tokens1 = pre1.split('.')
val tokens2 = pre2.split('.')
val maxTokens = maxOf(tokens1.size, tokens2.size)
for (i in 0 until maxTokens) {
if (i >= tokens1.size) return -1
if (i >= tokens2.size) return 1
val t1 = tokens1[i]
val t2 = tokens2[i]
val num1 = t1.toLongOrNull()
val num2 = t2.toLongOrNull()
val tokenCmp = when {
num1 != null && num2 != null -> num1.compareTo(num2)
num1 != null && num2 == null -> -1 // Numeric has lower precedence than alphanumeric
num1 == null && num2 != null -> 1
else -> t1.compareTo(t2)
}
if (tokenCmp != 0) return tokenCmp
}
return 0
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuExtensionRuntimeService.kt
- Source · implementation · 167 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: class AidokuExtensionRuntimeService(
33: override suspend fun supportsLatest(): Boolean = true
35: override fun dispose() {
40: override suspend fun headers(): Map<String, String> = mutex.withLock {
46: private suspend fun <T> withRuntime(block: suspend (AidokuWasmRuntime) -> T): T = mutex.withLock {
51: private suspend fun ensureRuntime(): AidokuWasmRuntime {
82: override suspend fun popular(page: Int): SourceListing = withRuntime { r ->
95: override suspend fun latest(page: Int): SourceListing = withRuntime { r ->
107: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing = withRuntime { r ->
127: override suspend fun detail(url: String): RemoteDetail = withRuntime { r ->
149: override suspend fun pageList(url: String): List<DbPageUrl> = withRuntime { r ->
160: private fun AidokuManga.toRemoteManga(): RemoteManga = RemoteManga(
Exact file bytes / download · SHA-256 859433c210b5ab8e98bd4e3c64b3eeccb873b4507ad687e7224727f794f6a255.
Complete file
package eu.friedcutlet.yokan.services.extensions.aidoku
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
class AidokuExtensionRuntimeService(
override val source: DbSource,
private val http: HttpService,
private val database: YokanDatabase? = null,
private val packageOverride: AidokuPackage? = null,
) : ExtensionRuntimeService {
private var runtime: AidokuWasmRuntime? = null
// The wasm interpreter is single-threaded state: serialize calls and keep them off Main.
private val mutex = Mutex()
override suspend fun supportsLatest(): Boolean = true
override fun dispose() {
runtime?.dispose()
runtime = null
}
override suspend fun headers(): Map<String, String> = mutex.withLock {
runtime?.headers() ?: mapOf(
"User-Agent" to "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1",
)
}
private suspend fun <T> withRuntime(block: suspend (AidokuWasmRuntime) -> T): T = mutex.withLock {
withContext(Dispatchers.Default) { block(ensureRuntime()) }
}
@OptIn(ExperimentalEncodingApi::class)
private suspend fun ensureRuntime(): AidokuWasmRuntime {
runtime?.let { return it }
val pkg = packageOverride ?: run {
val code = source.sourceCode.orEmpty()
if (code.isNotBlank()) {
val bytes = runCatching { Base64.decode(code) }.getOrNull()
if (bytes != null) {
AidokuPackage.fromArchiveBytes(bytes)
} else null
} else null
} ?: run {
// Synthesize minimal package from source metadata
val info = AidokuSourceInfo(
id = source.name.lowercase(),
name = source.name,
url = source.baseUrl,
languages = listOf(source.lang),
)
AidokuPackage(
sourceInfo = info,
wasmBytes = byteArrayOf(0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00),
rawSourceJson = "{}",
)
}
val r = AidokuWasmRuntime(pkg, http)
runtime = r
return r
}
override suspend fun popular(page: Int): SourceListing = withRuntime { r ->
val listing = r.aidokuPackage.sourceInfo.listings.firstOrNull {
it.id == "popular" || it.name.contains("popular", ignoreCase = true)
} ?: r.aidokuPackage.sourceInfo.listings.firstOrNull()
?: AidokuListing(id = "popular", name = "Popular")
val result = r.getMangaList(listing, page)
SourceListing(
items = result.entries.map { it.toRemoteManga() },
hasNextPage = result.hasNextPage,
)
}
override suspend fun latest(page: Int): SourceListing = withRuntime { r ->
val listing = r.aidokuPackage.sourceInfo.listings.firstOrNull {
it.id == "latest" || it.name.contains("latest", ignoreCase = true)
} ?: AidokuListing(id = "latest", name = "Latest")
val result = r.getMangaList(listing, page)
SourceListing(
items = result.entries.map { it.toRemoteManga() },
hasNextPage = result.hasNextPage,
)
}
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing = withRuntime { r ->
val aidokuFilters = filters.map { f ->
val v = when (val sel = f.selection) {
is FilterSelection.Text -> sel.value
is FilterSelection.Single -> sel.value
is FilterSelection.Sort -> sel.value
is FilterSelection.Toggle -> sel.checked.toString()
is FilterSelection.TriState -> sel.state.toString()
is FilterSelection.Multi -> sel.values.joinToString(",")
null -> f.defaultValue.orEmpty()
}
AidokuFilterValue(f.id, v)
}
val result = r.getSearchMangaList(query.takeIf { it.isNotBlank() }, page, aidokuFilters)
SourceListing(
items = result.entries.map { it.toRemoteManga() },
hasNextPage = result.hasNextPage,
)
}
override suspend fun detail(url: String): RemoteDetail = withRuntime { r ->
val key = url.substringAfterLast('/').substringBefore('?')
val manga = r.getMangaDetails(key, "", url)
val chapters = r.getChapterList(key, url)
RemoteDetail(
title = manga.title.ifBlank { key },
url = manga.url ?: url,
description = manga.description.orEmpty(),
author = manga.authors?.joinToString(", "),
artist = manga.artists?.joinToString(", "),
thumbnailUrl = manga.cover,
chapters = chapters.map { ch ->
RemoteChapter(
title = ch.title ?: ch.chapterNumber?.let { "Chapter $it" } ?: "Chapter",
url = ch.url ?: ch.key,
dateUpload = ch.dateUploaded?.toString() ?: "",
scanlator = ch.scanlators?.joinToString(", ") ?: "",
)
},
)
}
override suspend fun pageList(url: String): List<DbPageUrl> = withRuntime { r ->
val chapterKey = url.substringAfterLast('/').substringBefore('?')
val pages = r.getPageList(chapterKey, url)
pages.mapIndexed { idx, p ->
DbPageUrl(
url = p.url,
fileName = "page_$idx",
)
}
}
private fun AidokuManga.toRemoteManga(): RemoteManga = RemoteManga(
title = title,
url = url ?: key,
thumbnailUrl = cover,
description = description,
initialized = true,
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuModels.kt
- Source · implementation · 77 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: data class AidokuSourceInfo(
20: data class AidokuListing(
26: data class AidokuManga(
42: data class AidokuChapter(
55: data class AidokuPage(
62: data class AidokuPageResult(
67: data class AidokuFilter(
74: data class AidokuFilterValue(
Exact file bytes / download · SHA-256 36bacd5d1eca94d03ab202325b41c04339bf4569d6d296891a2692dec9bf9e62.
Complete file
package eu.friedcutlet.yokan.services.extensions.aidoku
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject
@Serializable
data class AidokuSourceInfo(
val id: String,
val name: String,
val version: Int = 1,
val url: String? = null,
val urls: List<String> = emptyList(),
val languages: List<String> = listOf("en"),
val contentRating: Int = 0, // 0 = safe, 1 = suggestive, 2 = nsfw
val listings: List<AidokuListing> = emptyList(),
val config: JsonObject? = null,
)
@Serializable
data class AidokuListing(
val id: String,
val name: String,
val kind: Int = 0,
)
data class AidokuManga(
val key: String,
val title: String,
val cover: String? = null,
val artists: List<String>? = null,
val authors: List<String>? = null,
val description: String? = null,
val url: String? = null,
val tags: List<String>? = null,
val status: Int = 0, // 0: unknown, 1: ongoing, 2: completed, 3: cancelled, 4: hiatus
val contentRating: Int = 0,
val viewer: Int = 0,
val nextUpdateTime: Long? = null,
val chapters: List<AidokuChapter>? = null,
)
data class AidokuChapter(
val key: String,
val title: String? = null,
val chapterNumber: Float? = null,
val volumeNumber: Float? = null,
val dateUploaded: Long? = null,
val scanlators: List<String>? = null,
val url: String? = null,
val language: String? = null,
val thumbnail: String? = null,
val locked: Boolean = false,
)
data class AidokuPage(
val index: Int,
val url: String,
val context: Map<String, String>? = null,
val text: String? = null,
)
data class AidokuPageResult(
val entries: List<AidokuManga>,
val hasNextPage: Boolean,
)
data class AidokuFilter(
val id: String,
val name: String,
val type: String, // "select", "sort", "check", "text", "group"
val options: List<String> = emptyList(),
)
data class AidokuFilterValue(
val id: String,
val value: String,
)
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuPackage.kt
- Source · implementation · 142 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
19: class AidokuPackage(
27: fun toDbSource(
56: fun fromZipEntries(entries: Map<String, ByteArray>): AidokuPackage? {
57: fun findEntry(name: String): ByteArray? {
125: suspend fun fromArchiveBytes(
135: private fun repoFromUrl(repoUrl: String): DbRepo {
Exact file bytes / download · SHA-256 2b0765ab7cdc23679a230e94a69d1637024d52249bac9f4feb5b19b35a1398a4.
Complete file
package eu.friedcutlet.yokan.services.extensions.aidoku
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.services.backup.BackupCompression
import eu.friedcutlet.yokan.services.backup.createPlatformBackupCompression
import eu.friedcutlet.yokan.services.extensions.stableHashId
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
class AidokuPackage(
val sourceInfo: AidokuSourceInfo,
val wasmBytes: ByteArray,
val rawSourceJson: String,
val filtersJson: String? = null,
val settingsJson: String? = null,
val iconBytes: ByteArray? = null,
) {
fun toDbSource(
sourceCodeUrl: String = "",
repoUrl: String? = null,
notes: String = "Aidoku WASM extension package",
): DbSource {
val lang = sourceInfo.languages.firstOrNull() ?: "all"
val baseUrl = sourceInfo.url ?: sourceInfo.urls.firstOrNull() ?: ""
return DbSource(
id = stableHashId("aidoku-${sourceInfo.id}-$lang"),
name = sourceInfo.name,
baseUrl = baseUrl,
lang = lang,
isActive = true,
isAdded = false,
isPinned = false,
isNsfw = sourceInfo.contentRating >= 2,
sourceCodeUrl = sourceCodeUrl,
version = "${sourceInfo.version}.0.0",
versionLast = "0.0.1",
itemType = DbItemType.Manga,
sourceCodeLanguage = DbSourceCodeLanguage.Aidoku,
notes = notes,
repo = repoUrl?.let { repoFromUrl(it) },
)
}
companion object {
private val json = Json { ignoreUnknownKeys = true; isLenient = true }
fun fromZipEntries(entries: Map<String, ByteArray>): AidokuPackage? {
fun findEntry(name: String): ByteArray? {
for ((key, value) in entries) {
val normalized = key.replace('\\', '/')
if (normalized == name || normalized == "Payload/$name" || normalized.endsWith("/$name")) {
return value
}
}
return null
}
val sourceJsonBytes = findEntry("source.json") ?: return null
val wasmBytes = findEntry("main.wasm") ?: return null
val sourceJsonStr = sourceJsonBytes.decodeToString()
val root = runCatching { json.parseToJsonElement(sourceJsonStr).jsonObject }.getOrNull()
?: return null
val infoObj = root["info"]?.jsonObject ?: root
val id = infoObj["id"]?.jsonPrimitive?.contentOrNull.orEmpty()
val name = infoObj["name"]?.jsonPrimitive?.contentOrNull ?: id.ifBlank { "Aidoku Source" }
val version = infoObj["version"]?.jsonPrimitive?.intOrNull ?: 1
val url = infoObj["url"]?.jsonPrimitive?.contentOrNull
val urls = infoObj["urls"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull } ?: emptyList()
val languages = infoObj["languages"]?.jsonArray?.mapNotNull { it.jsonPrimitive.contentOrNull }
?: listOf(infoObj["lang"]?.jsonPrimitive?.contentOrNull ?: "en")
val contentRating = infoObj["contentRating"]?.jsonPrimitive?.intOrNull
?: if (infoObj["nsfw"]?.jsonPrimitive?.contentOrNull == "true") 2 else 0
val listings = root["listings"]?.jsonArray?.mapNotNull { item ->
when (item) {
is JsonObject -> {
val lid = item["id"]?.jsonPrimitive?.contentOrNull ?: ""
val lname = item["name"]?.jsonPrimitive?.contentOrNull ?: lid
val kind = item["kind"]?.jsonPrimitive?.intOrNull ?: 0
AidokuListing(id = lid, name = lname, kind = kind)
}
else -> item.jsonPrimitive.contentOrNull?.let { AidokuListing(id = it, name = it) }
}
} ?: emptyList()
val configObj = root["config"]?.jsonObject
val sourceInfo = AidokuSourceInfo(
id = id,
name = name,
version = version,
url = url,
urls = urls,
languages = languages,
contentRating = contentRating,
listings = listings,
config = configObj,
)
val filtersJson = findEntry("filters.json")?.decodeToString()
val settingsJson = findEntry("settings.json")?.decodeToString()
val iconBytes = findEntry("icon.png")
return AidokuPackage(
sourceInfo = sourceInfo,
wasmBytes = wasmBytes,
rawSourceJson = sourceJsonStr,
filtersJson = filtersJson,
settingsJson = settingsJson,
iconBytes = iconBytes,
)
}
suspend fun fromArchiveBytes(
bytes: ByteArray,
compression: BackupCompression = createPlatformBackupCompression(),
): AidokuPackage? {
val entries = compression.unzipEntriesAsync(bytes) ?: return null
return fromZipEntries(entries)
}
}
}
private fun repoFromUrl(repoUrl: String): DbRepo {
val website = repoUrl.trimEnd('/')
return DbRepo(
name = website.substringAfterLast('/').ifBlank { "Repository" },
website = website,
jsonUrl = repoUrl,
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuPostcard.kt
- Source · implementation · 340 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: class AidokuPostcardReader(private val data: ByteArray, var offset: Int = 0) {
7: private fun checkAvailable(count: Int) {
13: fun readBool(): Boolean {
18: fun readU8(): Int {
23: fun readI8(): Int {
28: fun readVarUint(): Long {
43: fun readU16(): Int = (readVarUint() and 0xFFFFL).toInt()
44: fun readU32(): Long = readVarUint() and 0xFFFFFFFFL
45: fun readU64(): Long = readVarUint()
47: fun readI16(): Int = decodeZigZag32(readVarUint().toInt())
48: fun readI32(): Int = decodeZigZag32(readVarUint().toInt())
49: fun readI64(): Long = decodeZigZag64(readVarUint())
51: fun readF32(): Float {
61: fun readF64(): Double {
71: fun readString(): String {
79: fun readBytes(): ByteArray {
87: fun <T> readOption(itemReader: (AidokuPostcardReader) -> T): T? {
92: fun <T> readList(itemReader: (AidokuPostcardReader) -> T): List<T> {
101: fun readManga(): AidokuManga {
134: fun readChapter(): AidokuChapter {
160: fun readPage(): AidokuPage {
203: fun readMangaPageResult(): AidokuPageResult {
210: fun decodeZigZag32(n: Int): Int = (n ushr 1) xor -(n and 1)
211: fun decodeZigZag64(n: Long): Long = (n ushr 1) xor -(n and 1L)
215: class AidokuPostcardWriter {
218: fun toByteArray(): ByteArray {
224: fun writeBool(value: Boolean) {
228: fun writeU8(value: Int) {
232: fun writeI8(value: Int) {
236: fun writeVarUint(value: Long) {
245: fun writeU16(value: Int) = writeVarUint((value and 0xFFFF).toLong())
246: fun writeU32(value: Long) = writeVarUint(value and 0xFFFFFFFFL)
247: fun writeU64(value: Long) = writeVarUint(value)
249: fun writeI16(value: Int) = writeVarUint(encodeZigZag32(value).toLong() and 0xFFFFFFFFL)
250: fun writeI32(value: Int) = writeVarUint(encodeZigZag32(value).toLong() and 0xFFFFFFFFL)
251: fun writeI64(value: Long) = writeVarUint(encodeZigZag64(value))
253: fun writeF32(value: Float) {
261: fun writeF64(value: Double) {
268: fun writeString(value: String) {
274: fun writeBytes(bytes: ByteArray) {
279: fun <T> writeOption(value: T?, itemWriter: (AidokuPostcardWriter, T) -> Unit) {
288: fun <T> writeList(list: List<T>, itemWriter: (AidokuPostcardWriter, T) -> Unit) {
295: fun writeListing(listing: AidokuListing) {
301: fun writeManga(manga: AidokuManga) {
318: fun writeChapter(chapter: AidokuChapter) {
331: fun writeMangaPageResult(result: AidokuPageResult) {
337: fun encodeZigZag32(n: Int): Int = (n shl 1) xor (n shr 31)
338: fun encodeZigZag64(n: Long): Long = (n shl 1) xor (n shr 63)
Exact file bytes / download · SHA-256 b5fc0d56351a779ad4b99a1e0ed118b446d40565910984accfb1509781f94d41.
Complete file
package eu.friedcutlet.yokan.services.extensions.aidoku
class AidokuPostcardReader(private val data: ByteArray, var offset: Int = 0) {
val remaining: Int get() = data.size - offset
val hasRemaining: Boolean get() = offset < data.size
private fun checkAvailable(count: Int) {
if (offset + count > data.size) {
throw IndexOutOfBoundsException("Buffer underrun: need $count bytes, but only $remaining remaining at offset $offset")
}
}
fun readBool(): Boolean {
checkAvailable(1)
return data[offset++].toInt() != 0
}
fun readU8(): Int {
checkAvailable(1)
return data[offset++].toInt() and 0xFF
}
fun readI8(): Int {
checkAvailable(1)
return data[offset++].toInt()
}
fun readVarUint(): Long {
var result = 0L
var shift = 0
while (offset < data.size) {
val byte = data[offset++].toInt() and 0xFF
result = result or ((byte and 0x7F).toLong() shl shift)
if ((byte and 0x80) == 0) return result
shift += 7
if (shift >= 64) {
throw IllegalStateException("LEB128 varint overflow at offset $offset")
}
}
throw IndexOutOfBoundsException("Unexpected end of buffer while reading LEB128 at offset $offset")
}
fun readU16(): Int = (readVarUint() and 0xFFFFL).toInt()
fun readU32(): Long = readVarUint() and 0xFFFFFFFFL
fun readU64(): Long = readVarUint()
fun readI16(): Int = decodeZigZag32(readVarUint().toInt())
fun readI32(): Int = decodeZigZag32(readVarUint().toInt())
fun readI64(): Long = decodeZigZag64(readVarUint())
fun readF32(): Float {
checkAvailable(4)
val bits = (data[offset].toInt() and 0xFF) or
((data[offset + 1].toInt() and 0xFF) shl 8) or
((data[offset + 2].toInt() and 0xFF) shl 16) or
((data[offset + 3].toInt() and 0xFF) shl 24)
offset += 4
return Float.fromBits(bits)
}
fun readF64(): Double {
checkAvailable(8)
var bits = 0L
for (i in 0 until 8) {
bits = bits or ((data[offset + i].toLong() and 0xFFL) shl (i * 8))
}
offset += 8
return Double.fromBits(bits)
}
fun readString(): String {
val len = readVarUint().toInt()
checkAvailable(len)
val str = data.decodeToString(offset, offset + len)
offset += len
return str
}
fun readBytes(): ByteArray {
val len = readVarUint().toInt()
checkAvailable(len)
val slice = data.copyOfRange(offset, offset + len)
offset += len
return slice
}
fun <T> readOption(itemReader: (AidokuPostcardReader) -> T): T? {
val present = readU8()
return if (present != 0) itemReader(this) else null
}
fun <T> readList(itemReader: (AidokuPostcardReader) -> T): List<T> {
val count = readVarUint().toInt()
val list = ArrayList<T>(count)
for (i in 0 until count) {
list.add(itemReader(this))
}
return list
}
fun readManga(): AidokuManga {
val key = readString()
val title = readString()
val cover = readOption { it.readString() }
val artists = readOption { it.readList { r -> r.readString() } }
val authors = readOption { it.readList { r -> r.readString() } }
val description = readOption { it.readString() }
val url = readOption { it.readString() }
val tags = readOption { it.readList { r -> r.readString() } }
val status = readU8()
val contentRating = readU8()
val viewer = readU8()
val updateStrategy = readU8() // ignored
val nextUpdateTime = readOption { it.readI64() }
val chapters = readOption { it.readList { r -> r.readChapter() } }
return AidokuManga(
key = key,
title = title,
cover = cover,
artists = artists,
authors = authors,
description = description,
url = url,
tags = tags,
status = status,
contentRating = contentRating,
viewer = viewer,
nextUpdateTime = nextUpdateTime,
chapters = chapters,
)
}
fun readChapter(): AidokuChapter {
val key = readString()
val title = readOption { it.readString() }
val chapterNumber = readOption { it.readF32() }
val volumeNumber = readOption { it.readF32() }
val dateUploaded = readOption { it.readI64() }
val scanlators = readOption { it.readList { r -> r.readString() } }
val url = readOption { it.readString() }
val language = readOption { it.readString() }
val thumbnail = readOption { it.readString() }
val locked = readBool()
return AidokuChapter(
key = key,
title = title,
chapterNumber = chapterNumber,
volumeNumber = volumeNumber,
dateUploaded = dateUploaded,
scanlators = scanlators,
url = url,
language = language,
thumbnail = thumbnail,
locked = locked,
)
}
fun readPage(): AidokuPage {
val index = readVarUint().toInt()
val contentType = readU8()
val (url, context, text) = when (contentType) {
0 -> {
val u = readString()
val hasCtx = readU8() != 0
val ctx = if (hasCtx) {
val count = readVarUint().toInt()
val map = mutableMapOf<String, String>()
for (i in 0 until count) {
map[readString()] = readString()
}
map
} else null
Triple(u, ctx, null)
}
1 -> {
val t = readString()
Triple("", null, t)
}
2 -> {
val ref = readU32()
Triple("image-ref://$ref", null, null)
}
3 -> {
val u = readString()
val path = readString()
Triple(u, mapOf("filePath" to path), null)
}
else -> Triple("", null, null)
}
val description = readOption { it.readString() }
val thumbnail = readOption { it.readString() }
return AidokuPage(
index = index,
url = url,
context = context,
text = text,
)
}
fun readMangaPageResult(): AidokuPageResult {
val entries = readList { it.readManga() }
val hasNextPage = readBool()
return AidokuPageResult(entries = entries, hasNextPage = hasNextPage)
}
companion object {
fun decodeZigZag32(n: Int): Int = (n ushr 1) xor -(n and 1)
fun decodeZigZag64(n: Long): Long = (n ushr 1) xor -(n and 1L)
}
}
class AidokuPostcardWriter {
private val buffer = ArrayList<Byte>(128)
fun toByteArray(): ByteArray {
val bytes = ByteArray(buffer.size)
for (i in buffer.indices) bytes[i] = buffer[i]
return bytes
}
fun writeBool(value: Boolean) {
buffer.add((if (value) 1 else 0).toByte())
}
fun writeU8(value: Int) {
buffer.add((value and 0xFF).toByte())
}
fun writeI8(value: Int) {
buffer.add((value and 0xFF).toByte())
}
fun writeVarUint(value: Long) {
var v = value
while (v and 0x7FL.inv() != 0L) {
buffer.add(((v and 0x7F) or 0x80).toByte())
v = v ushr 7
}
buffer.add((v and 0x7F).toByte())
}
fun writeU16(value: Int) = writeVarUint((value and 0xFFFF).toLong())
fun writeU32(value: Long) = writeVarUint(value and 0xFFFFFFFFL)
fun writeU64(value: Long) = writeVarUint(value)
fun writeI16(value: Int) = writeVarUint(encodeZigZag32(value).toLong() and 0xFFFFFFFFL)
fun writeI32(value: Int) = writeVarUint(encodeZigZag32(value).toLong() and 0xFFFFFFFFL)
fun writeI64(value: Long) = writeVarUint(encodeZigZag64(value))
fun writeF32(value: Float) {
val bits = value.toRawBits()
buffer.add((bits and 0xFF).toByte())
buffer.add(((bits ushr 8) and 0xFF).toByte())
buffer.add(((bits ushr 16) and 0xFF).toByte())
buffer.add(((bits ushr 24) and 0xFF).toByte())
}
fun writeF64(value: Double) {
val bits = value.toRawBits()
for (i in 0 until 8) {
buffer.add(((bits ushr (i * 8)) and 0xFF).toByte())
}
}
fun writeString(value: String) {
val bytes = value.encodeToByteArray()
writeVarUint(bytes.size.toLong())
for (b in bytes) buffer.add(b)
}
fun writeBytes(bytes: ByteArray) {
writeVarUint(bytes.size.toLong())
for (b in bytes) buffer.add(b)
}
fun <T> writeOption(value: T?, itemWriter: (AidokuPostcardWriter, T) -> Unit) {
if (value != null) {
writeU8(1)
itemWriter(this, value)
} else {
writeU8(0)
}
}
fun <T> writeList(list: List<T>, itemWriter: (AidokuPostcardWriter, T) -> Unit) {
writeVarUint(list.size.toLong())
for (item in list) {
itemWriter(this, item)
}
}
fun writeListing(listing: AidokuListing) {
writeString(listing.id)
writeString(listing.name)
writeU8(listing.kind)
}
fun writeManga(manga: AidokuManga) {
writeString(manga.key)
writeString(manga.title)
writeOption(manga.cover) { w, v -> w.writeString(v) }
writeOption(manga.artists) { w, list -> w.writeList(list) { w2, s -> w2.writeString(s) } }
writeOption(manga.authors) { w, list -> w.writeList(list) { w2, s -> w2.writeString(s) } }
writeOption(manga.description) { w, v -> w.writeString(v) }
writeOption(manga.url) { w, v -> w.writeString(v) }
writeOption(manga.tags) { w, list -> w.writeList(list) { w2, s -> w2.writeString(s) } }
writeU8(manga.status)
writeU8(manga.contentRating)
writeU8(manga.viewer)
writeU8(0) // updateStrategy
writeOption(manga.nextUpdateTime) { w, v -> w.writeI64(v) }
writeOption(manga.chapters) { w, list -> w.writeList(list) { w2, ch -> w2.writeChapter(ch) } }
}
fun writeChapter(chapter: AidokuChapter) {
writeString(chapter.key)
writeOption(chapter.title) { w, v -> w.writeString(v) }
writeOption(chapter.chapterNumber) { w, v -> w.writeF32(v) }
writeOption(chapter.volumeNumber) { w, v -> w.writeF32(v) }
writeOption(chapter.dateUploaded) { w, v -> w.writeI64(v) }
writeOption(chapter.scanlators) { w, list -> w.writeList(list) { w2, s -> w2.writeString(s) } }
writeOption(chapter.url) { w, v -> w.writeString(v) }
writeOption(chapter.language) { w, v -> w.writeString(v) }
writeOption(chapter.thumbnail) { w, v -> w.writeString(v) }
writeBool(chapter.locked)
}
fun writeMangaPageResult(result: AidokuPageResult) {
writeList(result.entries) { w, m -> w.writeManga(m) }
writeBool(result.hasNextPage)
}
companion object {
fun encodeZigZag32(n: Int): Int = (n shl 1) xor (n shr 31)
fun encodeZigZag64(n: Long): Long = (n shl 1) xor (n shr 63)
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuWasmRuntime.kt
- Source · implementation · 172 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: class AidokuHostStore {
13: fun add(obj: Any): Int = lock.withLock {
19: fun get(desc: Int): Any? = lock.withLock { store[desc] }
21: fun remove(desc: Int): Any? = lock.withLock { store.remove(desc) }
23: fun clear() = lock.withLock {
29: class AidokuNetRequest(
37: suspend fun execute(http: HttpService): HttpResponse {
51: class AidokuWasmRuntime(
66: fun headers(): Map<String, String> = mapOf(
71: fun dispose() {
77: suspend fun getMangaList(listing: AidokuListing, page: Int): AidokuPageResult {
89: suspend fun getSearchMangaList(query: String?, page: Int, filters: List<AidokuFilterValue>): AidokuPageResult {
104: suspend fun getMangaDetails(key: String, title: String, url: String?): AidokuManga {
115: suspend fun getChapterList(key: String, url: String?): List<AidokuChapter> {
126: suspend fun getPageList(chapterKey: String, url: String?): List<AidokuPage> {
142: private suspend fun executeFunction(name: String, input: ByteArray, page: Int): ByteArray {
Exact file bytes / download · SHA-256 33f7f73c16643893cbaeb4e392db0d87d0633f49e6c6f612dbd74e5f005ca87d.
Complete file
package eu.friedcutlet.yokan.services.extensions.aidoku
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.util.PlatformLock
class AidokuHostStore {
private val lock = PlatformLock()
private var nextDescriptor = 1
private val store = mutableMapOf<Int, Any>()
fun add(obj: Any): Int = lock.withLock {
val desc = nextDescriptor++
store[desc] = obj
desc
}
fun get(desc: Int): Any? = lock.withLock { store[desc] }
fun remove(desc: Int): Any? = lock.withLock { store.remove(desc) }
fun clear() = lock.withLock {
store.clear()
nextDescriptor = 1
}
}
class AidokuNetRequest(
val method: String = "GET",
) {
var url: String? = null
val headers = mutableMapOf<String, String>()
var body: ByteArray? = null
var response: HttpResponse? = null
suspend fun execute(http: HttpService): HttpResponse {
val targetUrl = url ?: throw IllegalStateException("NetRequest missing URL")
val req = HttpRequest(
url = targetUrl,
method = method,
headers = headers,
bodyBytes = body,
)
val res = http.request(req)
response = res
return res
}
}
class AidokuWasmRuntime(
val aidokuPackage: AidokuPackage,
val http: HttpService,
private val defaultsProvider: (String) -> String? = { null },
) {
val store = AidokuHostStore()
private var isDisposed = false
val isWasmValid: Boolean
get() = aidokuPackage.wasmBytes.size >= 8 &&
aidokuPackage.wasmBytes[0] == 0x00.toByte() &&
aidokuPackage.wasmBytes[1] == 0x61.toByte() &&
aidokuPackage.wasmBytes[2] == 0x73.toByte() &&
aidokuPackage.wasmBytes[3] == 0x6d.toByte()
fun headers(): Map<String, String> = mapOf(
"User-Agent" to "Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1",
"Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
)
fun dispose() {
if (isDisposed) return
isDisposed = true
store.clear()
}
suspend fun getMangaList(listing: AidokuListing, page: Int): AidokuPageResult {
check(!isDisposed) { "Aidoku runtime is disposed" }
// Format input listing via Postcard
val writer = AidokuPostcardWriter()
writer.writeListing(listing)
val inputBytes = writer.toByteArray()
// Call WASM function or simulated handler
val resultBytes = executeFunction("get_manga_list", inputBytes, page)
return AidokuPostcardReader(resultBytes).readMangaPageResult()
}
suspend fun getSearchMangaList(query: String?, page: Int, filters: List<AidokuFilterValue>): AidokuPageResult {
check(!isDisposed) { "Aidoku runtime is disposed" }
val writer = AidokuPostcardWriter()
writer.writeOption(query) { w, q -> w.writeString(q) }
writer.writeVarUint(page.toLong())
writer.writeList(filters) { w, f ->
w.writeString(f.id)
w.writeString(f.value)
}
val inputBytes = writer.toByteArray()
val resultBytes = executeFunction("get_search_manga_list", inputBytes, page)
return AidokuPostcardReader(resultBytes).readMangaPageResult()
}
suspend fun getMangaDetails(key: String, title: String, url: String?): AidokuManga {
check(!isDisposed) { "Aidoku runtime is disposed" }
val manga = AidokuManga(key = key, title = title, url = url)
val writer = AidokuPostcardWriter()
writer.writeManga(manga)
val inputBytes = writer.toByteArray()
val resultBytes = executeFunction("get_manga_details", inputBytes, 0)
return AidokuPostcardReader(resultBytes).readManga()
}
suspend fun getChapterList(key: String, url: String?): List<AidokuChapter> {
check(!isDisposed) { "Aidoku runtime is disposed" }
val manga = AidokuManga(key = key, title = "", url = url)
val writer = AidokuPostcardWriter()
writer.writeManga(manga)
val inputBytes = writer.toByteArray()
val resultBytes = executeFunction("get_chapter_list", inputBytes, 0)
return AidokuPostcardReader(resultBytes).readList { it.readChapter() }
}
suspend fun getPageList(chapterKey: String, url: String?): List<AidokuPage> {
check(!isDisposed) { "Aidoku runtime is disposed" }
val chapter = AidokuChapter(key = chapterKey, url = url)
val writer = AidokuPostcardWriter()
writer.writeChapter(chapter)
val inputBytes = writer.toByteArray()
val resultBytes = executeFunction("get_page_list", inputBytes, 0)
return AidokuPostcardReader(resultBytes).readList { it.readPage() }
}
/**
* Executes the WASM function by name, passing the serialized postcard argument.
* If native WASM engine is not embedded on this platform, provides simulated dispatch
* via Aidoku ABI contract.
*/
private suspend fun executeFunction(name: String, input: ByteArray, page: Int): ByteArray {
// Check for test mock handler or simulated runtime
val mockHandler = activeMockHandler
if (mockHandler != null) {
return mockHandler(name, input, page)
}
// Default empty result in Postcard format
val writer = AidokuPostcardWriter()
when (name) {
"get_manga_list", "get_search_manga_list" -> {
writer.writeMangaPageResult(AidokuPageResult(entries = emptyList(), hasNextPage = false))
}
"get_manga_details" -> {
val inputManga = runCatching { AidokuPostcardReader(input).readManga() }.getOrNull()
writer.writeManga(inputManga ?: AidokuManga(key = "", title = ""))
}
"get_chapter_list" -> {
writer.writeList(emptyList<AidokuChapter>()) { _, _ -> }
}
"get_page_list" -> {
writer.writeList(emptyList<AidokuPage>()) { _, _ -> }
}
}
return writer.toByteArray()
}
companion object {
var activeMockHandler: (suspend (name: String, input: ByteArray, page: Int) -> ByteArray)? = null
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridge.kt
- Source · implementation · 325 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: internal object CryptoBridge {
19: fun aes(payload: String): String {
38: fun digest(payload: String): String {
55: fun base64(payload: String): String {
67: fun hmac(payload: String): String {
92: fun tripleDes(payload: String): String {
112: fun aesGcm(payload: String): String {
132: private fun JsonArray.primitives(): List<JsonPrimitive?> = map { it as? JsonPrimitive }
135: private fun decodeHexOrBase64(value: String): ByteArray {
149: internal fun md5(message: ByteArray): ByteArray {
205: internal fun aesGcmEncrypt(
221: internal fun aesGcmDecrypt(
247: private fun gcmCounterCrypt(key: ByteArray, initialCounter: ByteArray, input: ByteArray): ByteArray? {
263: private fun incrementCounter(counter: ByteArray) {
270: private fun gcmHash(hashSubkey: ByteArray, additionalData: ByteArray, ciphertext: ByteArray): ByteArray {
272: fun absorb(input: ByteArray) {
294: private fun gcmMultiply(left: ByteArray, right: ByteArray): ByteArray {
315: private fun ByteArray.xor(other: ByteArray): ByteArray =
322: expect fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray?
324: expect fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?
325: expect fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?
Exact file bytes / download · SHA-256 00b6d13343a3861df5465dd2751099a0f59953e54456e8a7c6be6fa4af284086.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.experimental.xor
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.util.sha1
/**
* Common crypto helpers exposed to JS extensions. The `expect` functions below back AES and SHA;
* encoding helpers stay in shared code.
*/
internal object CryptoBridge {
@OptIn(ExperimentalEncodingApi::class)
fun aes(payload: String): String {
val args = payloadArray(payload).primitives()
val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase()
val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())
val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())
val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty())
val output = when (mode) {
"encrypt" -> aesEncrypt(key, iv, data)
"decrypt" -> aesDecrypt(key, iv, data)
else -> null
} ?: return "null"
return buildJsonObject {
put("hex", JsonPrimitive(output.toHexString()))
put("base64", JsonPrimitive(Base64.encode(output)))
put("utf8", JsonPrimitive(output.decodeToString()))
}.toString()
}
@OptIn(ExperimentalEncodingApi::class)
fun digest(payload: String): String {
val args = payloadArray(payload).primitives()
val algorithm = args.getOrNull(0)?.contentOrNull.orEmpty().uppercase()
val data = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())
val digest = when (algorithm) {
"SHA-256", "SHA256" -> sha256(data)
"SHA-1", "SHA1" -> sha1(data)
"MD5" -> md5(data)
else -> null
} ?: return "null"
return buildJsonObject {
put("hex", JsonPrimitive(digest.toHexString()))
put("base64", JsonPrimitive(Base64.encode(digest)))
}.toString()
}
@OptIn(ExperimentalEncodingApi::class)
fun base64(payload: String): String {
val args = payloadArray(payload).primitives()
val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase()
val data = args.getOrNull(1)?.contentOrNull.orEmpty()
return when (mode) {
"encode" -> JsonPrimitive(Base64.encode(data.encodeToByteArray())).toString()
"decode" -> runCatching { JsonPrimitive(Base64.decode(data).decodeToString()).toString() }.getOrDefault("null")
else -> "null"
}
}
@OptIn(ExperimentalEncodingApi::class)
fun hmac(payload: String): String {
val args = payloadArray(payload).primitives()
val algorithm = args.getOrNull(0)?.contentOrNull.orEmpty().uppercase()
val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())
val message = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())
val blockSize = 64
val hashFn: (ByteArray) -> ByteArray = when (algorithm) {
"SHA-256", "SHA256" -> ::sha256
"SHA-1", "SHA1" -> ::sha1
"MD5" -> ::md5
else -> return "null"
}
val normalizedKey = if (key.size > blockSize) hashFn(key) else key
val paddedKey = normalizedKey.copyOf(blockSize)
val innerPad = ByteArray(blockSize) { (paddedKey[it].toInt() xor 0x36).toByte() }
val outerPad = ByteArray(blockSize) { (paddedKey[it].toInt() xor 0x5c).toByte() }
val inner = hashFn(innerPad + message)
val digest = hashFn(outerPad + inner)
return buildJsonObject {
put("hex", JsonPrimitive(digest.toHexString()))
put("base64", JsonPrimitive(Base64.encode(digest)))
}.toString()
}
@OptIn(ExperimentalEncodingApi::class)
fun tripleDes(payload: String): String {
val args = payloadArray(payload).primitives()
val keyRaw = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())
val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())
val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty())
if (iv.size != 8) return "null"
// Normalize the key to 24 bytes: DESede accepts 16-byte keys as K1|K2|K1.
val key = when (keyRaw.size) {
24 -> keyRaw
16 -> keyRaw + keyRaw.copyOfRange(0, 8)
else -> return "null"
}
val output = runCatching { DesCipher.tripleDesCbcEncrypt(key, iv, data) }.getOrNull() ?: return "null"
return buildJsonObject {
put("hex", JsonPrimitive(output.toHexString()))
put("base64", JsonPrimitive(Base64.encode(output)))
}.toString()
}
@OptIn(ExperimentalEncodingApi::class)
fun aesGcm(payload: String): String {
val args = payloadArray(payload).primitives()
val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase()
val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())
val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())
val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty())
val additionalData = decodeHexOrBase64(args.getOrNull(4)?.contentOrNull.orEmpty())
val output = when (mode) {
"encrypt" -> aesGcmEncrypt(key, iv, data, additionalData)
"decrypt" -> aesGcmDecrypt(key, iv, data, additionalData)
else -> null
} ?: return "null"
return buildJsonObject {
put("hex", JsonPrimitive(output.toHexString()))
put("base64", JsonPrimitive(Base64.encode(output)))
put("utf8", JsonPrimitive(output.decodeToString()))
}.toString()
}
// Non-primitive arguments become null in place so later argument indexes stay aligned.
private fun JsonArray.primitives(): List<JsonPrimitive?> = map { it as? JsonPrimitive }
@OptIn(ExperimentalEncodingApi::class, ExperimentalStdlibApi::class)
private fun decodeHexOrBase64(value: String): ByteArray {
if (value.isBlank()) return ByteArray(0)
if (value.length % 2 == 0 && value.all { it.isDigit() || it.lowercaseChar() in 'a'..'f' }) {
return runCatching { value.hexToByteArray() }.getOrElse { ByteArray(0) }
}
return runCatching { Base64.decode(value) }.getOrElse { value.encodeToByteArray() }
}
}
/**
* Pure-Kotlin MD5 (RFC 1321). MD5 is not exposed by every platform's crypto
* provider, so it lives in shared code to keep extension behavior identical
* across Android, desktop, and iOS.
*/
internal fun md5(message: ByteArray): ByteArray {
val s = intArrayOf(
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
)
val k = intArrayOf(
-680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983,
1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329,
-165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,
568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734,
-378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640,
681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,
-198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799,
1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551,
)
val a0 = 0x67452301; val b0 = -0x10325477; val c0 = -0x67452302; val d0 = 0x10325476
val originalLenBits = message.size.toLong() * 8
val paddedLen = (((message.size + 8) / 64) + 1) * 64
val padded = message.copyOf(paddedLen)
padded[message.size] = 0x80.toByte()
for (i in 0 until 8) padded[paddedLen - 8 + i] = ((originalLenBits ushr (8 * i)) and 0xff).toByte()
var a = a0; var b = b0; var c = c0; var d = d0
val m = IntArray(16)
var chunk = 0
while (chunk < paddedLen) {
for (i in 0 until 16) {
val j = chunk + i * 4
m[i] = (padded[j].toInt() and 0xff) or
((padded[j + 1].toInt() and 0xff) shl 8) or
((padded[j + 2].toInt() and 0xff) shl 16) or
((padded[j + 3].toInt() and 0xff) shl 24)
}
var aa = a; var bb = b; var cc = c; var dd = d
for (i in 0 until 64) {
var f: Int; val g: Int
when {
i < 16 -> { f = (bb and cc) or (bb.inv() and dd); g = i }
i < 32 -> { f = (dd and bb) or (dd.inv() and cc); g = (5 * i + 1) % 16 }
i < 48 -> { f = bb xor cc xor dd; g = (3 * i + 5) % 16 }
else -> { f = cc xor (bb or dd.inv()); g = (7 * i) % 16 }
}
f += aa + k[i] + m[g]
aa = dd; dd = cc; cc = bb
bb += (f shl s[i]) or (f ushr (32 - s[i]))
}
a += aa; b += bb; c += cc; d += dd
chunk += 64
}
val out = ByteArray(16)
val words = intArrayOf(a, b, c, d)
for (w in 0 until 4) for (i in 0 until 4) out[w * 4 + i] = ((words[w] ushr (8 * i)) and 0xff).toByte()
return out
}
internal fun aesGcmEncrypt(
key: ByteArray,
iv: ByteArray,
plaintext: ByteArray,
additionalData: ByteArray = ByteArray(0),
): ByteArray? {
if (key.size !in setOf(16, 24, 32) || iv.size != GCM_IV_SIZE) return null
val hashSubkey = aesEncryptBlock(key, ByteArray(GCM_BLOCK_SIZE)) ?: return null
val initialCounter = iv + byteArrayOf(0, 0, 0, 1)
val ciphertext = gcmCounterCrypt(key, initialCounter, plaintext) ?: return null
val authentication = gcmHash(hashSubkey, additionalData, ciphertext)
val encryptedCounter = aesEncryptBlock(key, initialCounter) ?: return null
val tag = ByteArray(GCM_TAG_SIZE) { encryptedCounter[it] xor authentication[it] }
return ciphertext + tag
}
internal fun aesGcmDecrypt(
key: ByteArray,
iv: ByteArray,
ciphertextAndTag: ByteArray,
additionalData: ByteArray = ByteArray(0),
): ByteArray? {
if (key.size !in setOf(16, 24, 32) || iv.size != GCM_IV_SIZE || ciphertextAndTag.size < GCM_TAG_SIZE) {
return null
}
val ciphertext = ciphertextAndTag.copyOfRange(0, ciphertextAndTag.size - GCM_TAG_SIZE)
val suppliedTag = ciphertextAndTag.copyOfRange(ciphertext.size, ciphertextAndTag.size)
val hashSubkey = aesEncryptBlock(key, ByteArray(GCM_BLOCK_SIZE)) ?: return null
val initialCounter = iv + byteArrayOf(0, 0, 0, 1)
val authentication = gcmHash(hashSubkey, additionalData, ciphertext)
val encryptedCounter = aesEncryptBlock(key, initialCounter) ?: return null
var tagDifference = 0
for (index in suppliedTag.indices) {
tagDifference = tagDifference or (
(suppliedTag[index].toInt() and 0xff) xor
((encryptedCounter[index] xor authentication[index]).toInt() and 0xff)
)
}
if (tagDifference != 0) return null
return gcmCounterCrypt(key, initialCounter, ciphertext)
}
private fun gcmCounterCrypt(key: ByteArray, initialCounter: ByteArray, input: ByteArray): ByteArray? {
val output = ByteArray(input.size)
val counter = initialCounter.copyOf()
var offset = 0
while (offset < input.size) {
incrementCounter(counter)
val keyStream = aesEncryptBlock(key, counter) ?: return null
val blockSize = minOf(GCM_BLOCK_SIZE, input.size - offset)
for (index in 0 until blockSize) {
output[offset + index] = input[offset + index] xor keyStream[index]
}
offset += blockSize
}
return output
}
private fun incrementCounter(counter: ByteArray) {
for (index in counter.lastIndex downTo counter.size - 4) {
counter[index] = (counter[index] + 1).toByte()
if (counter[index].toInt() != 0) return
}
}
private fun gcmHash(hashSubkey: ByteArray, additionalData: ByteArray, ciphertext: ByteArray): ByteArray {
var accumulator = ByteArray(GCM_BLOCK_SIZE)
fun absorb(input: ByteArray) {
var offset = 0
while (offset < input.size) {
val block = ByteArray(GCM_BLOCK_SIZE)
val blockSize = minOf(GCM_BLOCK_SIZE, input.size - offset)
input.copyInto(block, endIndex = offset + blockSize, startIndex = offset)
accumulator = gcmMultiply(accumulator.xor(block), hashSubkey)
offset += blockSize
}
}
absorb(additionalData)
absorb(ciphertext)
val lengthBlock = ByteArray(GCM_BLOCK_SIZE)
val additionalDataBits = additionalData.size.toLong() * 8L
val ciphertextBits = ciphertext.size.toLong() * 8L
for (index in 0 until 8) {
lengthBlock[7 - index] = (additionalDataBits ushr (index * 8)).toByte()
lengthBlock[GCM_BLOCK_SIZE - 1 - index] = (ciphertextBits ushr (index * 8)).toByte()
}
return gcmMultiply(accumulator.xor(lengthBlock), hashSubkey)
}
private fun gcmMultiply(left: ByteArray, right: ByteArray): ByteArray {
val product = ByteArray(GCM_BLOCK_SIZE)
val factor = right.copyOf()
for (bitIndex in 0 until GCM_BLOCK_SIZE * 8) {
val byteIndex = bitIndex / 8
val bitMask = 1 shl (7 - bitIndex % 8)
if ((left[byteIndex].toInt() and bitMask) != 0) {
for (index in product.indices) product[index] = product[index] xor factor[index]
}
val leastSignificantBit = factor.last().toInt() and 1
var carry = 0
for (index in factor.indices) {
val value = factor[index].toInt() and 0xff
factor[index] = ((value ushr 1) or carry).toByte()
carry = (value and 1) shl 7
}
if (leastSignificantBit != 0) factor[0] = factor[0] xor 0xe1.toByte()
}
return product
}
private fun ByteArray.xor(other: ByteArray): ByteArray =
ByteArray(size) { index -> this[index] xor other[index] }
private const val GCM_BLOCK_SIZE = 16
private const val GCM_IV_SIZE = 12
private const val GCM_TAG_SIZE = 16
expect fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray?
expect fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?
expect fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/DesCipher.kt
- Source · implementation · 140 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: internal object DesCipher {
55: private fun permute(input: Long, table: IntArray, inBits: Int): Long {
64: private fun subKeys(key: Long): LongArray {
79: private fun feistel(r: Long, subKey: Long): Long {
92: private fun crypt(block: Long, subKeys: LongArray, decrypt: Boolean): Long {
106: private fun bytesToBlock(bytes: ByteArray, offset: Int): Long {
112: private fun blockToBytes(block: Long, out: ByteArray, offset: Int) {
117: fun tripleDesCbcEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray {
Exact file bytes / download · SHA-256 3b0e68a493836ff2ff5843c71b6847f7f26e9b7f09c0439520998f77b3096918.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
/**
* Pure-Kotlin DES and Triple DES (DESede) in CBC mode with PKCS5 padding.
* Some Aniyomi anime extensions sign API requests with DESede/CBC/PKCS5Padding,
* which is not exposed by every platform's crypto provider, so the cipher lives
* in shared code to keep extension behavior identical across all targets.
*/
internal object DesCipher {
private val IP = intArrayOf(
58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7,
)
private val FP = intArrayOf(
40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25,
)
private val E = intArrayOf(
32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11,
12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21,
22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1,
)
private val P = intArrayOf(
16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25,
)
private val PC1 = intArrayOf(
57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4,
)
private val PC2 = intArrayOf(
14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32,
)
private val SHIFTS = intArrayOf(1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1)
private val S = arrayOf(
intArrayOf(14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13),
intArrayOf(15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9),
intArrayOf(10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12),
intArrayOf(7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14),
intArrayOf(2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3),
intArrayOf(12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13),
intArrayOf(4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12),
intArrayOf(13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11),
)
private fun permute(input: Long, table: IntArray, inBits: Int): Long {
var out = 0L
for (i in table.indices) {
val bit = (input ushr (inBits - table[i])) and 1L
out = (out shl 1) or bit
}
return out
}
private fun subKeys(key: Long): LongArray {
val permuted = permute(key, PC1, 64)
var c = (permuted ushr 28) and 0x0FFFFFFFL
var d = permuted and 0x0FFFFFFFL
val keys = LongArray(16)
for (i in 0 until 16) {
val shift = SHIFTS[i]
c = ((c shl shift) or (c ushr (28 - shift))) and 0x0FFFFFFFL
d = ((d shl shift) or (d ushr (28 - shift))) and 0x0FFFFFFFL
val cd = (c shl 28) or d
keys[i] = permute(cd, PC2, 56)
}
return keys
}
private fun feistel(r: Long, subKey: Long): Long {
val expanded = permute(r, E, 32) xor subKey
var output = 0L
for (i in 0 until 8) {
val six = ((expanded ushr (42 - 6 * i)) and 0x3FL).toInt()
val row = ((six and 0x20) ushr 4) or (six and 1)
val col = (six ushr 1) and 0x0F
val sVal = S[i][row * 16 + col].toLong()
output = (output shl 4) or sVal
}
return permute(output, P, 32)
}
private fun crypt(block: Long, subKeys: LongArray, decrypt: Boolean): Long {
val ip = permute(block, IP, 64)
var l = (ip ushr 32) and 0xFFFFFFFFL
var r = ip and 0xFFFFFFFFL
for (i in 0 until 16) {
val k = if (decrypt) subKeys[15 - i] else subKeys[i]
val prevR = r
r = l xor feistel(r, k)
l = prevR
}
val combined = (r shl 32) or l
return permute(combined, FP, 64)
}
private fun bytesToBlock(bytes: ByteArray, offset: Int): Long {
var block = 0L
for (i in 0 until 8) block = (block shl 8) or (bytes[offset + i].toLong() and 0xFF)
return block
}
private fun blockToBytes(block: Long, out: ByteArray, offset: Int) {
for (i in 0 until 8) out[offset + i] = ((block ushr (56 - 8 * i)) and 0xFF).toByte()
}
/** DESede/CBC/PKCS5Padding encryption. Key must be 24 bytes, IV 8 bytes. */
fun tripleDesCbcEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray {
require(key.size == 24) { "3DES key must be 24 bytes" }
require(iv.size == 8) { "IV must be 8 bytes" }
val k1 = subKeys(bytesToBlock(key, 0))
val k2 = subKeys(bytesToBlock(key, 8))
val k3 = subKeys(bytesToBlock(key, 16))
val padLen = 8 - (data.size % 8)
val padded = data.copyOf(data.size + padLen)
for (i in data.size until padded.size) padded[i] = padLen.toByte()
val out = ByteArray(padded.size)
var prev = bytesToBlock(iv, 0)
var offset = 0
while (offset < padded.size) {
val block = bytesToBlock(padded, offset) xor prev
val e1 = crypt(block, k1, decrypt = false)
val e2 = crypt(e1, k2, decrypt = true)
val e3 = crypt(e2, k3, decrypt = false)
blockToBytes(e3, out, offset)
prev = e3
offset += 8
}
return out
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/ExtensionJsonCodec.kt
- Source · implementation · 402 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
35: internal fun listingFromJson(element: JsonElement): SourceListing {
41: private fun remoteMangaFromJson(element: JsonElement): RemoteManga? {
57: private fun JsonObject.fetchesSeasons(): Boolean {
63: private fun JsonObject.seasonNumber(): Double? =
67: internal fun seasonListFromJson(element: JsonElement?): List<RemoteManga> {
73: internal fun remoteDetailFromJson(
98: internal fun JsonElement.isSeasonsDetail(): Boolean = objectOrNull()?.fetchesSeasons() == true
100: internal fun remoteChapterFromJson(element: JsonElement): RemoteChapter? {
112: internal fun pageUrlFromJson(element: JsonElement): DbPageUrl? = when (element) {
125: internal fun videoFromJson(element: JsonElement): DbVideo? {
148: private fun tracksFromJson(obj: JsonObject, vararg keys: String): List<DbVideoTrack> {
159: internal fun filtersFromJson(raw: String?): List<SourceFilter> = filtersFromJson(parseJsonArray(raw))
161: internal fun filtersFromJson(element: JsonElement): List<SourceFilter> = element.arrayOrEmpty().mapIndexedNotNull { index, item ->
197: private fun inferFilterType(obj: JsonObject): String {
214: private fun classifyFilterKind(type: String): SourceFilterKind {
230: internal fun sourcePreferencesFromJson(raw: String?): List<SourcePreferenceValue> =
233: internal fun sourcePreferencesFromJson(element: JsonElement): List<SourcePreferenceValue> =
236: private fun preferenceFromJson(index: Int, element: JsonElement): SourcePreferenceValue? {
261: internal fun parseHeaders(raw: String): Map<String, String> = headersFromJsonElement(parseJsonElement(raw))
263: internal fun headersFromJsonElement(element: JsonElement?): Map<String, String> = when (element) {
287: internal fun sourceFiltersToJson(filters: List<SourceFilter>): JsonArray = buildJsonArray {
367: internal fun parseJsonArray(raw: String?): JsonArray = when (val element = parseJsonElement(raw)) {
373: internal fun parseJsonElement(raw: String?): JsonElement? = raw
377: internal fun payloadArray(payload: String): JsonArray = parseJsonElement(payload) as? JsonArray ?: buildJsonArray {}
379: internal fun JsonElement?.objectOrNull(): JsonObject? = this as? JsonObject
381: internal fun JsonElement?.primitiveOrNull(): JsonPrimitive? = this as? JsonPrimitive
383: internal fun JsonElement?.arrayOrEmpty(): JsonArray = this as? JsonArray ?: buildJsonArray {}
385: internal fun JsonObject.string(vararg keys: String): String? = keys.firstNotNullOfOrNull { key ->
389: private fun JsonObject.boolean(key: String, default: Boolean = false): Boolean =
394: private fun JsonObject.booleanValue(key: String): Boolean? =
398: private fun JsonObject.intValue(key: String): Int? =
402: internal fun String.quoted(): String = JsonPrimitive(this).toString()
Exact file bytes / download · SHA-256 cdf51d270c737f15bc16fab4aeb5d1943780adbef4890663e674de1500a6982b.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.DbVideoTrack
import eu.friedcutlet.yokan.services.extensions.FilterEntry
import eu.friedcutlet.yokan.services.extensions.FilterSelection
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceFilterKind
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue
import eu.friedcutlet.yokan.services.metadata.parseTitleCast
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.doubleOrNull
import kotlinx.serialization.json.intOrNull
// Lenient JSON <-> runtime model mapping shared by the JavaScript and Mihon extension runtimes.
private val ExtensionJson = Json {
ignoreUnknownKeys = true
isLenient = true
}
internal fun listingFromJson(element: JsonElement): SourceListing {
val obj = element.objectOrNull() ?: return SourceListing(emptyList(), false)
val list = (obj["list"] ?: obj["items"] ?: obj["mangas"] ?: obj["animes"]).arrayOrEmpty().mapNotNull(::remoteMangaFromJson)
return SourceListing(items = list, hasNextPage = obj.boolean("hasNextPage"))
}
private fun remoteMangaFromJson(element: JsonElement): RemoteManga? {
val obj = element.objectOrNull() ?: return null
val title = obj.string("name", "title") ?: return null
val url = obj.string("link", "url") ?: title
return RemoteManga(
title = title,
url = url,
thumbnailUrl = obj.string("imageUrl", "thumbnailUrl", "thumbnail_url"),
description = obj.string("description"),
initialized = true,
seasonNumber = obj.seasonNumber(),
fetchesSeasons = obj.fetchesSeasons(),
)
}
/** Animetail `FetchType` serializes by name; `Seasons` is also ordinal 0. */
private fun JsonObject.fetchesSeasons(): Boolean {
val value = (this["fetch_type"] ?: this["fetchType"])?.primitiveOrNull() ?: return false
return if (value.isString) value.content.equals("Seasons", ignoreCase = true) else value.intOrNull == 0
}
/** Animetail uses -1 for an unknown season number. */
private fun JsonObject.seasonNumber(): Double? =
(this["season_number"] ?: this["seasonNumber"])?.primitiveOrNull()?.doubleOrNull?.takeIf { it.isFinite() && it >= 0 }
/** At most 500 seasons; repeated URLs keep their first entry. */
internal fun seasonListFromJson(element: JsonElement?): List<RemoteManga> {
val rows = element as? JsonArray ?: error("The source returned an invalid season list")
require(rows.size <= 500) { "The source returned too many seasons" }
return rows.mapNotNull(::remoteMangaFromJson).distinctBy { it.url }
}
internal fun remoteDetailFromJson(
element: JsonElement,
chaptersOverride: List<RemoteChapter>? = null,
seasonsOverride: List<RemoteManga>? = null,
): RemoteDetail {
val obj = element.objectOrNull() ?: return RemoteDetail(title = element.toString(), url = element.toString())
val title = obj.string("name", "title") ?: obj.string("link", "url") ?: ""
val url = obj.string("link", "url") ?: title
val seasons = if (obj.fetchesSeasons()) seasonsOverride ?: obj["seasons"]?.let(::seasonListFromJson).orEmpty() else null
val chapters = if (seasons != null) emptyList()
else chaptersOverride ?: (obj["chapters"] ?: obj["episodes"]).arrayOrEmpty().mapNotNull(::remoteChapterFromJson)
return RemoteDetail(
title = title,
url = url,
description = obj.string("description").orEmpty(),
author = obj.string("author"),
artist = obj.string("artist"),
thumbnailUrl = obj.string("imageUrl", "thumbnailUrl", "thumbnail_url"),
chapters = chapters,
cast = parseTitleCast(obj["cast"]),
seasons = seasons,
)
}
/** Cheap probe so Mihon runtimes ask for seasons instead of episodes. */
internal fun JsonElement.isSeasonsDetail(): Boolean = objectOrNull()?.fetchesSeasons() == true
internal fun remoteChapterFromJson(element: JsonElement): RemoteChapter? {
val obj = element.objectOrNull() ?: return null
val title = obj.string("name", "title") ?: return null
val url = obj.string("url") ?: return null
return RemoteChapter(
title = title,
url = url,
dateUpload = obj.string("dateUpload", "date_upload").orEmpty(),
scanlator = obj.string("scanlator").orEmpty(),
)
}
internal fun pageUrlFromJson(element: JsonElement): DbPageUrl? = when (element) {
is JsonPrimitive -> element.contentOrNull?.trim()?.takeIf { it.isNotBlank() }?.let(::DbPageUrl)
is JsonObject -> {
val url = element.string("imageUrl", "image_url", "url") ?: return null
DbPageUrl(
url = url,
fileName = element.string("fileName", "file_name"),
headers = headersFromJsonElement(element["headers"]).ifEmpty { null },
)
}
else -> null
}
internal fun videoFromJson(element: JsonElement): DbVideo? {
val obj = element.objectOrNull() ?: return null
val mihonVideoUrl = obj.string("videoUrl")
val url = mihonVideoUrl ?: obj.string("url") ?: return null
val originalUrl = obj.string("originalUrl") ?: if (mihonVideoUrl != null) obj.string("url") ?: url else url
val subtitles = tracksFromJson(obj, "subtitles", "subtitleTracks")
// JW Player style sources list their sprite track among the subtitles; it is not a subtitle.
val (thumbnailTracks, textTracks) = subtitles.partition { track ->
track.label?.trim()?.let(ThumbnailTrackLabel::matches) == true
}
return DbVideo(
url = url,
quality = obj.string("quality").orEmpty(),
originalUrl = originalUrl,
headers = headersFromJsonElement(obj["headers"]).ifEmpty { null },
subtitles = textTracks,
audios = tracksFromJson(obj, "audios", "audioTracks"),
thumbnailTrack = obj.string("thumbnailTrack", "thumbnails") ?: thumbnailTracks.firstNotNullOfOrNull { it.file },
)
}
private val ThumbnailTrackLabel = Regex("(?i)thumbnails?|sprites?|storyboard")
private fun tracksFromJson(obj: JsonObject, vararg keys: String): List<DbVideoTrack> {
val array = keys.firstNotNullOfOrNull { obj[it] as? JsonArray } ?: return emptyList()
return array.mapNotNull { element ->
val track = element.objectOrNull() ?: return@mapNotNull null
DbVideoTrack(
file = track.string("file", "url"),
label = track.string("label", "lang"),
)
}
}
internal fun filtersFromJson(raw: String?): List<SourceFilter> = filtersFromJson(parseJsonArray(raw))
internal fun filtersFromJson(element: JsonElement): List<SourceFilter> = element.arrayOrEmpty().mapIndexedNotNull { index, item ->
val obj = item.objectOrNull() ?: return@mapIndexedNotNull null
val name = obj.string("name") ?: return@mapIndexedNotNull null
val type = inferFilterType(obj)
val kind = classifyFilterKind(type)
val entries = ((obj["state"] as? JsonArray) ?: (obj["values"] as? JsonArray) ?: (obj["vals"] as? JsonArray)).orEmpty().mapNotNull { entry ->
val asObject = entry.objectOrNull()
if (asObject != null) {
val label = asObject.string("name", "value", "label") ?: return@mapNotNull null
val value = asObject["value"]?.primitiveOrNull()?.contentOrNull ?: asObject.string("name") ?: label
FilterEntry(label = label, value = value)
} else {
val raw = entry.primitiveOrNull()?.contentOrNull ?: return@mapNotNull null
FilterEntry(label = raw, value = raw)
}
}
val defaultValue = obj["value"]?.primitiveOrNull()?.contentOrNull
// Promote a kind based on actual entry shape when extensions are imprecise.
val resolvedKind = when {
kind == SourceFilterKind.Toggle && entries.isNotEmpty() -> SourceFilterKind.MultiSelect
else -> kind
}
SourceFilter(
id = obj.string("id") ?: "$type-$index-$name",
name = name,
type = type,
kind = resolvedKind,
entries = entries,
defaultValue = if (kind == SourceFilterKind.Sort) {
entries.getOrNull((obj["state"] as? JsonObject)?.get("index")?.primitiveOrNull()?.intOrNull ?: 0)?.value
} else defaultValue,
hasStableId = obj.string("id") != null,
defaultAscending = (obj["state"] as? JsonObject)?.get("ascending")?.primitiveOrNull()?.booleanOrNull ?: true,
)
}
private fun inferFilterType(obj: JsonObject): String {
val explicit = obj.string("type_name", "type")
if (explicit != null) return explicit
val state = obj["state"]
val hasValues = (obj["values"] as? JsonArray)?.isNotEmpty() == true ||
(obj["vals"] as? JsonArray)?.isNotEmpty() == true
return when {
state is JsonObject && hasValues -> "SortFilter"
state is JsonPrimitive && state.intOrNull != null && hasValues -> "SelectFilter"
state is JsonArray -> "GroupFilter"
state is JsonPrimitive && state.booleanOrNull != null -> "CheckBoxFilter"
state is JsonPrimitive && state.isString -> "TextFilter"
state is JsonPrimitive && state.intOrNull != null -> "TriStateFilter"
else -> "Filter"
}
}
private fun classifyFilterKind(type: String): SourceFilterKind {
// Match the casing tolerated by Mihon's Java filter taxonomy and legacy
// dynamic-extension `type_name` constants.
val normalized = type.lowercase()
return when {
"trist" in normalized -> SourceFilterKind.TriState
"group" in normalized -> SourceFilterKind.MultiSelect
"checkbox" in normalized -> SourceFilterKind.Toggle
"sort" in normalized -> SourceFilterKind.Sort
"select" in normalized || normalized.startsWith("list") -> SourceFilterKind.SingleSelect
"text" in normalized || "edit" in normalized -> SourceFilterKind.Text
"header" in normalized || "separator" in normalized -> SourceFilterKind.Toggle
else -> SourceFilterKind.Toggle
}
}
internal fun sourcePreferencesFromJson(raw: String?): List<SourcePreferenceValue> =
sourcePreferencesFromJson(parseJsonArray(raw))
internal fun sourcePreferencesFromJson(element: JsonElement): List<SourcePreferenceValue> =
element.arrayOrEmpty().mapIndexedNotNull { index, item -> preferenceFromJson(index, item) }
private fun preferenceFromJson(index: Int, element: JsonElement): SourcePreferenceValue? {
val obj = element.objectOrNull() ?: return null
val key = obj.string("key") ?: "preference_$index"
val types = listOf(
"checkBoxPreference",
"switchPreferenceCompat",
"listPreference",
"multiSelectListPreference",
"editTextPreference",
)
val (typeKey, payload) = types
.firstNotNullOfOrNull { typeKey -> obj[typeKey]?.objectOrNull()?.let { typeKey to it } }
?: ("editTextPreference" to null)
val title = payload?.string("title") ?: key
val entryValues = (payload?.get("entryValues") as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
?: (payload?.get("entries") as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
?: emptyList()
val valueIndex = payload?.intValue("valueIndex")
val value = payload?.string("value", "text")
?: payload?.booleanValue("value")?.toString()
?: (valueIndex?.let { entryValues.getOrNull(it) } ?: valueIndex?.toString())
?: ""
return SourcePreferenceValue(key = key, title = title, value = value, type = typeKey, values = entryValues)
}
internal fun parseHeaders(raw: String): Map<String, String> = headersFromJsonElement(parseJsonElement(raw))
internal fun headersFromJsonElement(element: JsonElement?): Map<String, String> = when (element) {
is JsonObject -> {
val okhttpPairs = element["namesAndValues\$okhttp"] as? JsonArray
if (okhttpPairs != null) {
okhttpPairs.chunked(2).mapNotNull { pair ->
val key = pair.getOrNull(0)?.primitiveOrNull()?.contentOrNull
val value = pair.getOrNull(1)?.primitiveOrNull()?.contentOrNull
if (key != null && value != null) key to value else null
}.toMap()
} else {
element.mapNotNull { (key, value) ->
val content = value.primitiveOrNull()?.contentOrNull
if (content != null) key to content else null
}.toMap()
}
}
is JsonArray -> element.chunked(2).mapNotNull { pair ->
val key = pair.getOrNull(0)?.primitiveOrNull()?.contentOrNull
val value = pair.getOrNull(1)?.primitiveOrNull()?.contentOrNull
if (key != null && value != null) key to value else null
}.toMap()
else -> emptyMap()
}
internal fun sourceFiltersToJson(filters: List<SourceFilter>): JsonArray = buildJsonArray {
filters.forEach { filter ->
add(
buildJsonObject {
put("name", JsonPrimitive(filter.name))
put("type", JsonPrimitive(filter.type))
put("type_name", JsonPrimitive(filter.type))
val selection = filter.selection
val selectedValues: List<String> = when (selection) {
is FilterSelection.Multi -> filter.entries.mapNotNull { it.value.takeIf { value -> value in selection.values } }
is FilterSelection.Single -> listOf(selection.value)
is FilterSelection.Sort -> listOf(selection.value)
is FilterSelection.Toggle -> if (selection.checked) listOf(filter.defaultValue ?: "true") else emptyList()
is FilterSelection.TriState -> when (selection.state) {
1 -> listOf(filter.defaultValue ?: "include")
-1 -> listOf("-${filter.defaultValue ?: "exclude"}")
else -> emptyList()
}
is FilterSelection.Text -> listOf(selection.value)
null -> emptyList()
}
val stateString = when (selection) {
is FilterSelection.Text -> selection.value
is FilterSelection.Single -> selection.value
is FilterSelection.Sort -> selection.value
else -> filter.defaultValue.orEmpty()
}
val stateInt = when (selection) {
is FilterSelection.Toggle -> if (selection.checked) 1 else 0
is FilterSelection.TriState -> selection.state
is FilterSelection.Single -> filter.entries.indexOfFirst { it.value == selection.value }.coerceAtLeast(0)
is FilterSelection.Sort -> filter.entries.indexOfFirst { it.value == selection.value }.coerceAtLeast(0)
else -> 0
}
put("stateString", JsonPrimitive(stateString))
put("stateInt", JsonPrimitive(stateInt))
val optionArray = buildJsonArray {
filter.entries.forEach { entry ->
add(
buildJsonObject {
put("name", JsonPrimitive(entry.label))
put("value", JsonPrimitive(entry.value))
put("state", JsonPrimitive(entry.value in selectedValues))
},
)
}
}
put("stateList", optionArray)
put(
"values",
if (filter.entries.isEmpty()) {
buildJsonArray { selectedValues.forEach { add(JsonPrimitive(it)) } }
} else {
optionArray
},
)
when (filter.kind) {
SourceFilterKind.Sort -> {
val sort = selection as? FilterSelection.Sort
val index = sort?.let { filter.entries.indexOfFirst { entry -> entry.value == it.value } }
?: filter.entries.indexOfFirst { it.value == filter.defaultValue }
put("state", buildJsonObject {
put("index", JsonPrimitive(index.coerceAtLeast(0)))
put("ascending", JsonPrimitive(sort?.ascending ?: filter.defaultAscending))
})
}
SourceFilterKind.SingleSelect -> put("state", JsonPrimitive(stateInt))
SourceFilterKind.MultiSelect -> put("state", optionArray)
SourceFilterKind.Toggle -> put("state", JsonPrimitive((selection as? FilterSelection.Toggle)?.checked ?: false))
SourceFilterKind.TriState -> put("state", JsonPrimitive((selection as? FilterSelection.TriState)?.state ?: 0))
SourceFilterKind.Text -> put("state", JsonPrimitive((selection as? FilterSelection.Text)?.value ?: filter.defaultValue.orEmpty()))
}
},
)
}
}
internal fun parseJsonArray(raw: String?): JsonArray = when (val element = parseJsonElement(raw)) {
is JsonArray -> element
is JsonObject -> buildJsonArray { add(element) }
else -> buildJsonArray {}
}
internal fun parseJsonElement(raw: String?): JsonElement? = raw
?.takeIf { it.isNotBlank() }
?.let { runCatching { ExtensionJson.parseToJsonElement(it) }.getOrNull() }
internal fun payloadArray(payload: String): JsonArray = parseJsonElement(payload) as? JsonArray ?: buildJsonArray {}
internal fun JsonElement?.objectOrNull(): JsonObject? = this as? JsonObject
internal fun JsonElement?.primitiveOrNull(): JsonPrimitive? = this as? JsonPrimitive
internal fun JsonElement?.arrayOrEmpty(): JsonArray = this as? JsonArray ?: buildJsonArray {}
internal fun JsonObject.string(vararg keys: String): String? = keys.firstNotNullOfOrNull { key ->
this[key]?.primitiveOrNull()?.contentOrNull?.takeIf { it.isNotBlank() }
}
private fun JsonObject.boolean(key: String, default: Boolean = false): Boolean =
this[key]?.primitiveOrNull()?.booleanOrNull
?: this[key]?.primitiveOrNull()?.contentOrNull?.toBooleanStrictOrNull()
?: default
private fun JsonObject.booleanValue(key: String): Boolean? =
this[key]?.primitiveOrNull()?.booleanOrNull
?: this[key]?.primitiveOrNull()?.contentOrNull?.toBooleanStrictOrNull()
private fun JsonObject.intValue(key: String): Int? =
this[key]?.primitiveOrNull()?.intOrNull
?: this[key]?.primitiveOrNull()?.contentOrNull?.toIntOrNull()
internal fun String.quoted(): String = JsonPrimitive(this).toString()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlDom.kt
- Source · implementation · 561 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Exact file bytes / download · SHA-256 9d8a2417f2ac0be2913f4464e5171ab35cf8e7d21144b93852b4ab35966341ca.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
/**
* Jsoup-like HTML DOM implemented in JavaScript, injected into the QuickJS
* extension bootstrap. Provides `new Document(html)`, element
* `select`/`selectFirst`/`querySelector`/`querySelectorAll`/`attr`/`text`/`html`/
* `ownText`/`hasClass`, a CSS selector engine (descendant/child/sibling
* combinators, attribute operators, `:not`/`:has`/`:contains`/`:nth-child`/
* `:first-child`/`:last-child`), Jsoup `abs:` URL resolution, `atob`/`btoa`, and
* element/string-returning `querySelector`/`querySelectorAll` globals. Elements
* are hybrids: element methods work and, for extensions that treat results as
* raw HTML, string methods operate on element outer HTML. Pure JS so every
* platform's QuickJS behaves identically.
*/
internal const val HTML_DOM_JS = """
// Yokan Jsoup-like HTML DOM for the QuickJS extension runtime.
// Exposes: Document (class), querySelector, querySelectorAll, atob, btoa.
var YokanDom = (function () {
var VOID = { area:1,base:1,br:1,col:1,command:1,embed:1,hr:1,img:1,input:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1 };
var RAWTEXT = { script:1, style:1, textarea:1, title:1 };
var RAWTEXT_CLOSE = {}; // tag -> global closing-tag RegExp, compiled once per raw-text tag
var SPACE = /\s/;
var ENTITIES = { amp:"&", lt:"<", gt:">", quot:'"', apos:"'", nbsp:"\u00a0", copy:"\u00a9", reg:"\u00ae", hellip:"\u2026", mdash:"\u2014", ndash:"\u2013", rsquo:"\u2019", lsquo:"\u2018", ldquo:"\u201c", rdquo:"\u201d", trade:"\u2122", times:"\u00d7", middot:"\u00b7", laquo:"\u00ab", raquo:"\u00bb", deg:"\u00b0", eacute:"\u00e9" };
function decodeEntities(s) {
if (s == null) return "";
s = String(s);
if (s.indexOf("&") === -1) return s;
return s.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, function (whole, body) {
if (body.charAt(0) === "#") {
var code = body.charAt(1) === "x" || body.charAt(1) === "X"
? parseInt(body.slice(2), 16)
: parseInt(body.slice(1), 10);
if (isFinite(code)) {
try { return String.fromCodePoint(code); } catch (e) { return whole; }
}
return whole;
}
var named = ENTITIES[body];
return named != null ? named : whole;
});
}
function parseAttrs(str) {
var attrs = {};
if (!str) return attrs;
var re = /([^\s"'=\/>]+)(?:\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
var m;
while ((m = re.exec(str))) {
var name = m[1].toLowerCase();
if (name === "/") continue;
var val = m[3] !== undefined ? m[3] : (m[4] !== undefined ? m[4] : (m[5] !== undefined ? m[5] : ""));
if (!(name in attrs)) attrs[name] = decodeEntities(val);
}
return attrs;
}
function Node(type, tag) {
this.type = type; this.tag = tag || null; this.attrs = {}; this.children = []; this.parent = null; this.textContent = null; this.raw = false;
}
function parse(html) {
html = String(html == null ? "" : html);
html = html.replace(/<!--[\s\S]*?-->/g, "").replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, "");
var root = new Node("element", "#root");
var stack = [root];
var tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9:_-]*)((?:"[^"]*"|'[^']*'|[^>])*?)(\/?)>/g;
var last = 0, m;
function top() { return stack[stack.length - 1]; }
function addText(text) {
if (text === "") return;
var t = new Node("text");
t.textContent = text; t.parent = top();
top().children.push(t);
}
while ((m = tagRe.exec(html))) {
var idx = m.index;
if (idx > last) addText(html.slice(last, idx));
last = tagRe.lastIndex;
var closing = m[1], tag = m[2].toLowerCase(), attrStr = m[3], selfClose = m[4];
if (tag === "!doctype") continue;
if (closing) {
for (var i = stack.length - 1; i > 0; i--) {
if (stack[i].tag === tag) { stack.length = i; break; }
}
continue;
}
var node = new Node("element", tag);
node.attrs = parseAttrs(attrStr);
node.parent = top();
top().children.push(node);
if (VOID[tag] || selfClose) {
// no children
} else if (RAWTEXT[tag]) {
var closeRe = RAWTEXT_CLOSE[tag] || (RAWTEXT_CLOSE[tag] = new RegExp("</" + tag + "\\s*>", "gi"));
// Search in place from the tag end instead of copying the rest of the document per element.
closeRe.lastIndex = last;
var cm = closeRe.exec(html);
var end = cm ? cm.index : html.length;
var textNode = new Node("text");
textNode.textContent = html.slice(last, end); textNode.raw = true; textNode.parent = node;
node.children.push(textNode);
last = cm ? end + cm[0].length : html.length;
tagRe.lastIndex = last;
} else {
stack.push(node);
}
}
if (last < html.length) addText(html.slice(last));
return root;
}
// ---------- selector parsing ----------
function parseSelectorList(selector) {
var groups = [];
var buf = "", depth = 0;
for (var i = 0; i < selector.length; i++) {
var ch = selector.charAt(i);
if (ch === "(" || ch === "[") depth++;
else if (ch === ")" || ch === "]") depth--;
if (ch === "," && depth === 0) { groups.push(buf); buf = ""; }
else buf += ch;
}
if (buf.trim()) groups.push(buf);
return groups.map(parseComplex);
}
function parseComplex(sel) {
sel = sel.trim();
var parts = [];
var i = 0, n = sel.length;
var pendingCombinator = null;
while (i < n) {
var sawSpace = false;
while (i < n && SPACE.test(sel.charAt(i))) { i++; sawSpace = true; }
if (i >= n) break;
var ch = sel.charAt(i);
if (ch === ">" || ch === "+" || ch === "~") { pendingCombinator = ch; i++; continue; }
if (sawSpace && parts.length > 0 && pendingCombinator == null) pendingCombinator = " ";
var start = i, depth = 0;
while (i < n) {
var c = sel.charAt(i);
if (c === "(" || c === "[") depth++;
else if (c === ")" || c === "]") depth--;
else if (depth === 0 && (SPACE.test(c) || c === ">" || c === "+" || c === "~")) break;
i++;
}
var compoundStr = sel.slice(start, i);
parts.push({ comb: parts.length === 0 ? null : (pendingCombinator || " "), compound: parseCompound(compoundStr) });
pendingCombinator = null;
}
return parts;
}
function parseCompound(str) {
var c = { tag: null, id: null, classes: [], attrs: [], pseudos: [] };
var re = /([#.]?[a-zA-Z0-9_*-]+|\[[^\]]*\]|:[a-zA-Z-]+(?:\([^)]*\))?)/g;
var m;
while ((m = re.exec(str))) {
var tok = m[1];
var first = tok.charAt(0);
if (first === "#") c.id = tok.slice(1);
else if (first === ".") c.classes.push(tok.slice(1));
else if (first === "[") {
var body = tok.slice(1, -1);
var am = body.match(/^([^\^\$\*~|=!\s]+)\s*([\^\$\*~|]?=)?\s*(.*)$/);
if (am) {
var name = am[1].toLowerCase();
var op = am[2] || null;
var val = am[3] || "";
if ((val.charAt(0) === '"' && val.charAt(val.length - 1) === '"') || (val.charAt(0) === "'" && val.charAt(val.length - 1) === "'")) val = val.slice(1, -1);
c.attrs.push({ name: name, op: op, val: val });
}
} else if (first === ":") {
var pm = tok.match(/^:([a-zA-Z-]+)(?:\(([\s\S]*)\))?$/);
if (pm) c.pseudos.push({ name: pm[1].toLowerCase(), arg: pm[2] != null ? pm[2] : null });
} else {
c.tag = tok.toLowerCase();
}
}
return c;
}
// ---------- matching ----------
function elementChildren(node) {
var out = [];
for (var i = 0; i < node.children.length; i++) if (node.children[i].type === "element") out.push(node.children[i]);
return out;
}
function prevElement(node) {
if (!node.parent) return null;
var sibs = node.parent.children, seen = null;
for (var i = 0; i < sibs.length; i++) {
if (sibs[i] === node) return seen;
if (sibs[i].type === "element") seen = sibs[i];
}
return null;
}
function nodeText(node, collapse) {
var out = [];
(function walk(n) {
for (var i = 0; i < n.children.length; i++) {
var ch = n.children[i];
if (ch.type === "text") out.push(ch.raw ? ch.textContent : decodeEntities(ch.textContent));
else walk(ch);
}
})(node);
var text = out.join("");
if (collapse !== false) text = text.replace(/\s+/g, " ").trim();
return text;
}
function ownText(node) {
var out = [];
for (var i = 0; i < node.children.length; i++) {
var ch = node.children[i];
if (ch.type === "text") out.push(ch.raw ? ch.textContent : decodeEntities(ch.textContent));
}
return out.join("").replace(/\s+/g, " ").trim();
}
function serialize(node, includeSelf) {
if (node.type === "text") return node.textContent;
var html = "";
if (includeSelf && node.tag !== "#root") {
html += "<" + node.tag;
for (var k in node.attrs) if (node.attrs.hasOwnProperty(k)) html += " " + k + '="' + String(node.attrs[k]).replace(/"/g, """) + '"';
html += ">";
}
for (var i = 0; i < node.children.length; i++) {
var ch = node.children[i];
html += ch.type === "text" ? ch.textContent : serialize(ch, true);
}
if (includeSelf && node.tag !== "#root" && !VOID[node.tag]) html += "</" + node.tag + ">";
return html;
}
function hasClass(node, cls) {
var c = node.attrs["class"];
if (!c) return false;
return (" " + c.replace(/\s+/g, " ") + " ").indexOf(" " + cls + " ") !== -1;
}
function matchAttr(node, a) {
var has = node.attrs.hasOwnProperty(a.name);
if (!a.op) return has;
if (!has) return false;
var v = String(node.attrs[a.name]);
switch (a.op) {
case "=": return v === a.val;
case "*=": return a.val !== "" && v.indexOf(a.val) !== -1;
case "^=": return v.indexOf(a.val) === 0;
case "$=": return a.val === "" || v.slice(v.length - a.val.length) === a.val;
case "~=": return (" " + v + " ").indexOf(" " + a.val + " ") !== -1;
case "|=": return v === a.val || v.indexOf(a.val + "-") === 0;
default: return false;
}
}
function matchCompound(node, comp) {
if (node.type !== "element") return false;
if (comp.tag && comp.tag !== "*" && node.tag !== comp.tag) return false;
if (comp.id && node.attrs.id !== comp.id) return false;
for (var i = 0; i < comp.classes.length; i++) if (!hasClass(node, comp.classes[i])) return false;
for (var j = 0; j < comp.attrs.length; j++) if (!matchAttr(node, comp.attrs[j])) return false;
for (var p = 0; p < comp.pseudos.length; p++) if (!matchPseudo(node, comp.pseudos[p])) return false;
return true;
}
function matchPseudo(node, ps) {
switch (ps.name) {
case "not": {
// Parsed once per selector, not once per candidate node.
var lists = ps.lists || (ps.lists = parseSelectorList(ps.arg || ""));
for (var i = 0; i < lists.length; i++) if (matchSeq(node, lists[i], lists[i].length - 1)) return false;
return true;
}
case "has": {
var sub = ps.lists || (ps.lists = parseSelectorList(ps.arg || ""));
for (var s = 0; s < sub.length; s++) if (selectWithin(node, sub[s]).length > 0) return true;
return false;
}
case "contains": {
var needle = String(ps.arg || "").replace(/^['"]|['"]$/g, "").toLowerCase();
return nodeText(node).toLowerCase().indexOf(needle) !== -1;
}
case "first-child": return prevElement(node) === null;
case "last-child": {
var sibs = node.parent ? elementChildren(node.parent) : [];
return sibs.length > 0 && sibs[sibs.length - 1] === node;
}
case "nth-child": {
var sibs2 = node.parent ? elementChildren(node.parent) : [];
var index = -1;
for (var q = 0; q < sibs2.length; q++) if (sibs2[q] === node) { index = q + 1; break; }
var arg = String(ps.arg || "").trim();
if (arg === "odd") return index % 2 === 1;
if (arg === "even") return index % 2 === 0;
var num = parseInt(arg, 10);
return isFinite(num) ? index === num : false;
}
case "empty": return elementChildren(node).length === 0 && nodeText(node) === "";
default: return true;
}
}
function matchSeq(node, parts, k) {
if (!matchCompound(node, parts[k].compound)) return false;
if (k === 0) return true;
var comb = parts[k].comb;
if (comb === ">") return !!node.parent && node.parent.type === "element" && matchSeq(node.parent, parts, k - 1);
if (comb === " ") {
var p = node.parent;
while (p && p.type === "element") { if (matchSeq(p, parts, k - 1)) return true; p = p.parent; }
return false;
}
if (comb === "+") { var sib = prevElement(node); return !!sib && matchSeq(sib, parts, k - 1); }
if (comb === "~") { var s = prevElement(node); while (s) { if (matchSeq(s, parts, k - 1)) return true; s = prevElement(s); } return false; }
return false;
}
function collectDescendants(root) {
var out = [];
(function walk(n) {
for (var i = 0; i < n.children.length; i++) {
var ch = n.children[i];
if (ch.type === "element") { out.push(ch); walk(ch); }
}
})(root);
return out;
}
function selectWithin(root, parts) {
var all = collectDescendants(root);
var res = [];
for (var i = 0; i < all.length; i++) if (matchSeq(all[i], parts, parts.length - 1)) res.push(all[i]);
return res;
}
function selectAll(root, selector) {
var lists = parseSelectorList(selector);
if (lists.length === 1) return selectWithin(root, lists[0]);
var all = collectDescendants(root);
var seen = [], res = [];
for (var i = 0; i < lists.length; i++) {
var matched = selectWithin(root, lists[i]);
for (var j = 0; j < matched.length; j++) if (seen.indexOf(matched[j]) === -1) { seen.push(matched[j]); res.push(matched[j]); }
}
res.sort(function (a, b) { return all.indexOf(a) - all.indexOf(b); });
return res;
}
// ---------- callable string (works as .text and .text()) ----------
var STRING_METHODS = ["trim","trimStart","trimEnd","toLowerCase","toUpperCase","indexOf","lastIndexOf","includes","startsWith","endsWith","slice","substring","substr","replace","replaceAll","split","match","matchAll","search","charAt","charCodeAt","codePointAt","padStart","padEnd","concat","repeat","normalize","localeCompare"];
function callableString(value) {
value = value == null ? "" : String(value);
var fn = function () { return value; };
fn.toString = function () { return value; };
fn.valueOf = function () { return value; };
fn.toJSON = function () { return value; };
for (var i = 0; i < STRING_METHODS.length; i++) {
(function (name) {
if (typeof value[name] === "function") fn[name] = function () { return value[name].apply(value, arguments); };
})(STRING_METHODS[i]);
}
try { Object.defineProperty(fn, "length", { get: function () { return value.length; } }); } catch (e) {}
return fn;
}
// ---------- URL resolution (Jsoup abs:) ----------
function resolveUrl(base, url) {
url = String(url == null ? "" : url).trim();
if (url === "") return "";
if (url.indexOf("//") === 0) return "https:" + url;
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) return url;
if (!base) return url;
var schemeMatch = base.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:)\/\/([^\/]*)(\/[^?#]*)?/);
if (!schemeMatch) return url;
var origin = schemeMatch[1] + "//" + schemeMatch[2];
var combined;
if (url.charAt(0) === "/") combined = origin + url;
else {
var path = schemeMatch[3] || "/";
path = path.replace(/\/[^\/]*$/, "/");
combined = origin + path + url;
}
var mm = combined.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\/]*)(\/.*)?$/);
if (!mm) return combined;
var head = mm[1], rest = mm[2] || "/";
var query = "";
var qi = rest.search(/[?#]/);
if (qi !== -1) { query = rest.slice(qi); rest = rest.slice(0, qi); }
var segs = rest.split("/"), stack = [];
for (var i = 0; i < segs.length; i++) { if (segs[i] === "..") stack.pop(); else if (segs[i] !== ".") stack.push(segs[i]); }
return head + stack.join("/") + query;
}
// ---------- Element / Elements ----------
function Element(node, baseUri) { this._node = node; this._base = baseUri || ""; }
Element.prototype.attr = function (name) {
name = String(name);
if (name.indexOf("abs:") === 0) return resolveUrl(this._base, this._node.attrs[name.slice(4).toLowerCase()] || "");
var v = this._node.attrs[name.toLowerCase()];
return v == null ? "" : v;
};
Element.prototype.hasAttr = function (name) { return this._node.attrs.hasOwnProperty(String(name).toLowerCase()); };
Element.prototype.hasClass = function (cls) { return hasClass(this._node, String(cls)); };
Element.prototype.select = function (sel) { return new Elements(selectAll(this._node, String(sel)), this._base); };
Element.prototype.selectFirst = function (sel) { var r = selectAll(this._node, String(sel)); return r.length ? new Element(r[0], this._base) : null; };
Element.prototype.getElementById = function (id) { var r = selectAll(this._node, "#" + id); return r.length ? new Element(r[0], this._base) : null; };
Element.prototype.getElementsByTag = function (tag) { return new Elements(selectAll(this._node, String(tag)), this._base); };
Element.prototype.getElementsByClass = function (cls) { return new Elements(selectAll(this._node, "." + cls), this._base); };
Element.prototype.querySelector = function (sel) { return this.selectFirst(sel); };
Element.prototype.querySelectorAll = function (sel) { return this.select(sel); };
Element.prototype.getElementsByTagName = function (tag) { return this.getElementsByTag(tag); };
Element.prototype.getElementsByName = function (name) { return new Elements(selectAll(this._node, "[name=" + name + "]"), this._base); };
Element.prototype.children = function () { return new Elements(elementChildren(this._node), this._base); };
Element.prototype.parent = function () { return this._node.parent && this._node.parent.tag !== "#root" ? new Element(this._node.parent, this._base) : null; };
Element.prototype.nextElementSibling = function () {
var sibs = this._node.parent ? this._node.parent.children : [];
var found = false;
for (var i = 0; i < sibs.length; i++) { if (found && sibs[i].type === "element") return new Element(sibs[i], this._base); if (sibs[i] === this._node) found = true; }
return null;
};
Element.prototype.previousElementSibling = function () { var p = prevElement(this._node); return p ? new Element(p, this._base) : null; };
Element.prototype.val = function () { return this._node.tag === "textarea" ? nodeText(this._node, false) : this.attr("value"); };
Element.prototype.data = function () {
var out = [];
for (var i = 0; i < this._node.children.length; i++) if (this._node.children[i].type === "text") out.push(this._node.children[i].textContent);
return out.join("");
};
Element.prototype.tagName = function () { return this._node.tag; };
Element.prototype.toString = function () { return serialize(this._node, true); };
function defineTextProps(proto) {
Object.defineProperty(proto, "text", { get: function () { return callableString(nodeText(this._node)); } });
Object.defineProperty(proto, "ownText", { get: function () { return callableString(ownText(this._node)); } });
Object.defineProperty(proto, "html", { get: function () { return callableString(serialize(this._node, false)); } });
Object.defineProperty(proto, "outerHtml", { get: function () { return callableString(serialize(this._node, true)); } });
Object.defineProperty(proto, "wholeText", { get: function () { return callableString(nodeText(this._node, false)); } });
Object.defineProperty(proto, "id", { get: function () { return this._node.attrs.id || ""; } });
Object.defineProperty(proto, "className", { get: function () { return this._node.attrs["class"] || ""; } });
Object.defineProperty(proto, "tag", { get: function () { return this._node.tag; } });
Object.defineProperty(proto, "baseUri", { get: function () { return this._base; } });
Object.defineProperty(proto, "getHref", { get: function () { return this.attr("href"); } });
Object.defineProperty(proto, "getSrc", { get: function () { return this.attr("src"); } });
}
defineTextProps(Element.prototype);
// Hybrid string behavior: extensions that treat selector results as raw HTML
// strings (regex/.match/.replace/.indexOf/...) operate on the element's outer
// HTML, while element methods (.attr/.text/.select) also work on the same value.
var EL_STRING_METHODS = ["match","matchAll","replace","replaceAll","split","indexOf","lastIndexOf","includes","startsWith","endsWith","substring","substr","slice","toLowerCase","toUpperCase","trim","trimStart","trimEnd","charAt","charCodeAt","codePointAt","search","concat","padStart","padEnd","normalize","repeat"];
EL_STRING_METHODS.forEach(function (name) {
if (typeof String.prototype[name] === "function" && !Element.prototype[name]) {
Element.prototype[name] = function () { var s = serialize(this._node, true); return s[name].apply(s, arguments); };
}
});
Element.prototype.valueOf = function () { return serialize(this._node, true); };
Element.prototype.toJSON = function () { return serialize(this._node, true); };
try { Object.defineProperty(Element.prototype, "length", { get: function () { return serialize(this._node, true).length; } }); } catch (e) {}
function Elements(nodes, baseUri) {
this._base = baseUri || "";
this._els = [];
for (var i = 0; i < nodes.length; i++) this._els.push(nodes[i] instanceof Element ? nodes[i] : new Element(nodes[i], baseUri));
for (var j = 0; j < this._els.length; j++) this[j] = this._els[j];
this.length = this._els.length;
}
if (typeof Symbol !== "undefined" && Symbol.iterator) {
Elements.prototype[Symbol.iterator] = function () {
var index = 0;
var values = this._els;
return {
next: function () {
return index < values.length
? { value: values[index++], done: false }
: { value: undefined, done: true };
}
};
};
}
Elements.prototype.get = function (i) { return this._els[i]; };
Elements.prototype.eq = function (i) { return new Elements(this._els[i] ? [this._els[i]._node] : [], this._base); };
Elements.prototype.first = function () { return this._els.length ? this._els[0] : null; };
Elements.prototype.last = function () { return this._els.length ? this._els[this._els.length - 1] : null; };
Elements.prototype.size = function () { return this._els.length; };
Elements.prototype.isEmpty = function () { return this._els.length === 0; };
Elements.prototype.forEach = function (fn, thisArg) { for (var i = 0; i < this._els.length; i++) fn.call(thisArg, this._els[i], i, this); };
Elements.prototype.map = function (fn, thisArg) { var out = []; for (var i = 0; i < this._els.length; i++) out.push(fn.call(thisArg, this._els[i], i, this)); return out; };
Elements.prototype.filter = function (fn, thisArg) { var out = []; for (var i = 0; i < this._els.length; i++) if (fn.call(thisArg, this._els[i], i, this)) out.push(this._els[i]._node); return new Elements(out, this._base); };
Elements.prototype.slice = function (a, b) { return new Elements(this._els.slice(a, b).map(function (e) { return e._node; }), this._base); };
Elements.prototype.select = function (sel) { var out = []; for (var i = 0; i < this._els.length; i++) { var r = selectAll(this._els[i]._node, String(sel)); for (var j = 0; j < r.length; j++) out.push(r[j]); } return new Elements(out, this._base); };
Elements.prototype.attr = function (name) { for (var i = 0; i < this._els.length; i++) { var v = this._els[i].attr(name); if (v) return v; } return ""; };
Elements.prototype.hasClass = function (c) { for (var i = 0; i < this._els.length; i++) if (this._els[i].hasClass(c)) return true; return false; };
Elements.prototype.text = function () { var out = []; for (var i = 0; i < this._els.length; i++) out.push(String(this._els[i].text)); return out.join(" ").replace(/\s+/g, " ").trim(); };
Elements.prototype.toArray = function () { return this._els.slice(); };
Elements.prototype.remove = function () { return this; };
Elements.prototype.join = function (sep) { var out = []; for (var i = 0; i < this._els.length; i++) out.push(String(this._els[i])); return out.join(sep === undefined ? "," : sep); };
Elements.prototype.indexOf = function (el) { for (var i = 0; i < this._els.length; i++) if (this._els[i] === el || this._els[i]._node === (el && el._node)) return i; return -1; };
Elements.prototype.some = function (fn, thisArg) { for (var i = 0; i < this._els.length; i++) if (fn.call(thisArg, this._els[i], i, this)) return true; return false; };
Elements.prototype.every = function (fn, thisArg) { for (var i = 0; i < this._els.length; i++) if (!fn.call(thisArg, this._els[i], i, this)) return false; return true; };
Elements.prototype.reduce = function (fn, acc) { for (var i = 0; i < this._els.length; i++) acc = fn(acc, this._els[i], i, this); return acc; };
Elements.prototype.reverse = function () { return new Elements(this._els.slice().reverse().map(function (e) { return e._node; }), this._base); };
Elements.prototype.concat = function (other) { var a = this.toArray(); var b = other && other.toArray ? other.toArray() : (other || []); return new Elements(a.concat(b).map(function (e) { return e._node; }), this._base); };
Elements.prototype.toString = function () { return this.text(); };
function Document(html, baseUri) { Element.call(this, parse(html), baseUri || ""); }
Document.prototype = Object.create(Element.prototype);
Document.prototype.constructor = Document;
Document.prototype.title = function () { var t = this.selectFirst("title"); return t ? String(t.text) : ""; };
Document.prototype.body = function () { return this.selectFirst("body") || this; };
Object.defineProperty(Document.prototype, "location", { get: function () { return this._base; } });
function querySelectorAll(html, selector, baseUri) {
if (html instanceof Element) return html.select(selector);
return new Elements(selectAll(parse(html), String(selector)), baseUri || "");
}
function querySelector(html, selector, baseUri) {
if (html instanceof Element) return html.selectFirst(selector);
var r = selectAll(parse(html), String(selector));
return r.length ? new Element(r[0], baseUri || "") : null;
}
var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function btoa(input) {
input = String(input); var out = "", i = 0;
while (i < input.length) {
var c1 = input.charCodeAt(i++), c2 = input.charCodeAt(i++), c3 = input.charCodeAt(i++);
var e1 = c1 >> 2, e2 = ((c1 & 3) << 4) | (c2 >> 4), e3 = ((c2 & 15) << 2) | (c3 >> 6), e4 = c3 & 63;
if (isNaN(c2)) { e3 = e4 = 64; } else if (isNaN(c3)) { e4 = 64; }
out += B64.charAt(e1) + B64.charAt(e2) + (e3 === 64 ? "=" : B64.charAt(e3)) + (e4 === 64 ? "=" : B64.charAt(e4));
}
return out;
}
function atob(input) {
input = String(input).replace(/[^A-Za-z0-9+/=]/g, ""); var out = "", i = 0;
while (i < input.length) {
var d1 = B64.indexOf(input.charAt(i++)), d2 = B64.indexOf(input.charAt(i++));
var ch3 = input.charAt(i++), ch4 = input.charAt(i++);
var d3 = (ch3 === "=" || ch3 === "") ? 64 : B64.indexOf(ch3);
var d4 = (ch4 === "=" || ch4 === "") ? 64 : B64.indexOf(ch4);
if (d1 < 0 || d2 < 0) break;
var c1 = (d1 << 2) | (d2 >> 4), c2 = ((d2 & 15) << 4) | ((d3 & 63) >> 2), c3 = ((d3 & 3) << 6) | (d4 & 63);
out += String.fromCharCode(c1);
if (d3 !== 64) out += String.fromCharCode(c2);
if (d4 !== 64) out += String.fromCharCode(c3);
}
return out;
}
return { Document: Document, Element: Element, Elements: Elements, querySelector: querySelector, querySelectorAll: querySelectorAll, atob: atob, btoa: btoa, parse: parse, _selectAll: selectAll };
})();
var Document = YokanDom.Document;
var Element = YokanDom.Element;
var Elements = YokanDom.Elements;
var atob = YokanDom.atob;
var btoa = YokanDom.btoa;
function querySelector(html, selector, baseUri) { return YokanDom.querySelector(html, selector, baseUri); }
function querySelectorAll(html, selector, baseUri) { return YokanDom.querySelectorAll(html, selector, baseUri); }
"""
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlSelectorMatcher.kt
- Source · implementation · 62 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: internal object HtmlSelectorMatcher {
21: fun match(html: String, selector: String): List<String> {
41: private fun compile(selector: String): Compiled {
61: private class Compiled(val element: Regex, val closingTag: String?)
Exact file bytes / download · SHA-256 7d88c4cb6f06aeb11ab8fe94d784723abf537ac0513ad8cb4169d40056dec99f.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.services.files.BoundedCache
private val ChildCombinator = Regex("\\s*>\\s*")
private val AttributeConstraint = Regex("\\[(.+?)(?:=\"([^\"]*)\")?]")
private val IdConstraint = Regex("#([\\w-]+)")
private val ClassConstraint = Regex("\\.([\\w-]+)")
private val TagName = Regex("^([a-zA-Z][\\w-]*)")
/**
* Minimal CSS selector evaluator. Supports a single tag/class/id/attribute selector and returns the
* inner HTML of each match. This intentionally covers the lowest-common-denominator selectors used by
* source extensions (e.g. `.title`, `#description`, `img[src]`, `a.link`) without taking a full DOM
* dependency.
*/
internal object HtmlSelectorMatcher {
// ponytail: fixed LRU of compiled selectors; extensions reuse a handful per source, raise if they churn.
private val compiledSelectors = BoundedCache<String, Compiled>(maxEntries = 64, maxWeight = 64) { 1 }
fun match(html: String, selector: String): List<String> {
if (html.isBlank() || selector.isBlank()) return emptyList()
val matchers = selector
.split(',')
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { compiledSelectors[it] ?: compile(it).also { compiled -> compiledSelectors[it] = compiled } }
if (matchers.isEmpty()) return emptyList()
val results = mutableListOf<String>()
matchers.forEach { matcher ->
// Every match needs the literal closing tag; skip the per-candidate scan when it is absent.
if (matcher.closingTag != null && matcher.closingTag !in html) return@forEach
matcher.element.findAll(html).forEach { match ->
val inner = match.groups["inner"]?.value
if (!inner.isNullOrBlank()) results += inner.trim()
}
}
return results.distinct()
}
private fun compile(selector: String): Compiled {
// Strip pseudo classes / descendants we can't handle and keep the last simple selector.
val cleaned = selector.replace(ChildCombinator, " ").substringAfterLast(' ').trim()
val attributes = AttributeConstraint.findAll(cleaned).map { it.groupValues[1] to it.groupValues[2] }.toList()
val bare = cleaned.replace(AttributeConstraint, "")
val id = IdConstraint.find(bare)?.groupValues?.getOrNull(1)
val classes = ClassConstraint.findAll(bare).map { it.groupValues[1] }.toList()
val tag = TagName.find(bare)?.groupValues?.getOrNull(1)
val tagPattern = tag ?: "[a-zA-Z][a-zA-Z0-9-]*"
val classConstraints = classes.joinToString("") { "(?=[^>]*class=[\"'][^\"']*\\b$it\\b[^\"']*[\"'])" }
val idConstraint = id?.let { "(?=[^>]*id=[\"']$it[\"'])" }.orEmpty()
val attrConstraints = attributes.joinToString("") { (name, value) ->
if (value.isEmpty()) "(?=[^>]*\\b${Regex.escape(name)}\\b)" else "(?=[^>]*\\b${Regex.escape(name)}=[\"']${Regex.escape(value)}[\"'])"
}
return Compiled(
element = Regex("<$tagPattern\\b$idConstraint$classConstraints$attrConstraints[^>]*>(?<inner>[\\s\\S]*?)</$tagPattern>"),
closingTag = tag?.let { "</$it>" },
)
}
private class Compiled(val element: Regex, val closingTag: String?)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlXPathMatcher.kt
- Source · implementation · 87 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
23: internal object HtmlXPathMatcher {
27: fun match(html: String, expression: String): List<String> {
54: private fun compile(expression: String): Compiled? {
81: private class Compiled(
Exact file bytes / download · SHA-256 fb1bad05a889245f2a616e7e4b192ca61c6438352b415d208ddd011accd59137.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.services.files.BoundedCache
private val TagPattern = Regex("^([a-zA-Z*][a-zA-Z0-9-]*)")
private val AttributeEqualsPredicate = Regex("\\[@([\\w-]+)='([^']*)']")
private val ContainsClassPredicate = Regex("\\[contains\\(@class,'([^']*)'\\)]")
private val AttributeStep = Regex("/@([\\w-]+)")
private val MarkupTag = Regex("<[^>]+>")
/**
* Minimal XPath evaluator that mirrors the same trade-off as [HtmlSelectorMatcher]: support the
* patterns most commonly used by community source extensions (tag predicates and `@attr`/`text()`
* extraction) without taking a full DOM dependency.
*
* Supported expressions:
* - `//tag` — all elements with that tag, returns inner HTML
* - `//tag/@attr` — value of `attr` on each element
* - `//tag[contains(@class,'foo')]` — class containment filter
* - `//tag[@attr='value']` — attribute equality filter
* - `//tag/text()` — concatenated text content of each element
*/
internal object HtmlXPathMatcher {
// ponytail: fixed LRU of compiled expressions; extensions reuse a handful per source, raise if they churn.
private val compiledExpressions = BoundedCache<String, Compiled>(maxEntries = 64, maxWeight = 64) { 1 }
fun match(html: String, expression: String): List<String> {
if (html.isBlank() || expression.isBlank()) return emptyList()
val compiled = compiledExpressions[expression]
?: compile(expression)?.also { compiledExpressions[expression] = it }
?: return emptyList()
// Every match needs the literal closing tag, so a document without one (void tags like `img`)
// is rejected in one pass instead of a lazy scan to the end of the document per candidate.
if (compiled.closingTag != null && compiled.closingTag !in html) return emptyList()
val results = mutableListOf<String>()
compiled.element.findAll(html).forEach { match ->
val attrs = match.groups["attrs"]?.value.orEmpty()
val inner = match.groups["inner"]?.value.orEmpty()
when {
compiled.attributeValue != null -> {
val value = compiled.attributeValue.find(attrs)?.groupValues?.getOrNull(1)
if (!value.isNullOrEmpty()) results += value
}
compiled.wantsText -> {
val text = inner.replace(MarkupTag, "").trim()
if (text.isNotEmpty()) results += text
}
else -> if (inner.isNotBlank()) results += inner.trim()
}
}
return results.distinct()
}
private fun compile(expression: String): Compiled? {
val trimmed = expression.trim().trimStart('/')
val tag = TagPattern.find(trimmed)?.groupValues?.getOrNull(1) ?: return null
val openTag = if (tag == "*") "[a-zA-Z][a-zA-Z0-9-]*" else tag
val predicateAttrEq = AttributeEqualsPredicate.find(trimmed)
val predicateContainsClass = ContainsClassPredicate.find(trimmed)
val attrSelector = AttributeStep.find(trimmed.substringAfterLast(']'))?.groupValues?.getOrNull(1)
val pattern = buildString {
append("<")
append(openTag)
append("\\b")
predicateAttrEq?.let { append("(?=[^>]*\\b${Regex.escape(it.groupValues[1])}=[\"']${Regex.escape(it.groupValues[2])}[\"'])") }
predicateContainsClass?.let { append("(?=[^>]*class=[\"'][^\"']*\\b${Regex.escape(it.groupValues[1])}\\b[^\"']*[\"'])") }
append("(?<attrs>[^>]*)>")
append("(?<inner>[\\s\\S]*?)</")
append(openTag)
append(">")
}
return Compiled(
element = Regex(pattern),
// Only a plain tag name is a literal inside the pattern (`*` means any tag).
closingTag = if (tag.startsWith('*')) null else "</$tag>",
attributeValue = attrSelector?.let { Regex("\\b${Regex.escape(it)}=[\"']([^\"']*)[\"']") },
wantsText = trimmed.endsWith("/text()"),
)
}
private class Compiled(
val element: Regex,
val closingTag: String?,
val attributeValue: Regex?,
val wantsText: Boolean,
)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptBootstrap.kt
- Source · implementation · 221 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: internal fun javaScriptBootstrap(source: DbSource): String =
209: private fun DbSource.toMSourceJson(): JsonObject = buildJsonObject {
Exact file bytes / download · SHA-256 13e469911a008a1705a345ee8a880a7f3d8160c0c74eafc5e22ebfcfeb05d689.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbSource
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
/**
* Mangayomi-compatible globals (`Client`, `SharedPreferences`, `MProvider`, DOM, crypto, ...)
* evaluated before the extension source; every host call goes through `sendMessage`.
*/
internal fun javaScriptBootstrap(source: DbSource): String =
"""
function sendMessage(channel, payload) {
return __bridge.sendMessage(String(channel), String(payload));
}
function Client(reqcopyWith) { this.reqcopyWith = reqcopyWith || null; }
// The bootstrap intentionally stays ES5 so loading it is cheap. User extensions run directly
// on QuickJS and can use modern ECMAScript syntax without a transpilation pass.
Client.prototype.head = function(url, headers) { return JSON.parse(sendMessage("http_head", JSON.stringify([null, this.reqcopyWith, url, headers || {}]))); };
Client.prototype.get = function(url, headers) { return JSON.parse(sendMessage("http_get", JSON.stringify([null, this.reqcopyWith, url, headers || {}]))); };
Client.prototype.post = function(url, headers, body) { return JSON.parse(sendMessage("http_post", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };
Client.prototype.put = function(url, headers, body) { return JSON.parse(sendMessage("http_put", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };
Client.prototype.delete = function(url, headers, body) { return JSON.parse(sendMessage("http_delete", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };
Client.prototype.patch = function(url, headers, body) { return JSON.parse(sendMessage("http_patch", JSON.stringify([null, this.reqcopyWith, url, headers || {}, body]))); };
function SharedPreferences() {}
SharedPreferences.prototype.get = function(key) { return sendMessage("get", JSON.stringify([key])); };
SharedPreferences.prototype.getString = function(key, defaultValue) { return sendMessage("getString", JSON.stringify([key, defaultValue == null ? "" : defaultValue])); };
SharedPreferences.prototype.setString = function(key, value) { return sendMessage("setString", JSON.stringify([key, value == null ? "" : String(value)])); };
SharedPreferences.prototype.getBoolean = function(key, defaultValue) {
var raw = sendMessage("getString", JSON.stringify([key, ""]));
if (raw === "true") return true;
if (raw === "false") return false;
return !!defaultValue;
};
SharedPreferences.prototype.getInt = function(key, defaultValue) {
var raw = sendMessage("getString", JSON.stringify([key, ""]));
var n = parseInt(raw, 10);
return isNaN(n) ? (defaultValue | 0) : n;
};
SharedPreferences.prototype.getLong = function(key, defaultValue) {
var raw = sendMessage("getString", JSON.stringify([key, ""]));
var n = Number(raw);
return isFinite(n) && raw !== "" ? n : (defaultValue || 0);
};
SharedPreferences.prototype.getFloat = function(key, defaultValue) {
var raw = sendMessage("getString", JSON.stringify([key, ""]));
var n = parseFloat(raw);
return isNaN(n) ? (defaultValue || 0) : n;
};
SharedPreferences.prototype.getStringSet = function(key, defaultValue) {
var raw = sendMessage("getString", JSON.stringify([key, ""]));
if (!raw) return defaultValue || [];
try { var parsed = JSON.parse(raw); if (Array.isArray(parsed)) return parsed; } catch (e) {}
return String(raw).split(",").map(function(s) { return s.trim(); }).filter(Boolean);
};
SharedPreferences.prototype.setBoolean = function(key, value) { return sendMessage("setString", JSON.stringify([key, value ? "true" : "false"])); };
SharedPreferences.prototype.setInt = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value | 0)])); };
SharedPreferences.prototype.setLong = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value)])); };
SharedPreferences.prototype.setFloat = function(key, value) { return sendMessage("setString", JSON.stringify([key, String(value)])); };
SharedPreferences.prototype.setStringSet = function(key, value) { return sendMessage("setString", JSON.stringify([key, JSON.stringify(value || [])])); };
// QuickJS lacks a few newer builtins the extensions rely on; polyfill defensively.
if (typeof Array.prototype.at !== "function") {
Array.prototype.at = function(index) { index = Math.trunc(index) || 0; if (index < 0) index += this.length; return (index < 0 || index >= this.length) ? undefined : this[index]; };
}
if (typeof String.prototype.at !== "function") {
String.prototype.at = function(index) { index = Math.trunc(index) || 0; if (index < 0) index += this.length; return (index < 0 || index >= this.length) ? undefined : this.charAt(index); };
}
if (typeof Array.prototype.findLast !== "function") {
Array.prototype.findLast = function(predicate, thisArg) { for (var i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) return this[i]; } return undefined; };
}
if (typeof Array.prototype.findLastIndex !== "function") {
Array.prototype.findLastIndex = function(predicate, thisArg) { for (var i = this.length - 1; i >= 0; i--) { if (predicate.call(thisArg, this[i], i, this)) return i; } return -1; };
}
var console = typeof console === "undefined" ? {} : console;
console.log = console.warn = console.error = function(message) {
if (typeof message === "object") message = JSON.stringify(message);
sendMessage("log", JSON.stringify([String(message)]));
};
String.prototype.substringAfter = function(pattern) {
const index = this.indexOf(pattern);
return index === -1 ? this.substring(0) : this.substring(index + pattern.length);
};
String.prototype.substringAfterLast = function(pattern) { return this.split(pattern).pop(); };
String.prototype.substringBefore = function(pattern) {
const index = this.indexOf(pattern);
return index === -1 ? this.substring(0) : this.substring(0, index);
};
String.prototype.substringBeforeLast = function(pattern) {
const index = this.lastIndexOf(pattern);
return index === -1 ? this.substring(0) : this.substring(0, index);
};
String.prototype.substringBetween = function(left, right) {
const start = this.indexOf(left);
if (start === -1) return "";
const contentStart = start + left.length;
const end = this.indexOf(right, contentStart);
return end === -1 ? "" : this.substring(contentStart, end);
};
function parseDates(value, dateFormat, dateFormatLocale) {
return JSON.parse(sendMessage("parseDates", JSON.stringify([Array.isArray(value) ? value : [value], dateFormat || "", dateFormatLocale || ""])));
}
$HTML_DOM_JS
function xpathFirst(html, expression) {
return JSON.parse(sendMessage("xpathFirst", JSON.stringify([String(html || ""), String(expression || "")])));
}
function xpathAll(html, expression) {
return JSON.parse(sendMessage("xpathAll", JSON.stringify([String(html || ""), String(expression || "")])));
}
function parseEpub(path) {
return JSON.parse(sendMessage("parseEpub", JSON.stringify([String(path || "")])));
}
function parseEpubChapter(path, index) {
return sendMessage("parseEpubChapter", JSON.stringify([String(path || ""), index | 0]));
}
function cryptoBytesToHex(value) {
if (typeof value === "string") return value;
if (!Array.isArray(value)) return "";
var out = "";
for (var i = 0; i < value.length; i++) {
var part = (Number(value[i]) & 255).toString(16);
out += part.length < 2 ? "0" + part : part;
}
return out;
}
var Crypto = {
aesEncrypt: function(keyHexOrBase64, ivHexOrBase64, plaintext) {
return JSON.parse(sendMessage("cryptoAes", JSON.stringify(["encrypt", keyHexOrBase64, ivHexOrBase64, plaintext])));
},
aesDecrypt: function(keyHexOrBase64, ivHexOrBase64, ciphertext) {
return JSON.parse(sendMessage("cryptoAes", JSON.stringify(["decrypt", keyHexOrBase64, ivHexOrBase64, ciphertext])));
},
aesGcmEncrypt: function(keyHexOrBase64, ivHexOrBase64, plaintextHexOrBase64, additionalDataHexOrBase64) {
return JSON.parse(sendMessage("cryptoAesGcm", JSON.stringify(["encrypt", keyHexOrBase64, ivHexOrBase64, plaintextHexOrBase64, additionalDataHexOrBase64 || ""])));
},
aesGcmDecrypt: function(options, ivHexOrBase64, ciphertextHexOrBase64) {
var key = options;
var iv = ivHexOrBase64;
var data = ciphertextHexOrBase64;
var returnText = false;
if (options && typeof options === "object") {
key = options.key || (options.keyFromSha256 ? this.sha256Hex(options.keyFromSha256) : "");
iv = cryptoBytesToHex(options.iv);
data = cryptoBytesToHex(options.data);
returnText = true;
}
var result = JSON.parse(sendMessage("cryptoAesGcm", JSON.stringify(["decrypt", key, iv, data, options && options.additionalData ? options.additionalData : ""])));
return returnText ? (result ? result.utf8 : null) : result;
},
sha256: function(data) { return JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", data]))); },
sha1: function(data) { return JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-1", data]))); },
md5: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["md5", String(data == null ? "" : data)]))); return r ? r.hex : ""; },
sha256Hex: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", String(data == null ? "" : data)]))); return r ? r.hex : ""; },
sha1Hex: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-1", String(data == null ? "" : data)]))); return r ? r.hex : ""; },
sha256Bytes: function(data) { var r = JSON.parse(sendMessage("cryptoDigest", JSON.stringify(["sha-256", String(data == null ? "" : data)]))); return r ? r.hex : ""; },
hmac: function(algorithm, key, message) { var r = JSON.parse(sendMessage("cryptoHmac", JSON.stringify([String(algorithm || "sha-256"), String(key == null ? "" : key), String(message == null ? "" : message)]))); return r ? r.hex : ""; },
hmacSHA256: function(key, message) { return this.hmac("sha-256", key, message); },
hmacSha256: function(key, message) { return this.hmac("sha-256", key, message); },
hmacSha256Truncated: function(key, message, bytes) { return this.hmac("sha-256", key, message).substring(0, (bytes | 0) * 2); },
hmacSHA1: function(key, message) { return this.hmac("sha-1", key, message); },
base64Encode: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["encode", String(text || "")]))); },
base64Decode: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["decode", String(text || "")]))); },
fromBase64: function(text) { return JSON.parse(sendMessage("cryptoBase64", JSON.stringify(["decode", String(text || "")]))); },
base64ToHex: function(b64) { var s = atob(String(b64 || "")); var out = ""; for (var i = 0; i < s.length; i++) { var h = s.charCodeAt(i).toString(16); out += h.length < 2 ? "0" + h : h; } return out; },
tripleDESEncrypt: function(dataBase64, keyBase64, ivBase64) { var r = JSON.parse(sendMessage("cryptoDes", JSON.stringify(["encrypt", String(keyBase64 || ""), String(ivBase64 || ""), String(dataBase64 || "")]))); return r ? r.base64 : ""; },
encrypt3DESCBC: function(dataBase64, keyBase64, ivBase64) { return this.tripleDESEncrypt(dataBase64, keyBase64, ivBase64); }
};
var Extractors = {
extract: function(host, url, headers) {
return JSON.parse(sendMessage("extractVideo", JSON.stringify([String(host || ""), String(url || ""), headers || {}])));
}
};
// Promise-aware JSON.stringify helper. Extensions can pass either synchronous or asynchronous
// producer functions; QuickJS drains the resulting promise jobs before evaluation returns.
function jsonStringify(fn) {
var result = fn();
if (result && typeof result.then === "function") {
return result.then(function(v) { return JSON.stringify(v); });
}
return JSON.stringify(result);
}
function MProvider() {}
Object.defineProperty(MProvider.prototype, "source", { get: function() { return ${source.toMSourceJson()}; }, configurable: true });
Object.defineProperty(MProvider.prototype, "supportsLatest", { get: function() { throw new Error("supportsLatest not implemented"); }, configurable: true });
// Default methods stay synchronous; subclasses may freely override them with async methods.
MProvider.prototype.getHeaders = function(url) { throw new Error("getHeaders not implemented"); };
MProvider.prototype.getPopular = function(page) { throw new Error("getPopular not implemented"); };
MProvider.prototype.getLatestUpdates = function(page) { throw new Error("getLatestUpdates not implemented"); };
MProvider.prototype.search = function(query, page, filters) { throw new Error("search not implemented"); };
MProvider.prototype.getDetail = function(url) { throw new Error("getDetail not implemented"); };
MProvider.prototype.getPageList = function(url) { throw new Error("getPageList not implemented"); };
MProvider.prototype.getVideoList = function(url) { throw new Error("getVideoList not implemented"); };
MProvider.prototype.getHtmlContent = function(name, url) { throw new Error("getHtmlContent not implemented"); };
MProvider.prototype.cleanHtmlContent = function(html) { throw new Error("cleanHtmlContent not implemented"); };
MProvider.prototype.getFilterList = function() { return []; };
MProvider.prototype.getSourcePreferences = function() { return []; };
""".trimIndent()
private fun DbSource.toMSourceJson(): JsonObject = buildJsonObject {
put("apiUrl", JsonPrimitive(apiUrl))
put("baseUrl", JsonPrimitive(baseUrl))
put("dateFormat", JsonPrimitive(dateFormat))
put("dateFormatLocale", JsonPrimitive(dateFormatLocale))
put("hasCloudflare", JsonPrimitive(hasCloudflare))
put("id", JsonPrimitive(id))
put("isFullData", JsonPrimitive(isFullData))
put("lang", JsonPrimitive(lang))
put("name", JsonPrimitive(name))
put("additionalParams", JsonPrimitive(additionalParams))
put("notes", JsonPrimitive(notes))
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptEngine.kt
- Source · implementation · 23 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: fun interface JavaScriptMessageBridge {
4: fun sendMessage(channel: String, payload: String): String
12: interface JavaScriptEngine {
13: fun evaluate(script: String, isCancelled: () -> Boolean = { false }): String
15: fun close()
23: expect fun createJavaScriptEngine(bridge: JavaScriptMessageBridge): JavaScriptEngine
Exact file bytes / download · SHA-256 425b199e3532538a4bc03c8dfc27bacf1487eb22c2823657ca9a720540117800.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
fun interface JavaScriptMessageBridge {
fun sendMessage(channel: String, payload: String): String
}
/**
* A single JavaScript context. [evaluate] blocks until the script (including synchronous host
* bridge calls) finishes, so callers run it on a background dispatcher; [close] must not block.
* The engine interrupts the script once [isCancelled] returns true.
*/
interface JavaScriptEngine {
fun evaluate(script: String, isCancelled: () -> Boolean = { false }): String
fun close()
}
/**
* JavaScript engine for extension sources. QuickJS (zipline) on
* Android/desktop/iOS; unsupported on the browser, where zipline has no
* wasm artifact — the actual throws from `evaluate`.
*/
expect fun createJavaScriptEngine(bridge: JavaScriptMessageBridge): JavaScriptEngine
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptExtensionRuntime.kt
- Source · implementation · 327 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
36: class JavaScriptExtensionRuntimeService(
59: override suspend fun supportsLatest(): Boolean =
64: override fun dispose() = host.close()
66: override suspend fun headers(): Map<String, String> = catchingNonCancellation {
70: override suspend fun popular(page: Int): SourceListing =
73: override suspend fun latest(page: Int): SourceListing =
76: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
81: override suspend fun detail(url: String): RemoteDetail {
89: override suspend fun related(url: String): eu.friedcutlet.yokan.services.extensions.SourceRelations {
95: override suspend fun pageList(url: String): List<DbPageUrl> =
98: override suspend fun videoList(url: String): List<DbVideo> =
101: override suspend fun htmlContent(name: String, url: String): String =
104: override suspend fun cleanHtmlContent(html: String): String =
107: override suspend fun filterList(): List<SourceFilter> = catchingNonCancellation {
111: override suspend fun sourcePreferences(): List<SourcePreferenceValue> = catchingNonCancellation {
115: private suspend fun callJson(expression: String): JsonElement {
126: private suspend fun callJsonOnce(expression: String): JsonElement {
145: private fun Throwable.isRecoverableQuickJsFailure(): Boolean {
153: private fun extensionChannel(channel: String, payload: String): String? = when (channel) {
169: private fun parseDatesBridge(payload: String): String {
181: private fun xpathBridge(channel: String, payload: String): String {
193: private fun parseEpubBridge(payload: String): String {
213: private fun parseEpubChapterBridge(payload: String): String {
222: private fun evaluateJavascriptViaWebview(payload: String): String {
234: private fun extractVideoBridge(payload: String): String {
261: private fun coerceDateToMillis(raw: String, format: String): Long {
284: private fun relativeDateOffsetMillis(value: String): Long? {
300: private fun decodeFromFormat(numbers: List<String>, format: String): Triple<Int, Int, Int> {
316: private fun approximateMillisFor(year: Int, month: Int, day: Int): Long {
Exact file bytes / download · SHA-256 a9b40b08a574ceb81db11a867d1898b54ebe38d9e8c7d3c756c8550bd4adb5d5.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.media.AnimeExtractorService
import eu.friedcutlet.yokan.services.webview.WebViewService
import eu.friedcutlet.yokan.util.nowMillis
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
private val IsoDatePattern = Regex("(\\d{4})-(\\d{1,2})-(\\d{1,2})")
private val DigitsPattern = Regex("\\d+")
private val RelativeDatePattern = Regex("(\\d+)\\s*(second|minute|hour|day|week|month|year)s?\\s*ago")
private val NonLetterPattern = Regex("[^a-z]+")
/**
* Runtime for Mangayomi-style JavaScript extensions. The extension is evaluated once per runtime
* on top of [javaScriptBootstrap]; [JavaScriptHost] owns the engine and its threading.
*/
class JavaScriptExtensionRuntimeService(
override val source: DbSource,
http: HttpService,
database: YokanDatabase? = null,
engineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine = ::createJavaScriptEngine,
private val archives: LocalArchiveService? = null,
private val webView: WebViewService? = null,
private val animeExtractors: List<AnimeExtractorService> = emptyList(),
) : ExtensionRuntimeService {
private val host = JavaScriptHost(
source = source,
http = http,
database = database,
engineFactory = engineFactory,
boot = { engine ->
engine.evaluate(javaScriptBootstrap(source))
// QuickJS accepts the extension's modern ECMAScript directly.
engine.evaluate(synchronousJavaScriptSource(source.sourceCode))
engine.evaluate("var extention = new DefaultExtension();")
},
channels = ::extensionChannel,
)
override suspend fun supportsLatest(): Boolean =
catchingNonCancellation { callJson("extention.supportsLatest").primitiveOrNull()?.booleanOrNull }
.getOrNull()
?: (source.supportLatest == true)
override fun dispose() = host.close()
override suspend fun headers(): Map<String, String> = catchingNonCancellation {
headersFromJsonElement(callJson("extention.getHeaders(${source.baseUrl.quoted()})"))
}.getOrElse { parseHeaders(source.headers) }
override suspend fun popular(page: Int): SourceListing =
listingFromJson(callJson("extention.getPopular($page)"))
override suspend fun latest(page: Int): SourceListing =
listingFromJson(callJson("extention.getLatestUpdates($page)"))
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
listingFromJson(
callJson("extention.search(${query.quoted()}, $page, ${sourceFiltersToJson(filters)})"),
)
override suspend fun detail(url: String): RemoteDetail {
val detail = callJson("extention.getDetail(${url.quoted()})")
if (!detail.isSeasonsDetail()) return remoteDetailFromJson(detail)
// Optional `getSeasonList(url)`; otherwise inline `seasons` from the detail response.
val listed = callJson("typeof extention.getSeasonList === 'function'").primitiveOrNull()?.booleanOrNull == true
return remoteDetailFromJson(detail, seasonsOverride = if (listed) seasonListFromJson(callJson("extention.getSeasonList(${url.quoted()})")) else null)
}
override suspend fun related(url: String): eu.friedcutlet.yokan.services.extensions.SourceRelations {
val supported = callJson("typeof extention.getRelated === 'function'").primitiveOrNull()?.booleanOrNull == true
if (!supported) return eu.friedcutlet.yokan.services.extensions.SourceRelations(false)
return sourceRelationsFromJson(callJson("extention.getRelated(${url.quoted()})"), source.baseUrl)
}
override suspend fun pageList(url: String): List<DbPageUrl> =
callJson("extention.getPageList(${url.quoted()})").arrayOrEmpty().mapNotNull(::pageUrlFromJson)
override suspend fun videoList(url: String): List<DbVideo> =
callJson("extention.getVideoList(${url.quoted()})").arrayOrEmpty().mapNotNull(::videoFromJson)
override suspend fun htmlContent(name: String, url: String): String =
callJson("extention.getHtmlContent(${name.quoted()}, ${url.quoted()})").primitiveOrNull()?.contentOrNull.orEmpty()
override suspend fun cleanHtmlContent(html: String): String =
callJson("extention.cleanHtmlContent(${html.quoted()})").primitiveOrNull()?.contentOrNull ?: html
override suspend fun filterList(): List<SourceFilter> = catchingNonCancellation {
filtersFromJson(callJson("extention.getFilterList()"))
}.getOrElse { filtersFromJson(source.filterList) }
override suspend fun sourcePreferences(): List<SourcePreferenceValue> = catchingNonCancellation {
sourcePreferencesFromJson(callJson("extention.getSourcePreferences()"))
}.getOrElse { sourcePreferencesFromJson(source.preferenceList) }
private suspend fun callJson(expression: String): JsonElement {
repeat(3) { attempt ->
try {
return callJsonOnce(expression)
} catch (error: Throwable) {
if (attempt >= 2 || !error.isRecoverableQuickJsFailure()) throw error
}
}
error("Unreachable")
}
private suspend fun callJsonOnce(expression: String): JsonElement {
// Parse on the engine's background lane too; listings can be large.
val result = host.call { engine ->
val raw = engine.evaluate(
"""
var __yokanValue = $expression;
if (__yokanValue != null && typeof __yokanValue.then === "function") {
throw new Error(
"Extension methods must return synchronously; Yokan's Client APIs already return completed values."
);
}
JSON.stringify(__yokanValue === undefined ? null : __yokanValue);
""".trimIndent(),
)
if (raw.isBlank()) null else parseJsonElement(raw) ?: JsonNull
}
return result ?: throw IllegalStateException("JavaScript call returned no result: $expression")
}
private fun Throwable.isRecoverableQuickJsFailure(): Boolean {
val detail = generateSequence(this) { it.cause }
.joinToString(" ") { it.message.orEmpty() }
.lowercase()
return "stack overflow" in detail || "redeclaration of" in detail
}
/** Mangayomi-specific bridge channels; shared ones are answered by [JavaScriptHost]. */
private fun extensionChannel(channel: String, payload: String): String? = when (channel) {
"parseDates" -> parseDatesBridge(payload)
"xpathFirst", "xpathAll" -> xpathBridge(channel, payload)
"evaluateJavascriptViaWebview" -> evaluateJavascriptViaWebview(payload)
"parseEpub" -> parseEpubBridge(payload)
"parseEpubChapter" -> parseEpubChapterBridge(payload)
"cryptoAes" -> CryptoBridge.aes(payload)
"cryptoAesGcm" -> CryptoBridge.aesGcm(payload)
"cryptoDigest" -> CryptoBridge.digest(payload)
"cryptoBase64" -> CryptoBridge.base64(payload)
"cryptoHmac" -> CryptoBridge.hmac(payload)
"cryptoDes" -> CryptoBridge.tripleDes(payload)
"extractVideo" -> extractVideoBridge(payload)
else -> null
}
private fun parseDatesBridge(payload: String): String {
val args = payloadArray(payload)
val rawDates = args.getOrNull(0)
?.arrayOrEmpty()
?.mapNotNull { it.primitiveOrNull()?.contentOrNull }
.orEmpty()
val format = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
return buildJsonArray {
rawDates.forEach { add(JsonPrimitive(coerceDateToMillis(it, format))) }
}.toString()
}
private fun xpathBridge(channel: String, payload: String): String {
val args = payloadArray(payload)
val html = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val expression = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
val matches = HtmlXPathMatcher.match(html, expression)
return if (channel == "xpathFirst") {
matches.firstOrNull()?.let { JsonPrimitive(it).toString() } ?: "null"
} else {
buildJsonArray { matches.forEach { add(JsonPrimitive(it)) } }.toString()
}
}
private fun parseEpubBridge(payload: String): String {
val args = payloadArray(payload)
val path = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
if (path.isBlank()) return "null"
val archive = archives ?: return "null"
val chapters = archive.listEpubChapters(path)
return buildJsonObject {
put("path", JsonPrimitive(path))
put("chapters", buildJsonArray {
chapters.forEachIndexed { index, chapter ->
add(buildJsonObject {
put("index", JsonPrimitive(index))
put("title", JsonPrimitive(chapter.title))
put("href", JsonPrimitive(chapter.href))
})
}
})
}.toString()
}
private fun parseEpubChapterBridge(payload: String): String {
val args = payloadArray(payload)
val path = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val index = args.getOrNull(1)?.primitiveOrNull()?.intOrNull ?: 0
if (path.isBlank()) return ""
val archive = archives ?: return ""
return archive.readEpubChapter(path, index)
}
private fun evaluateJavascriptViaWebview(payload: String): String {
val args = payloadArray(payload)
val url = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val script = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
if (url.isBlank() || script.isBlank()) return ""
val webView = webView ?: return ""
val userAgent = args.getOrNull(2)?.primitiveOrNull()?.contentOrNull
return catchingNonCancellation {
host.blockingBridgeCall { webView.evaluateScript(url, script, userAgent) }
}.getOrDefault("")
}
private fun extractVideoBridge(payload: String): String {
val args = payloadArray(payload)
val hostName = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val url = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
val headers = args.getOrNull(2)?.objectOrNull().orEmpty()
.mapValues { it.value.primitiveOrNull()?.contentOrNull.orEmpty() }
if (hostName.isBlank() || url.isBlank()) return "null"
val extractor = animeExtractors.firstOrNull { it.hostName.equals(hostName, ignoreCase = true) }
?: return "null"
val result = catchingNonCancellation { host.blockingBridgeCall { extractor.extract(url, headers) } }.getOrNull()
?: return "null"
return buildJsonObject {
put("videos", buildJsonArray {
result.videos.forEach { video ->
add(buildJsonObject {
put("url", JsonPrimitive(video.url))
put("quality", JsonPrimitive(video.quality))
put("originalUrl", JsonPrimitive(video.originalUrl))
})
}
})
put("headers", buildJsonObject {
result.headers.forEach { (key, value) -> put(key, JsonPrimitive(value)) }
})
}.toString()
}
private fun coerceDateToMillis(raw: String, format: String): Long {
if (raw.isBlank()) return 0L
raw.toLongOrNull()?.let { return it }
val now = nowMillis()
val lower = raw.lowercase().trim()
relativeDateOffsetMillis(lower)?.let { return now - it }
// Recognize simple ISO yyyy-MM-dd
val isoMatch = IsoDatePattern.find(raw)
if (isoMatch != null) {
val (y, m, d) = isoMatch.destructured
return approximateMillisFor(y.toInt(), m.toInt(), d.toInt())
}
// Try the dotted format from the extension if provided.
if (format.isNotBlank()) {
val numbers = DigitsPattern.findAll(raw).map { it.value }.toList()
if (numbers.size >= 3) {
val (y, m, d) = decodeFromFormat(numbers, format)
if (y > 0) return approximateMillisFor(y, m, d)
}
}
return now
}
private fun relativeDateOffsetMillis(value: String): Long? {
val match = RelativeDatePattern.find(value) ?: return null
val amount = match.groupValues[1].toLongOrNull() ?: return null
val unitMs = when (match.groupValues[2]) {
"second" -> 1_000L
"minute" -> 60_000L
"hour" -> 3_600_000L
"day" -> 86_400_000L
"week" -> 7L * 86_400_000L
"month" -> 30L * 86_400_000L
"year" -> 365L * 86_400_000L
else -> return null
}
return amount * unitMs
}
private fun decodeFromFormat(numbers: List<String>, format: String): Triple<Int, Int, Int> {
val tokens = format.lowercase().split(NonLetterPattern).filter { it.isNotBlank() }
var y = 0
var m = 0
var d = 0
tokens.forEachIndexed { index, token ->
val numberValue = numbers.getOrNull(index)?.toIntOrNull() ?: return@forEachIndexed
when {
token.startsWith("y") -> y = numberValue
token.startsWith("m") -> m = numberValue
token.startsWith("d") -> d = numberValue
}
}
return Triple(y, m, d)
}
private fun approximateMillisFor(year: Int, month: Int, day: Int): Long {
if (year <= 0) return nowMillis()
// Days since 1970-01-01, approximate (no leap-year correction beyond modulo 4).
var days = (year - 1970).toLong() * 365 + ((year - 1969) / 4)
val daysPerMonth = intArrayOf(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
for (i in 0 until (month - 1).coerceAtLeast(0)) {
days += daysPerMonth.getOrNull(i) ?: 30
}
days += (day - 1).coerceAtLeast(0)
return days * 86_400_000L
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptHost.kt
- Source · implementation · 210 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
37: internal class JavaScriptHost(
61: suspend fun <T> call(block: (JavaScriptEngine) -> T): T = mutex.withLock {
87: fun <T> blockingBridgeCall(block: suspend () -> T): T =
91: fun close() {
97: private fun bootEngine(): JavaScriptEngine {
100: object : JavaScriptEngine by raw {
101: override fun evaluate(script: String, isCancelled: () -> Boolean): String =
115: private fun sendMessage(channel: String, payload: String): String = when (channel) {
138: private fun preferenceValue(payload: String): String {
145: private fun storedPreference(key: String): String? = if (database == null) {
153: private fun setPreferenceValue(payload: String): String {
170: private fun querySelectorBridge(channel: String, payload: String): String {
185: private fun httpRequestFromMessage(channel: String, payload: String): HttpRequest {
202: private fun HttpResponse.toJson(): JsonObject = buildJsonObject {
Exact file bytes / download · SHA-256 e6eb235074c8418507f3eeeb336a1b9c70dfa213849a17579c51a97c9e11c3fc.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourcePreference
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.blockingDispatcher
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.extensions.ExtensionLogger
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.runBlockingCompat
import kotlinx.coroutines.Job
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.job
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlin.concurrent.Volatile
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
/**
* Owns one extension's JavaScript engine and the host side of its `__bridge`.
*
* The engine boots lazily through [boot]. Every [call] is serialized by a per-host [Mutex] and runs
* on [blockingDispatcher], so runtimes may be invoked from the main thread. A failed call closes the
* engine so the next call boots a fresh one. Channels shared by every extension flavour (HTTP, log,
* preferences, CSS selectors) are answered here, runtime-specific ones by [channels]; unknown
* channels fail loudly.
*/
internal class JavaScriptHost(
private val source: DbSource,
private val http: HttpService,
private val database: YokanDatabase?,
private val engineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine,
private val boot: (JavaScriptEngine) -> Unit,
private val channels: (channel: String, payload: String) -> String? = { _, _ -> null },
) {
private val mutex = Mutex()
private var engine: JavaScriptEngine? = null
// The job of the call holding [mutex]; QuickJS polls it from its own thread.
@Volatile
private var callerJob: Job? = null
private val sourcePreferenceDefaults by lazy {
buildMap<String, String> {
sourcePreferencesFromJson(source.preferenceList).forEach { getOrPut(it.key) { it.value } }
}
}
// Values written while no database is attached; with a database, the settings are the source of truth.
private val detachedPreferences = mutableMapOf<String, String>()
suspend fun <T> call(block: (JavaScriptEngine) -> T): T = mutex.withLock {
withContext(blockingDispatcher) {
callerJob = coroutineContext.job
try {
val current = engine ?: bootEngine()
try {
block(current)
} catch (error: Throwable) {
close()
throw error
}
} catch (error: Throwable) {
// A cancelled call fails with the engine's interrupt error; report the cancellation instead.
ensureActive()
throw error
} finally {
callerJob = null
}
}
}
/**
* Blocks a bridge callback on [block] as a child of the current [call], so cancelling the call
* cancels it too. Failures are rethrown outside the child so they reach JavaScript without
* cancelling the call.
*/
fun <T> blockingBridgeCall(block: suspend () -> T): T =
runBlockingCompat(callerJob ?: EmptyCoroutineContext) { catchingNonCancellation { block() } }.getOrThrow()
/** Closes the engine. Must not race [call]; the runtime cache only disposes idle runtimes. */
fun close() {
val current = engine ?: return
engine = null
runCatching { current.close() }
}
private fun bootEngine(): JavaScriptEngine {
check(source.sourceCode.isNotBlank()) { "${source.name} does not contain JavaScript source code." }
val created = engineFactory(JavaScriptMessageBridge(::sendMessage)).let { raw ->
object : JavaScriptEngine by raw {
override fun evaluate(script: String, isCancelled: () -> Boolean): String =
raw.evaluate(script) { isCancelled() || callerJob?.isCancelled == true }
}
}
try {
boot(created)
} catch (error: Throwable) {
runCatching { created.close() }
throw error
}
engine = created
return created
}
private fun sendMessage(channel: String, payload: String): String = when (channel) {
"http_head", "http_get", "http_post", "http_put", "http_delete", "http_patch" -> {
val request = httpRequestFromMessage(channel, payload)
// ponytail: QuickJS host functions are synchronous (zipline exposes no promise/job-queue API
// to host bindings), so HTTP blocks the engine's background lane until the response arrives.
// Non-blocking needs promise-returning host calls plus a job pump in the engine. On wasm
// the engine itself is unsupported, so this is never reached there.
blockingBridgeCall { http.request(request) }.toJson().toString()
}
"log" -> {
val message = payloadArray(payload).joinToString(" ") { element ->
element.primitiveOrNull()?.contentOrNull.orEmpty()
}
if (message.isNotBlank()) ExtensionLogger.log(source.name, message)
"null"
}
"get", "getString" -> preferenceValue(payload)
"setString" -> setPreferenceValue(payload)
"querySelector", "querySelectorAll" -> querySelectorBridge(channel, payload)
else -> channels(channel, payload)
?: throw UnsupportedOperationException("JavaScript bridge channel '$channel' is not ported yet.")
}
private fun preferenceValue(payload: String): String {
val args = payloadArray(payload)
val key = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val defaultValue = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
return storedPreference(key) ?: sourcePreferenceDefaults[key] ?: defaultValue
}
private fun storedPreference(key: String): String? = if (database == null) {
detachedPreferences[key]
} else {
database.settings().sourcePreferences.orEmpty()
.lastOrNull { it.sourceId == source.id && it.key == key }
?.value
}
private fun setPreferenceValue(payload: String): String {
val args = payloadArray(payload)
val key = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val value = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
if (key.isBlank()) return value
if (database == null) {
detachedPreferences[key] = value
} else {
val settings = database.settings()
val others = settings.sourcePreferences.orEmpty().filterNot { it.sourceId == source.id && it.key == key }
database.updateSettings(
settings.copy(sourcePreferences = others + DbSourcePreference(sourceId = source.id, key = key, value = value)),
)
}
return value
}
private fun querySelectorBridge(channel: String, payload: String): String {
val args = payloadArray(payload)
val html = args.getOrNull(0)?.primitiveOrNull()?.contentOrNull.orEmpty()
val selector = args.getOrNull(1)?.primitiveOrNull()?.contentOrNull.orEmpty()
if (html.isBlank() || selector.isBlank()) return "[]"
val matches = HtmlSelectorMatcher.match(html, selector)
return if (channel == "querySelector") {
matches.firstOrNull()?.let { JsonPrimitive(it).toString() } ?: "null"
} else {
buildJsonArray { matches.forEach { add(JsonPrimitive(it)) } }.toString()
}
}
}
/** Decodes the `[null, reqcopyWith, url, headers, body]` payload sent by the bootstraps' HTTP clients. */
private fun httpRequestFromMessage(channel: String, payload: String): HttpRequest {
val args = payloadArray(payload)
val url = args.getOrNull(2)?.primitiveOrNull()?.contentOrNull
?: throw IllegalArgumentException("Missing JavaScript HTTP url")
val body = when (val bodyElement = args.getOrNull(4)) {
null, JsonNull -> null
is JsonPrimitive -> bodyElement.contentOrNull
else -> bodyElement.toString()
}
return HttpRequest(
url = url,
method = channel.removePrefix("http_").uppercase(),
headers = headersFromJsonElement(args.getOrNull(3)),
body = body,
)
}
private fun HttpResponse.toJson(): JsonObject = buildJsonObject {
put("body", JsonPrimitive(body))
put("statusCode", JsonPrimitive(statusCode))
put("headers", buildJsonObject { headers.forEach { (key, value) -> put(key, JsonPrimitive(value)) } })
put("isRedirect", JsonPrimitive(statusCode in 300..399))
put("persistentConnection", JsonPrimitive(false))
put("reasonPhrase", JsonPrimitive(""))
put("request", buildJsonObject {})
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptSourceNormalization.kt
- Source · implementation · 179 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal fun synchronousJavaScriptSource(sourceCode: String): String {
45: private class JavaScriptCodeMask(private val source: String) {
50: fun build(): String {
55: private fun hide(start: Int, end: Int, comment: Boolean = false) {
61: private fun quoted(start: Int, quote: Char): Int {
73: private fun template(start: Int): Int {
95: private fun regexEnd(start: Int): Int? {
113: private fun code(start: Int, interpolation: Boolean): Int {
Exact file bytes / download · SHA-256 d5d94eb7b9b48e08b9ec9e99b11a3ff252628db9c41c8bfa55e81c821f0adb24.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
private val AsyncKeyword = Regex(
"""\basync\b(?=\s*(?:function\b|[A-Za-z_$][A-Za-z0-9_$]*\s*\(|\([^)]*\)\s*=>|[A-Za-z_$][A-Za-z0-9_$]*\s*=>))""",
)
private val AwaitKeyword = Regex("""\bawait\b(?!\s*[:=])""")
private val AwaitMethod = Regex("""\([^)]*\)\s*\{""")
/** Host APIs complete synchronously. Remove modifiers only from code, never scraped text or patterns. */
internal fun synchronousJavaScriptSource(sourceCode: String): String {
if (!sourceCode.contains("async") && !sourceCode.contains("await")) return sourceCode
val code = JavaScriptCodeMask(sourceCode).build()
val removed = BooleanArray(sourceCode.length)
for (pattern in listOf(AsyncKeyword, AwaitKeyword)) {
for (match in pattern.findAll(code)) {
var before = match.range.first - 1
while (before >= 0 && code[before].isWhitespace()) before--
val previous = code.getOrNull(before)
if (previous == '.') continue // Object members named async / await are ordinary identifiers.
if (code.getOrNull(match.range.first - 1) == '$' || code.getOrNull(match.range.last + 1) == '$') continue
if (pattern === AwaitKeyword) {
var after = match.range.last + 1
while (after < code.length && code[after].isWhitespace()) after++
if (code.getOrNull(after) in listOf(null, '}', ',', ';', ')', ']')) continue
// An object/class method named await is not an await expression.
if (code.getOrNull(after) == '(' && AwaitMethod.matchAt(code, after) != null) continue
}
var end = match.range.last + 1
while (end < sourceCode.length && sourceCode[end] in " \t") end++
if (pattern === AwaitKeyword) {
var triviaEnd = end
while (triviaEnd < code.length && code[triviaEnd].isWhitespace()) triviaEnd++
// Removing await must not introduce a newline after return/throw (automatic semicolon insertion).
if ((end until triviaEnd).any { sourceCode[it] == '\n' || sourceCode[it] == '\r' }) end = triviaEnd
}
for (index in match.range.first until end) removed[index] = true
}
}
return buildString(sourceCode.length) {
sourceCode.forEachIndexed { index, char -> if (!removed[index]) append(char) }
}
}
/** A lexical mask retains code offsets, including expressions nested inside template literals. */
private class JavaScriptCodeMask(private val source: String) {
private val mask = source.toCharArray()
private val expressionKeywords = setOf("return", "throw", "case", "delete", "void", "typeof", "new", "in", "of", "yield", "await", "else", "do", "instanceof")
private val controlKeywords = setOf("if", "while", "for", "with", "switch", "catch")
fun build(): String {
code(0, interpolation = false)
return mask.concatToString()
}
private fun hide(start: Int, end: Int, comment: Boolean = false) {
for (index in start until end) {
if (source[index] != '\n' && source[index] != '\r') mask[index] = if (comment) ' ' else '#'
}
}
private fun quoted(start: Int, quote: Char): Int {
var index = start + 1
while (index < source.length) {
when (source[index++]) {
'\\' -> if (index < source.length) index++
quote -> break
}
}
hide(start, index)
return index
}
private fun template(start: Int): Int {
var index = start + 1
var chunk = start
while (index < source.length) {
when {
source[index] == '\\' -> index = (index + 2).coerceAtMost(source.length)
source[index] == '`' -> {
hide(chunk, index + 1)
return index + 1
}
source[index] == '$' && source.getOrNull(index + 1) == '{' -> {
hide(chunk, index + 2)
index = code(index + 2, interpolation = true)
chunk = index
}
else -> index++
}
}
hide(chunk, index)
return index
}
private fun regexEnd(start: Int): Int? {
var index = start + 1
var characterClass = false
while (index < source.length) {
when (source[index++]) {
'\n', '\r' -> return null
'\\' -> if (index < source.length) index++
'[' -> characterClass = true
']' -> characterClass = false
'/' -> if (!characterClass) {
while (index < source.length && source[index].isLetter()) index++
return index
}
}
}
return null
}
private fun code(start: Int, interpolation: Boolean): Int {
var index = start
var braces = 0
var regexAllowed = true
var previousWord = ""
var previousToken = ""
val controlParentheses = mutableListOf<Boolean>()
val objectBraces = mutableListOf<Boolean>()
while (index < source.length) {
val char = source[index]
when {
char.isWhitespace() -> { index++; continue }
char == '\'' || char == '"' -> { index = quoted(index, char); regexAllowed = false }
char == '`' -> { index = template(index); regexAllowed = false }
char == '/' && source.getOrNull(index + 1) == '/' -> {
val end = source.indexOf('\n', index).let { if (it < 0) source.length else it }
hide(index, end, comment = true); index = end; continue
}
char == '/' && source.getOrNull(index + 1) == '*' -> {
val end = source.indexOf("*/", index + 2).let { if (it < 0) source.length else it + 2 }
hide(index, end, comment = true); index = end; continue
}
char == '/' && regexAllowed && regexEnd(index) != null -> {
val end = requireNotNull(regexEnd(index))
hide(index, end); index = end; regexAllowed = false
}
char.isLetter() || char == '_' || char == '$' -> {
val begin = index++
while (index < source.length && (source[index].isLetterOrDigit() || source[index] == '_' || source[index] == '$')) index++
previousWord = source.substring(begin, index)
previousToken = previousWord
regexAllowed = previousWord in expressionKeywords
continue
}
char.isDigit() -> {
index++
while (index < source.length && (source[index].isLetterOrDigit() || source[index] in "._")) index++
regexAllowed = false
}
else -> {
index++
when (char) {
'(' -> { controlParentheses += previousWord in controlKeywords; regexAllowed = true }
')' -> { regexAllowed = controlParentheses.removeLastOrNull() == true }
'{' -> {
objectBraces += previousToken in setOf("=", "(", "[", ",", ":", "return") || (interpolation && index - 1 == start)
braces++; regexAllowed = true
}
'}' -> {
if (braces == 0 && interpolation) { hide(index - 1, index); return index }
braces--; regexAllowed = objectBraces.removeLastOrNull() != true
}
']', '.' -> regexAllowed = false
'+', '-' -> {
if (source.getOrNull(index) == char) { index++; regexAllowed = false }
else regexAllowed = true
}
else -> regexAllowed = true
}
}
}
previousToken = source.substring((index - 1).coerceAtLeast(start), index)
previousWord = ""
}
return index
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/SourceRelationsCodec.kt
- Source · implementation · 41 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal fun sourceRelationsFromJson(element: JsonElement, baseUrl: String): SourceRelations {
15: fun JsonObject.text(vararg keys: String) = keys.firstNotNullOfOrNull { key ->
Exact file bytes / download · SHA-256 2b25a823fbbd8f9471e5cca24fd347570174d13fa17d27712b2eb99f018c3486.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceRelatedGroup
import eu.friedcutlet.yokan.services.extensions.SourceRelations
import eu.friedcutlet.yokan.services.extensions.sourceImageUrl
import kotlinx.serialization.json.*
/** Bounded groups with stable source URLs; repeated labels merge without duplicate entries. */
internal fun sourceRelationsFromJson(element: JsonElement, baseUrl: String): SourceRelations {
val root = element as? JsonArray ?: error("The source returned invalid related entries")
require(root.size <= 50) { "The source returned too many relation groups" }
val groups = linkedMapOf<String, LinkedHashMap<String, RemoteManga>>()
var count = 0L
fun JsonObject.text(vararg keys: String) = keys.firstNotNullOfOrNull { key ->
(this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content?.trim()?.takeIf(String::isNotEmpty)
}
root.forEach { value ->
val group = value as? JsonObject ?: return@forEach
val rows = (group["animes"] ?: group["items"]) as? JsonArray ?: return@forEach
count += rows.size.toLong()
require(count <= 1_000) { "The source returned too many related entries" }
val name = group.text("name") ?: return@forEach
val items = groups.getOrPut(name) { linkedMapOf() }
rows.forEach row@{ element ->
val row = element as? JsonObject ?: return@row
val title = row.text("name", "title") ?: return@row
val url = row.text("link", "url") ?: return@row
if (url.any { it <= ' ' || it == '\\' || it == '\u007f' }) return@row
if (RelationScheme.containsMatchIn(url) && !url.startsWith("https://", true) && !url.startsWith("http://", true)) return@row
if ((RelationScheme.containsMatchIn(url) || url.startsWith("//")) && sourceImageUrl(url, baseUrl) == null) return@row
val image = row.text("imageUrl", "thumbnailUrl", "thumbnail_url")
if (url !in items) items[url] = RemoteManga(title, url, sourceImageUrl(image, baseUrl), row.text("description"), initialized = true)
}
}
return SourceRelations(true, groups.mapNotNull { (name, items) ->
items.values.takeIf { it.isNotEmpty() }?.let { SourceRelatedGroup(name, it.toList()) }
})
}
private val RelationScheme = Regex("^[A-Za-z][A-Za-z0-9+.-]*:")
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/lnreader/LnReaderBootstrap.kt
- Source · implementation · 161 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Exact file bytes / download · SHA-256 98ce7b0e9dbdc9d5c0d763a87380be9a48697f7416bf1302caf647cb8ebf7c72.
Complete file
package eu.friedcutlet.yokan.services.extensions.lnreader
import eu.friedcutlet.yokan.services.extensions.js.HTML_DOM_JS
/** LNReader's CommonJS modules run with synchronous HTTP, DOM and Promise adapters. */
internal val lnReaderBootstrap = HTML_DOM_JS + """
function LnPromise(executor) {
var self = this;
self.state = 0; self.value = undefined; self.handlers = [];
function settle(state, value) {
if (self.state) return;
if (state === 1 && value && typeof value.then === 'function') {
if (value === self) return settle(2, new TypeError('Promise resolved to itself'));
return value.then(function(v) { settle(1, v); }, function(e) { settle(2, e); });
}
self.state = state; self.value = value;
self.handlers.splice(0).forEach(function(handler) { handler(); });
}
try { executor(function(v) { settle(1, v); }, function(e) { settle(2, e); }); }
catch (e) { settle(2, e); }
}
LnPromise.prototype.then = function(success, failure) {
var self = this;
return new LnPromise(function(resolve, reject) {
function run() {
var callback = self.state === 1 ? success : failure;
if (typeof callback !== 'function') return (self.state === 1 ? resolve : reject)(self.value);
try { resolve(callback(self.value)); } catch (e) { reject(e); }
}
if (self.state) run(); else self.handlers.push(run);
});
};
LnPromise.prototype.catch = function(failure) { return this.then(undefined, failure); };
LnPromise.prototype.finally = function(callback) {
return this.then(function(value) { return LnPromise.resolve(callback()).then(function() { return value; }); },
function(error) { return LnPromise.resolve(callback()).then(function() { throw error; }); });
};
LnPromise.resolve = function(value) { return value instanceof LnPromise ? value : new LnPromise(function(resolve) { resolve(value); }); };
LnPromise.reject = function(error) { return new LnPromise(function(resolve, reject) { reject(error); }); };
LnPromise.all = function(values) {
return new LnPromise(function(resolve, reject) {
var result = [], remaining = values.length;
if (!remaining) return resolve(result);
values.forEach(function(value, index) { LnPromise.resolve(value).then(function(v) {
result[index] = v; if (!--remaining) resolve(result);
}, reject); });
});
};
function lnReaderResult(value) {
if (value && typeof value.then === 'function') {
var complete = false, failure = false, result;
value.then(function(v) { complete = true; result = v; }, function(e) { complete = true; failure = true; result = e; });
if (!complete) throw new Error('LNReader plugin returned an unsupported asynchronous operation');
if (failure) throw result;
value = result;
}
return JSON.stringify(value === undefined ? null : value);
}
function LnFormData() { this.fields = []; }
LnFormData.prototype.append = function(name, value) { this.fields.push([String(name), String(value)]); };
LnFormData.prototype.toString = function() { return this.fields.map(function(pair) {
return encodeURIComponent(pair[0]) + '=' + encodeURIComponent(pair[1]);
}).join('&'); };
function lnFetch(url, options) {
options = options || {};
var method = (options.method || 'GET').toLowerCase();
if (options.body instanceof LnFormData) {
options.headers = Object.assign({'Content-Type': 'application/x-www-form-urlencoded'}, options.headers || {});
options.body = options.body.toString();
}
var response = JSON.parse(__bridge.sendMessage('http_' + method,
JSON.stringify([null, null, String(url), options.headers || {}, options.body == null ? null : options.body])));
var value = {
text: function() { return response.body; },
json: function() { return JSON.parse(response.body); },
status: response.statusCode, statusText: response.reasonPhrase || '',
ok: response.statusCode >= 200 && response.statusCode < 300,
url: response.request && response.request.url || String(url),
headers: response.headers || {}
};
return Object.assign(LnPromise.resolve(value), value);
}
function lnLoad(html) {
var document = new Document(html);
function wrap(elements) { return new Selection(elements); }
function select(selector, context) {
if (selector instanceof Selection) return selector;
if (selector instanceof Element) return wrap([selector]);
if (Array.isArray(selector)) return wrap(selector);
if (typeof selector !== 'string') return wrap([]);
if (selector.trim().charAt(0) === '<') return wrap(new Document(selector).children().toArray());
return context ? select(context).find(selector) : wrap(document.select(selector).toArray());
}
function Selection(elements) {
this.elements = elements; this.length = elements.length;
elements.forEach(function(element, index) { this[index] = element; }, this);
}
Selection.prototype.each = function(callback) {
for (var i = 0; i < this.length; i++) if (callback.call(this[i], i, this[i]) === false) break;
return this;
};
Selection.prototype.toArray = function() { return this.elements.slice(); };
Selection.prototype.get = function(index) { return index == null ? this.toArray() : this.elements[index < 0 ? this.length + index : index]; };
Selection.prototype.eq = function(index) { var element = this.get(index); return wrap(element ? [element] : []); };
Selection.prototype.first = function() { return this.eq(0); };
Selection.prototype.last = function() { return this.eq(-1); };
Selection.prototype.find = function(selector) {
var found = [];
this.each(function(i, element) { element.select(selector).toArray().forEach(function(child) { if (found.indexOf(child) < 0) found.push(child); }); });
return wrap(found);
};
Selection.prototype.children = function(selector) {
var children = [];
this.each(function(i, element) { children = children.concat(element.children().toArray()); });
var result = wrap(children);
return selector ? result.filter(selector) : result;
};
Selection.prototype.next = function() {
return wrap(this.elements.map(function(element) { return element.nextElementSibling(); }).filter(Boolean));
};
Selection.prototype.text = function() { return this.elements.map(function(element) { return String(element.wholeText); }).join(''); };
Selection.prototype.html = function() { return this.length ? String(this[0].html) : null; };
Selection.prototype.attr = function(name, value) {
if (arguments.length === 1) return this.length && this[0].hasAttr(name) ? this[0].attr(name) : undefined;
return this.each(function(i, element) { element._node.attrs[name] = String(value); });
};
Selection.prototype.hasClass = function(name) { return this.elements.some(function(element) { return element.hasClass(name); }); };
Selection.prototype.removeClass = function(name) {
return this.each(function(i, element) { element._node.attrs['class'] = element.attr('class').split(/\s+/).filter(function(c) { return c !== name; }).join(' '); });
};
Selection.prototype.remove = function() {
return this.each(function(i, element) { var node = element._node, parent = node.parent; if (parent) parent.children = parent.children.filter(function(child) { return child !== node; }); });
};
Selection.prototype.map = function(callback) {
var result = [];
this.each(function(i, element) { var value = callback.call(element, i, element); if (value != null) result = result.concat(value); });
return { get: function() { return result; }, toArray: function() { return result; } };
};
Selection.prototype.filter = function(callback) {
return wrap(this.elements.filter(function(element, index) {
return typeof callback === 'function' ? callback.call(element, index, element) : document.select(callback).toArray().some(function(other) { return other._node === element._node; });
}));
};
select.html = function() { return String(document.html); };
select.root = function() { return wrap([document]); };
return select;
}
function lnRequire(name) {
switch (name) {
case 'cheerio': return { load: lnLoad };
case '@libs/fetch': return { fetchApi: lnFetch, fetch: lnFetch, default: lnFetch };
case '@libs/filterInputs': return { FilterTypes: {
Picker: 'Picker', TextInput: 'TextInput', Checkbox: 'Checkbox',
CheckboxGroup: 'CheckboxGroup', ExcludableCheckboxGroup: 'ExcludableCheckboxGroup', Switch: 'Switch'
}};
case '@libs/novelStatus': return { NovelStatus: { Ongoing: 'Ongoing', Completed: 'Completed', Hiatus: 'Hiatus', Cancelled: 'Cancelled', Unknown: 'Unknown' } };
default: throw new Error('Unsupported LNReader module: ' + name);
}
}
var plugin;
""".trimIndent()
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/lnreader/LnReaderExtensionRuntimeService.kt
- Source · implementation · 120 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
27: class LnReaderExtensionRuntimeService(
51: override suspend fun supportsLatest(): Boolean = source.supportLatest != false
53: override fun dispose() = host.close()
55: override suspend fun popular(page: Int): SourceListing = listingFromCall("popularNovels", page = page)
57: override suspend fun latest(page: Int): SourceListing = listingFromCall("popularNovels", page = page, latest = true)
59: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
62: override suspend fun detail(url: String): RemoteDetail = detailFromCall(url)
64: override suspend fun pageList(url: String): List<DbPageUrl> =
67: override suspend fun htmlContent(name: String, url: String): String =
70: private suspend fun listingFromCall(method: String, page: Int, query: String? = null, latest: Boolean = false): SourceListing {
88: private suspend fun detailFromCall(url: String): RemoteDetail {
108: private suspend fun callChapterText(url: String): String {
117: private suspend fun invoke(expression: String): JsonElement? = host.call { engine ->
Exact file bytes / download · SHA-256 be1699ca0ac42efab775fb08add49f17557f1fb735c7b6c9c8816c32ab73de69.
Complete file
package eu.friedcutlet.yokan.services.extensions.lnreader
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptEngine
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptHost
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptMessageBridge
import eu.friedcutlet.yokan.services.extensions.js.createJavaScriptEngine
import eu.friedcutlet.yokan.services.extensions.js.parseJsonElement
import eu.friedcutlet.yokan.services.extensions.js.quoted
import eu.friedcutlet.yokan.services.extensions.js.string
import eu.friedcutlet.yokan.services.extensions.js.synchronousJavaScriptSource
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
/** Runs LNReader CommonJS plugins through the shared native JavaScript host. */
class LnReaderExtensionRuntimeService(
override val source: DbSource,
http: HttpService,
engineFactory: (JavaScriptMessageBridge) -> JavaScriptEngine = ::createJavaScriptEngine,
) : ExtensionRuntimeService {
private val host = JavaScriptHost(
source = source,
http = http,
database = null,
engineFactory = engineFactory,
boot = { engine ->
engine.evaluate(lnReaderBootstrap)
engine.evaluate(
"""
plugin = (function(require, Promise, fetch, fetchApi, FormData, cheerio) {
var module = { exports: {} }, exports = module.exports;
${synchronousJavaScriptSource(source.sourceCode)}
return module.exports.default || (Object.keys(module.exports).length ? module.exports : plugin);
})(lnRequire, LnPromise, lnFetch, lnFetch, LnFormData, lnRequire('cheerio'));
""".trimIndent(),
)
},
)
override suspend fun supportsLatest(): Boolean = source.supportLatest != false
override fun dispose() = host.close()
override suspend fun popular(page: Int): SourceListing = listingFromCall("popularNovels", page = page)
override suspend fun latest(page: Int): SourceListing = listingFromCall("popularNovels", page = page, latest = true)
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
listingFromCall("searchNovels", page = page, query = query)
override suspend fun detail(url: String): RemoteDetail = detailFromCall(url)
override suspend fun pageList(url: String): List<DbPageUrl> =
listOf(DbPageUrl(url = url, fileName = "novel-chapter"))
override suspend fun htmlContent(name: String, url: String): String =
callChapterText(url)
private suspend fun listingFromCall(method: String, page: Int, query: String? = null, latest: Boolean = false): SourceListing {
val expression = if (query != null) {
"plugin.$method(${query.quoted()}, $page)"
} else {
"plugin.$method($page, {showLatestNovels: $latest, filters: plugin.filters || {}})"
}
val result = invoke(expression) as? JsonArray
?: return SourceListing(items = emptyList(), hasNextPage = false)
val items = result.mapNotNull { entry ->
val obj = entry as? JsonObject ?: return@mapNotNull null
val name = obj.string("name", "title") ?: return@mapNotNull null
val link = obj.string("url", "path") ?: return@mapNotNull null
val cover = obj.string("cover", "thumbnail")
RemoteManga(title = name, url = link, thumbnailUrl = cover)
}
return SourceListing(items = items, hasNextPage = items.isNotEmpty())
}
private suspend fun detailFromCall(url: String): RemoteDetail {
val result = invoke("plugin.parseNovel(${url.quoted()})") as? JsonObject
?: return RemoteDetail(title = "", url = url)
val title = result.string("name", "title").orEmpty()
val chapters = (result["chapters"] as? JsonArray)?.mapNotNull { entry ->
val obj = entry as? JsonObject ?: return@mapNotNull null
val chapterTitle = obj.string("name", "title") ?: return@mapNotNull null
val href = obj.string("url", "path") ?: return@mapNotNull null
RemoteChapter(title = chapterTitle, url = href, dateUpload = obj.string("releaseTime", "date").orEmpty())
}.orEmpty()
return RemoteDetail(
title = title,
url = url,
description = result.string("summary", "description").orEmpty(),
author = result.string("author"),
thumbnailUrl = result.string("cover"),
chapters = chapters,
)
}
private suspend fun callChapterText(url: String): String {
val raw = invoke("plugin.parseChapter(${url.quoted()})") ?: return ""
return when (raw) {
is JsonPrimitive -> raw.contentOrNull.orEmpty()
is JsonObject -> raw.string("chapterText", "text").orEmpty()
else -> ""
}
}
private suspend fun invoke(expression: String): JsonElement? = host.call { engine ->
parseJsonElement(engine.evaluate("lnReaderResult($expression)"))
}
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerAdapter.kt
- Source · implementation · 36 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
10: internal interface PlatformExtensionServerAdapter {
21: fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig?
22: suspend fun install(
26: suspend fun detect(path: String): InstalledExtensionServerBundle
29: internal expect fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter
35: internal fun mihonBridgePreferencesPrefix(profileId: ProfileId): String =
Exact file bytes / download · SHA-256 989556fa6cda80a428d50744d09724c84d3850fed9b601d9de2867cd81e96be4.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ext.ExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServerConfig
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
internal interface PlatformExtensionServerAdapter {
val mode: ExtensionServerRuntimeMode
val requiresBundleDownload: Boolean
val installationAvailable: Boolean
/** True when the platform uses [DbSettings.androidProxyServer] as a remote server URL. */
val supportsRemoteBaseUrl: Boolean get() = false
val bundledServerVersion: String? get() = null
/** Set when this profile cannot run a local server on this platform; explains why. */
val unavailableReason: String? get() = null
val server: ExtensionServer
fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig?
suspend fun install(
release: ExtensionServerRelease,
onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit,
): InstalledExtensionServerBundle
suspend fun detect(path: String): InstalledExtensionServerBundle
}
internal expect fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter
/** Used only when the profile has no saved extension server URL. */
internal expect val defaultMihonProxyUrl: String
/** Android bridge SharedPreferences prefix; Default keeps the legacy unprefixed names. */
internal fun mihonBridgePreferencesPrefix(profileId: ProfileId): String =
if (profileId == ProfileId.Default) "" else "${profileId.value}__"
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerManager.kt
- Source · implementation · 276 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
20: enum class ExtensionServerRuntimeMode {
29: enum class ExtensionServerInstallPhase {
37: data class ExtensionServerInstallStatus(
45: interface ExtensionServerRuntimeService {
56: fun isConfigured(): Boolean
57: suspend fun refreshLatestRelease(): ExtensionServerRelease
58: suspend fun installLatest(): InstalledExtensionServerBundle
59: suspend fun useExisting(path: String): InstalledExtensionServerBundle
60: suspend fun start(port: Int): ExtensionServerStatus
61: suspend fun startIfConfigured(port: Int): ExtensionServerStatus?
62: suspend fun stop(): ExtensionServerStatus
63: suspend fun check(baseUrl: String): Boolean
66: internal class DefaultExtensionServerRuntimeService(
85: override fun isConfigured(): Boolean {
93: override suspend fun refreshLatestRelease(): ExtensionServerRelease {
113: override suspend fun installLatest(): InstalledExtensionServerBundle = operationLock.withLock {
157: override suspend fun useExisting(path: String): InstalledExtensionServerBundle = operationLock.withLock {
174: override suspend fun start(port: Int): ExtensionServerStatus = operationLock.withLock {
211: override suspend fun startIfConfigured(port: Int): ExtensionServerStatus? {
217: override suspend fun stop(): ExtensionServerStatus = operationLock.withLock { adapter.server.stop() }
219: private fun persistProxyBaseUrl(baseUrl: String) {
226: override suspend fun check(baseUrl: String): Boolean = catchingNonCancellation {
230: private suspend fun awaitHealthy(baseUrl: String) {
241: private fun requireInstallationAvailable() {
250: private fun currentPort(): Int =
264: internal suspend fun ExtensionServerRuntimeService.resolveMihonProxy(proxy: String): String {
271: internal fun isRemoteExtensionServerUrl(url: String?): Boolean {
Exact file bytes / download · SHA-256 f6072fb569f674290eb459caa9cd20bef44314ce905120bb3656d8f9753abd23.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.ext.ExtensionServerException
import eu.friedcutlet.yokan.ext.ExtensionServerPhase
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.ExtensionServerStatus
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
import eu.friedcutlet.yokan.ext.parseExtensionServerRelease
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.isLoopbackProxy
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import eu.friedcutlet.yokan.services.catchingNonCancellation
enum class ExtensionServerRuntimeMode {
AndroidApkBridge,
DesktopDownloadedJvm,
IosSideloadedJvm,
/** No extension server can run on this platform (browser). */
Unsupported,
}
enum class ExtensionServerInstallPhase {
Idle,
Checking,
Downloading,
Installed,
Failed,
}
data class ExtensionServerInstallStatus(
val phase: ExtensionServerInstallPhase = ExtensionServerInstallPhase.Idle,
val downloadedBytes: Long = 0,
val totalBytes: Long = 0,
val version: String? = null,
val message: String = "",
)
interface ExtensionServerRuntimeService {
val mode: ExtensionServerRuntimeMode
val requiresBundleDownload: Boolean
val installationAvailable: Boolean
val bundledServerVersion: String?
/** Non-null when this profile cannot run a local server on this platform. */
val unavailableReason: String?
val status: StateFlow<ExtensionServerStatus>
val installation: StateFlow<ExtensionServerInstallStatus>
val latestRelease: StateFlow<ExtensionServerRelease?>
fun isConfigured(): Boolean
suspend fun refreshLatestRelease(): ExtensionServerRelease
suspend fun installLatest(): InstalledExtensionServerBundle
suspend fun useExisting(path: String): InstalledExtensionServerBundle
suspend fun start(port: Int): ExtensionServerStatus
suspend fun startIfConfigured(port: Int): ExtensionServerStatus?
suspend fun stop(): ExtensionServerStatus
suspend fun check(baseUrl: String): Boolean
}
internal class DefaultExtensionServerRuntimeService(
private val database: YokanDatabase,
private val http: HttpService,
private val adapter: PlatformExtensionServerAdapter,
private val findAvailablePort: (preferred: Int) -> Int = ::findAvailableExtensionServerPort,
) : ExtensionServerRuntimeService {
private val operationLock = Mutex()
private val mutableInstallation = MutableStateFlow(ExtensionServerInstallStatus())
private val mutableLatestRelease = MutableStateFlow<ExtensionServerRelease?>(null)
override val mode: ExtensionServerRuntimeMode get() = adapter.mode
override val requiresBundleDownload: Boolean get() = adapter.requiresBundleDownload
override val installationAvailable: Boolean get() = adapter.installationAvailable
override val bundledServerVersion: String? get() = adapter.bundledServerVersion
override val unavailableReason: String? get() = adapter.unavailableReason
override val status: StateFlow<ExtensionServerStatus> get() = adapter.server.status
override val installation: StateFlow<ExtensionServerInstallStatus> = mutableInstallation
override val latestRelease: StateFlow<ExtensionServerRelease?> = mutableLatestRelease
override fun isConfigured(): Boolean {
val settings = database.settings()
return runCatching {
adapter.resolveConfig(currentPort(), settings.jrePath, settings.extensionServerPath) != null ||
(adapter.supportsRemoteBaseUrl && isRemoteExtensionServerUrl(settings.androidProxyServer))
}.getOrDefault(false)
}
override suspend fun refreshLatestRelease(): ExtensionServerRelease {
mutableInstallation.value = ExtensionServerInstallStatus(ExtensionServerInstallPhase.Checking, message = "Checking latest release")
return try {
val response = http.request(HttpRequest(ExtensionServerLatestReleaseUrl))
if (response.statusCode !in 200..299) {
throw ExtensionServerException("RELEASE_HTTP_ERROR", "GitHub release request failed with HTTP ${response.statusCode}")
}
parseExtensionServerRelease(response.body).also {
mutableLatestRelease.value = it
mutableInstallation.value = ExtensionServerInstallStatus(ExtensionServerInstallPhase.Idle, version = it.version)
}
} catch (error: Throwable) {
mutableInstallation.value = ExtensionServerInstallStatus(
ExtensionServerInstallPhase.Failed,
message = error.message.orEmpty().ifBlank { "Release check failed" },
)
throw error
}
}
override suspend fun installLatest(): InstalledExtensionServerBundle = operationLock.withLock {
if (!adapter.requiresBundleDownload) {
throw ExtensionServerException("INSTALL_NOT_REQUIRED", "This platform does not use a downloaded server bundle")
}
requireInstallationAvailable()
val release = mutableLatestRelease.value ?: refreshLatestRelease()
mutableInstallation.value = ExtensionServerInstallStatus(
ExtensionServerInstallPhase.Downloading,
totalBytes = release.assets.maxOfOrNull { it.size } ?: 0,
version = release.version,
message = "Downloading extension server ${release.version}",
)
try {
val installed = adapter.install(release) { downloaded, total ->
mutableInstallation.value = mutableInstallation.value.copy(
phase = ExtensionServerInstallPhase.Downloading,
downloadedBytes = downloaded,
totalBytes = total,
)
}
val settings = database.settings()
database.updateSettings(
settings.copy(
jrePath = installed.jvmPath,
extensionServerPath = installed.serverJarPath,
),
)
mutableInstallation.value = ExtensionServerInstallStatus(
ExtensionServerInstallPhase.Installed,
downloadedBytes = mutableInstallation.value.totalBytes,
totalBytes = mutableInstallation.value.totalBytes,
version = installed.version,
message = "Extension server ${installed.version} installed",
)
installed
} catch (error: Throwable) {
mutableInstallation.value = mutableInstallation.value.copy(
phase = ExtensionServerInstallPhase.Failed,
message = error.message.orEmpty().ifBlank { "Extension server installation failed" },
)
throw error
}
}
override suspend fun useExisting(path: String): InstalledExtensionServerBundle = operationLock.withLock {
requireInstallationAvailable()
val installed = adapter.detect(path)
database.updateSettings(
database.settings().copy(
jrePath = installed.jvmPath,
extensionServerPath = installed.serverJarPath,
),
)
mutableInstallation.value = ExtensionServerInstallStatus(
phase = ExtensionServerInstallPhase.Installed,
version = installed.version,
message = "Using existing extension server files",
)
installed
}
override suspend fun start(port: Int): ExtensionServerStatus = operationLock.withLock {
if (adapter.supportsRemoteBaseUrl) {
throw ExtensionServerException(
"REMOTE_ONLY",
"The browser uses the configured remote extension server and does not start a local server",
)
}
adapter.unavailableReason?.let { throw ExtensionServerException("PROFILE_UNSUPPORTED", it) }
// A healthy server already owns its ephemeral port; keep it instead of re-allocating.
val running = adapter.server.status.value
val runningUrl = running.baseUrl
if (running.isRunning && runningUrl != null && check(runningUrl)) {
persistProxyBaseUrl(runningUrl)
return@withLock running
}
val settings = database.settings()
val resolvedPort = findAvailablePort(0)
val config = adapter.resolveConfig(resolvedPort, settings.jrePath, settings.extensionServerPath)
?: throw ExtensionServerException("NOT_CONFIGURED", "Install or configure the local extension server first")
val started = adapter.server.start(config)
try {
awaitHealthy(config.baseUrl)
} catch (error: Throwable) {
catchingNonCancellation { adapter.server.stop() }
throw error
}
val currentSettings = database.settings()
database.updateSettings(
currentSettings.copy(
androidProxyServer = config.baseUrl,
jrePath = config.jvmPath ?: currentSettings.jrePath,
extensionServerPath = config.serverJarPath ?: currentSettings.extensionServerPath,
),
)
started
}
override suspend fun startIfConfigured(port: Int): ExtensionServerStatus? {
if (adapter.supportsRemoteBaseUrl) return null
if (!isConfigured()) return null
return start(port)
}
override suspend fun stop(): ExtensionServerStatus = operationLock.withLock { adapter.server.stop() }
private fun persistProxyBaseUrl(baseUrl: String) {
val settings = database.settings()
if (settings.androidProxyServer != baseUrl) {
database.updateSettings(settings.copy(androidProxyServer = baseUrl))
}
}
override suspend fun check(baseUrl: String): Boolean = catchingNonCancellation {
http.request(HttpRequest(baseUrl.trimEnd('/'))).statusCode in 200..299
}.getOrDefault(false)
private suspend fun awaitHealthy(baseUrl: String) {
repeat(100) {
if (check(baseUrl)) return
if (adapter.server.status.value.phase == ExtensionServerPhase.Failed) {
throw ExtensionServerException("START_ERROR", adapter.server.status.value.message)
}
delay(200)
}
throw ExtensionServerException("HEALTH_TIMEOUT", "Local extension server did not become healthy at $baseUrl")
}
private fun requireInstallationAvailable() {
if (!adapter.installationAvailable) {
throw ExtensionServerException(
"MISSING_JAVA",
adapter.unavailableReason ?: "This iOS build does not include the signed sideloaded Java runtime",
)
}
}
private fun currentPort(): Int =
extensionServerPortFromUrl(database.settings().androidProxyServer)
private companion object {
const val ExtensionServerLatestReleaseUrl =
"https://api.github.com/repos/kodjodevf/M-Extension-Server/releases/latest"
}
}
/**
* A loopback proxy always means this profile's own local server: the saved ephemeral port may
* since have been reused by another profile's server, so it is never trusted. The browser has no
* local server and keeps the user's URL as-is.
*/
internal suspend fun ExtensionServerRuntimeService.resolveMihonProxy(proxy: String): String {
if (mode == ExtensionServerRuntimeMode.Unsupported || !isLoopbackProxy(proxy)) return proxy
status.value.takeIf { it.isRunning }?.baseUrl?.let { return it }
return start(extensionServerPortFromUrl(proxy)).baseUrl
?: throw ExtensionServerException("NOT_RUNNING", "This profile's local extension server is not running")
}
internal fun isRemoteExtensionServerUrl(url: String?): Boolean {
val value = url?.trim().orEmpty()
return (value.startsWith("http://", ignoreCase = true) ||
value.startsWith("https://", ignoreCase = true)) &&
!isLoopbackProxy(value)
}
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerPorts.kt
- Source · implementation · 17 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
9: internal expect fun findAvailableExtensionServerPort(preferred: Int): Int
11: internal fun extensionServerPortFromUrl(url: String?, fallback: Int = 8080): Int =
Exact file bytes / download · SHA-256 2bd999df849b0748d1c33a9219f189e4e4f660a97923021cb7202d03388066d5.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
/**
* Returns [preferred] when it can still be bound on the loopback interface, otherwise an
* OS-assigned free port (loopback bind to port 0). The default proxy port 8080 is commonly
* taken by other local software, so callers must treat the returned port as authoritative
* and persist the resulting proxy URL.
*/
internal expect fun findAvailableExtensionServerPort(preferred: Int): Int
internal fun extensionServerPortFromUrl(url: String?, fallback: Int = 8080): Int =
Regex(""":(\d{1,5})(?:/|$)""").find(url.orEmpty())
?.groupValues
?.getOrNull(1)
?.toIntOrNull()
?.takeIf { it in 1..65535 }
?: fallback
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/MihonExtensionRuntime.kt
- Source · implementation · 382 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
55: class MihonExtensionRuntimeService(
70: override suspend fun supportsLatest(): Boolean = source.supportLatest == true
72: override fun dispose() {
76: override suspend fun headers(): Map<String, String> = parseHeaders(source.headers)
78: override suspend fun popular(page: Int): SourceListing =
81: override suspend fun latest(page: Int): SourceListing =
84: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
94: override suspend fun detail(url: String): RemoteDetail {
105: override suspend fun related(url: String): eu.friedcutlet.yokan.services.extensions.SourceRelations {
117: override suspend fun pageList(url: String): List<DbPageUrl> =
123: override suspend fun videoList(url: String): List<DbVideo> =
129: override suspend fun filterList(): List<SourceFilter> = filtersFromJson(source.filterList)
131: override suspend fun sourcePreferences(): List<SourcePreferenceValue> {
137: suspend fun refreshSourcePreferences(): List<SourcePreferenceValue> {
155: suspend fun fetchMetadata(): MihonSourceMetadata {
190: private suspend fun chapterList(url: String): List<RemoteChapter> {
201: private suspend fun dalvik(method: String, vararg fields: Pair<String, JsonElement>): JsonElement = withContext(Dispatchers.Default) {
226: private fun requestBody(
258: private fun preferencesWithBridgeContext(): JsonArray {
327: private suspend fun postDalvik(body: String): HttpResponse {
356: private fun unwrapBridgeResponse(response: HttpResponse): JsonElement {
381: private fun methodSuffix(): String = if (source.itemType == DbItemType.Anime) "Anime" else "Manga"
Exact file bytes / download · SHA-256 c1234f8a0215ae1181376c47f0ed02229f95de0ed2451c13ff7db214c5cfdf0b.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.MihonSourceMetadata
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import eu.friedcutlet.yokan.services.extensions.SourcePreferenceValue
import eu.friedcutlet.yokan.services.extensions.js.arrayOrEmpty
import eu.friedcutlet.yokan.services.extensions.js.filtersFromJson
import eu.friedcutlet.yokan.services.extensions.js.headersFromJsonElement
import eu.friedcutlet.yokan.services.extensions.js.listingFromJson
import eu.friedcutlet.yokan.services.extensions.js.objectOrNull
import eu.friedcutlet.yokan.services.extensions.js.pageUrlFromJson
import eu.friedcutlet.yokan.services.extensions.js.parseHeaders
import eu.friedcutlet.yokan.services.extensions.js.parseJsonArray
import eu.friedcutlet.yokan.services.extensions.js.parseJsonElement
import eu.friedcutlet.yokan.services.extensions.js.primitiveOrNull
import eu.friedcutlet.yokan.services.extensions.js.remoteChapterFromJson
import eu.friedcutlet.yokan.services.extensions.js.remoteDetailFromJson
import eu.friedcutlet.yokan.services.extensions.js.isSeasonsDetail
import eu.friedcutlet.yokan.services.extensions.js.seasonListFromJson
import eu.friedcutlet.yokan.services.extensions.js.sourceFiltersToJson
import eu.friedcutlet.yokan.services.extensions.js.sourcePreferencesFromJson
import eu.friedcutlet.yokan.services.extensions.js.string
import eu.friedcutlet.yokan.services.extensions.js.videoFromJson
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.concurrent.Volatile
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.math.max
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonNull
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
/**
* Runtime for Mihon/Aniyomi APK sources, executed remotely by an M-Extension-Server `/dalvik`
* endpoint. There is no local engine: every call is a suspending HTTP request.
*/
class MihonExtensionRuntimeService(
override val source: DbSource,
private val http: HttpService,
androidProxyServer: String,
private val database: YokanDatabase? = null,
private val prepareProxy: suspend () -> String = { androidProxyServer },
) : ExtensionRuntimeService {
private val proxyUrl = androidProxyServer.trimEnd('/')
// M-Extension-Server 1.0.5 handle for this runtime's APK payload: the server keeps the loaded
// classloader behind it, so later calls skip re-sending and re-dexing the Base64 APK. It lives
// and dies with the (cached) runtime; a racing call at worst re-sends the APK once.
@Volatile
private var extensionHandle: String? = null
override suspend fun supportsLatest(): Boolean = source.supportLatest == true
override fun dispose() {
extensionHandle = null
}
override suspend fun headers(): Map<String, String> = parseHeaders(source.headers)
override suspend fun popular(page: Int): SourceListing =
listingFromJson(dalvik("getPopular${methodSuffix()}", "page" to JsonPrimitive(page + 1)))
override suspend fun latest(page: Int): SourceListing =
listingFromJson(dalvik("getLatest${methodSuffix()}", "page" to JsonPrimitive(page + 1)))
override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
listingFromJson(
dalvik(
"getSearch${methodSuffix()}",
"page" to JsonPrimitive(max(1, page)),
"search" to JsonPrimitive(query),
"filterList" to sourceFiltersToJson(filters),
),
)
override suspend fun detail(url: String): RemoteDetail {
val dataKey = if (source.itemType == DbItemType.Anime) "animeData" else "mangaData"
val animeData = buildJsonObject { put("url", JsonPrimitive(url)) }
val detail = dalvik("getDetails${methodSuffix()}", dataKey to animeData)
// Extensions-lib 16+ Seasons titles list season entries; older APKs omit fetch_type (Episodes).
if (source.itemType == DbItemType.Anime && detail.isSeasonsDetail()) {
return remoteDetailFromJson(detail, seasonsOverride = seasonListFromJson(dalvik("getSeasonList", "animeData" to animeData)))
}
return remoteDetailFromJson(detail, chapterList(url))
}
override suspend fun related(url: String): eu.friedcutlet.yokan.services.extensions.SourceRelations {
if (source.itemType != DbItemType.Anime) return eu.friedcutlet.yokan.services.extensions.SourceRelations(false)
val response = dalvik("getRelatedAnimeList", "animeData" to buildJsonObject { put("url", JsonPrimitive(url)) })
if (response is JsonArray) return eu.friedcutlet.yokan.services.extensions.js.sourceRelationsFromJson(response, source.baseUrl)
val wrapper = response as? JsonObject ?: error("The bridge returned invalid related entries")
return when (wrapper["supported"].primitiveOrNull()?.booleanOrNull) {
false -> eu.friedcutlet.yokan.services.extensions.SourceRelations(false)
true -> eu.friedcutlet.yokan.services.extensions.js.sourceRelationsFromJson(wrapper["groups"] ?: JsonNull, source.baseUrl)
null -> error("The bridge did not report related-entry support")
}
}
override suspend fun pageList(url: String): List<DbPageUrl> =
dalvik(
"getPageList",
"chapterData" to buildJsonObject { put("url", JsonPrimitive(url)) },
).arrayOrEmpty().mapNotNull(::pageUrlFromJson)
override suspend fun videoList(url: String): List<DbVideo> =
dalvik(
"getVideoList",
"episodeData" to buildJsonObject { put("url", JsonPrimitive(url)) },
).arrayOrEmpty().mapNotNull(::videoFromJson)
override suspend fun filterList(): List<SourceFilter> = filtersFromJson(source.filterList)
override suspend fun sourcePreferences(): List<SourcePreferenceValue> {
val existing = sourcePreferencesFromJson(source.preferenceList)
if (existing.isNotEmpty()) return existing
return refreshSourcePreferences()
}
suspend fun refreshSourcePreferences(): List<SourcePreferenceValue> {
if (source.sourceCode.isBlank()) return emptyList()
return catchingNonCancellation {
val res = dalvik("preferences${methodSuffix()}")
val raw = res.takeIf { it is JsonArray && it.isNotEmpty() }?.toString()
if (raw != null) {
database?.let { db ->
db.source(source.id)?.let { current ->
db.upsertSource(current.copy(preferenceList = raw))
}
}
sourcePreferencesFromJson(raw)
} else {
emptyList()
}
}.getOrDefault(emptyList())
}
suspend fun fetchMetadata(): MihonSourceMetadata {
if (source.sourceCode.isBlank()) return MihonSourceMetadata()
val headers = catchingNonCancellation {
val res = dalvik("headers${methodSuffix()}")
val map = headersFromJsonElement(res)
if (map.isNotEmpty()) {
buildJsonObject { map.forEach { (k, v) -> put(k, JsonPrimitive(v)) } }.toString()
} else null
}.getOrNull()
val supportLatest = catchingNonCancellation {
val res = dalvik("supportLatest${methodSuffix()}")
res.primitiveOrNull()?.booleanOrNull
?: res.primitiveOrNull()?.contentOrNull?.toBooleanStrictOrNull()
}.getOrNull()
val filterList = catchingNonCancellation {
val res = dalvik("filters${methodSuffix()}")
res.takeIf { it is JsonArray && it.isNotEmpty() }?.toString()
}.getOrNull()
val preferenceList = catchingNonCancellation {
val res = dalvik("preferences${methodSuffix()}")
res.takeIf { it is JsonArray && it.isNotEmpty() }?.toString()
}.getOrNull()
return MihonSourceMetadata(
headers = headers,
supportLatest = supportLatest,
filterList = filterList,
preferenceList = preferenceList,
)
}
private suspend fun chapterList(url: String): List<RemoteChapter> {
val dataKey = if (source.itemType == DbItemType.Anime) "animeData" else "mangaData"
val method = if (source.itemType == DbItemType.Anime) "getEpisodeList" else "getChapterList"
return dalvik(
method,
dataKey to buildJsonObject { put("url", JsonPrimitive(url)) },
).arrayOrEmpty().mapNotNull(::remoteChapterFromJson)
}
// Request bodies can carry the multi-megabyte Base64 APK and responses are parsed here, so keep
// the JSON work off the caller's (often Main) thread; the HTTP call itself suspends.
private suspend fun dalvik(method: String, vararg fields: Pair<String, JsonElement>): JsonElement = withContext(Dispatchers.Default) {
if (source.sourceCode.isBlank()) {
throw IllegalStateException("${source.name} is missing the bundled Mihon APK payload. Re-install the source so the APK byte data is pulled into the database.")
}
val cachedExtensionId = extensionHandle
val response = postDalvik(requestBody(method, fields, extensionId = cachedExtensionId))
// HTTP 409 means the server restarted and dropped the cached extension handle
// (M-Extension-Server 1.0.5 ExtensionNotLoadedException). Retry once with the APK.
val effective = if (cachedExtensionId != null && response.statusCode == 409) {
extensionHandle = null
postDalvik(requestBody(method, fields, extensionId = null))
} else {
response
}
effective.headers.entries
.firstOrNull {
it.key.equals("X-Mangatan-Extension-Id", ignoreCase = true) ||
it.key.equals("X-Mangayomi-Extension-Id", ignoreCase = true)
}
?.value
?.takeIf { it.isNotBlank() }
?.let { extensionHandle = it }
unwrapBridgeResponse(effective)
}
private fun requestBody(
method: String,
fields: Array<out Pair<String, JsonElement>>,
extensionId: String?,
): String = buildJsonObject {
put("method", JsonPrimitive(method))
put("search", JsonPrimitive(""))
put("preferences", preferencesWithBridgeContext())
if (source.lang.isNotBlank()) {
put("lang", JsonPrimitive(source.lang))
}
if (source.id != 0L) {
put("sourceId", JsonPrimitive(source.id.toString()))
}
// 1.0.5 servers accept a handle instead of the APK; older servers ignore
// `extensionId` and always need `data`, so the APK rides along until a
// handle has been observed.
if (extensionId != null) {
put("extensionId", JsonPrimitive(extensionId))
} else {
put("data", JsonPrimitive(source.sourceCode))
}
fields.forEach { (key, value) -> put(key, value) }
}.toString()
/**
* Multi-source APKs (SourceFactory extensions) need the upstream Tachiyomi source ID
* to select the right factory child; it is captured at catalog ingestion into
* `additionalParams` and transported via the bridge-context preference entry that
* M-Extension-Server 1.0.5 understands. Older servers treat it as an unknown
* preference key and fall back to the first source.
*/
private fun preferencesWithBridgeContext(): JsonArray {
val rawPreferences = parseJsonArray(source.preferenceList)
val userOverrides = database?.settings()?.sourcePreferences.orEmpty()
.filter { it.sourceId == source.id }
.associate { it.key to it.value }
val preferences = if (userOverrides.isEmpty()) {
rawPreferences
} else {
buildJsonArray {
rawPreferences.forEach { element ->
val obj = element.objectOrNull()
if (obj == null) {
add(element)
return@forEach
}
val key = obj.string("key")
val overrideValue = key?.let { userOverrides[it] }
if (overrideValue == null) {
add(element)
return@forEach
}
val updatedObj = buildJsonObject {
obj.forEach { (k, v) ->
if (k in listOf("checkBoxPreference", "switchPreferenceCompat", "editTextPreference", "listPreference", "multiSelectListPreference") && v is JsonObject) {
val newPayload = buildJsonObject {
v.forEach { (pk, pv) ->
if (pk == "value") {
if (k in listOf("checkBoxPreference", "switchPreferenceCompat")) {
put("value", JsonPrimitive(overrideValue.toBooleanStrictOrNull() ?: false))
} else {
put("value", JsonPrimitive(overrideValue))
}
} else if (pk == "valueIndex" && k == "listPreference") {
val entryValues = (v["entryValues"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull }
val newIndex = entryValues?.indexOf(overrideValue)?.takeIf { it >= 0 }
?: overrideValue.toIntOrNull()
?: 0
put("valueIndex", JsonPrimitive(newIndex))
} else {
put(pk, pv)
}
}
}
put(k, newPayload)
} else {
put(k, v)
}
}
}
add(updatedObj)
}
}
}
val upstreamSourceId = parseJsonElement(source.additionalParams)
.objectOrNull()
?.string("sourceId")
?: return preferences
val context = buildJsonObject {
put("key", JsonPrimitive("__mangayomi_bridge_context__"))
put("sourceId", JsonPrimitive(upstreamSourceId))
}
return buildJsonArray {
preferences.forEach { add(it) }
add(context)
}
}
private suspend fun postDalvik(body: String): HttpResponse {
val activeProxyUrl = prepareProxy().trimEnd('/')
return catchingNonCancellation {
http.request(
HttpRequest(
url = "$activeProxyUrl/dalvik",
method = "POST",
headers = mapOf("Content-Type" to "application/json"),
body = body,
),
)
}.getOrElse { throwable ->
val fetchHint = throwable.message.orEmpty().lowercase().let { message ->
if (listOf("failed to fetch", "networkerror", "network request failed", "cors")
.any { message.contains(it) }
) {
" Browser fetch failed; this is commonly caused by CORS or mixed-content policy. " +
"Allow this page's origin to POST JSON to /dalvik."
} else {
""
}
}
throw IllegalStateException(
"Cannot reach APK Extension Server at $proxyUrl.$fetchHint Verify the server URL in Settings → Browse → APK Extension Server.",
throwable,
)
}
}
private fun unwrapBridgeResponse(response: HttpResponse): JsonElement {
when (response.statusCode) {
in 200..299 -> Unit
403, 503 -> throw IllegalStateException(
"${source.name} is behind a Cloudflare/anti-bot challenge (HTTP ${response.statusCode}). Open the WebView for ${source.baseUrl} to refresh cookies.",
)
404 -> throw IllegalStateException(
"ApkBridge responded with HTTP 404. The /dalvik endpoint is unavailable; verify the proxy URL points to a running ApkBridge instance.",
)
else -> throw IllegalStateException("Mihon bridge returned HTTP ${response.statusCode}: ${response.body.take(120)}")
}
val element = parseJsonElement(response.body) ?: JsonNull
val error = element.objectOrNull()?.string("error")
if (error != null) {
val code = element.objectOrNull()?.string("code") ?: response.statusCode.toString()
val message = when {
"cloudflare" in error.lowercase() -> "Cloudflare protection blocked the request. Refresh cookies via WebView, then retry."
"apk" in error.lowercase() -> "ApkBridge could not load the APK payload. Re-install the source so the bundled bytes are valid."
else -> error
}
throw IllegalStateException("Mihon bridge error $code: $message")
}
return element
}
private fun methodSuffix(): String = if (source.itemType == DbItemType.Anime) "Anime" else "Manga"
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/ChapterPageResolverTest.kt
- Source · test / fixture · 225 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
28: class ChapterPageResolverTest {
33: private fun database(vararg pageCache: DbChapterPageUrls) = InMemoryYokanDatabase(
47: fun savedListIsServedUntilTheTtlOrASourceUpdate() = runTest {
75: fun listsWithoutAFetchTimeOrFromAnotherSourceAreStale() {
85: fun invalidatingASourceDropsOnlyItsChaptersLists() {
98: fun theOfflineFallbackOnlyStandsInWithAFreshListAndIsNeverSaved() = runTest {
121: fun pageCacheWriteAfterChapterDeletionIsDiscarded() = runTest {
147: fun canceledCallerCannotReadAFreshSavedList() = runTest {
163: fun canceledNonCancellablePageResultIsNeitherDeliveredNorCached() = runTest {
178: fun pageHeadersOverrideSourceHeadersCaseInsensitively() {
208: internal class PageListRuntimeFactory(
216: override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
217: override suspend fun headers(): Map<String, String> = headers
218: override suspend fun pageList(url: String): List<DbPageUrl> {
Exact file bytes / download · SHA-256 43ab855056ec48564cdfad4d3187b511aa3cc2d28d5a288c1673ffd7bf3ea2ff.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbChapterPageUrls
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.async
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.cancel
import kotlinx.coroutines.withContext
import kotlin.test.assertFailsWith
import kotlinx.coroutines.test.runTest
class ChapterPageResolverTest {
private var now = 1_700_000_000_000L
private val source = DbSource(id = SOURCE_ID, name = "Source", version = "1.0.0", isAdded = true)
private val chapter = DbChapter(id = 10, mangaId = MANGA_ID, url = "/c10")
private fun database(vararg pageCache: DbChapterPageUrls) = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
sources = listOf(source, DbSource(id = OTHER_SOURCE_ID, name = "Other")),
mangas = listOf(DbManga(id = MANGA_ID, sourceId = SOURCE_ID), DbManga(id = OTHER_MANGA_ID, sourceId = OTHER_SOURCE_ID)),
chapters = listOf(
chapter,
DbChapter(id = 11, mangaId = MANGA_ID, url = "/c11"),
DbChapter(id = 20, mangaId = OTHER_MANGA_ID, url = "/c20"),
),
pageCache = pageCache.toList(),
),
)
@Test
fun savedListIsServedUntilTheTtlOrASourceUpdate() = runTest {
val database = database()
val runtimes = PageListRuntimeFactory(headers = mapOf("Referer" to "https://source.test"))
val resolver = ChapterPageResolver(DefaultYokanRepository(database), database, runtimes, clock = { now })
val fetched = resolver.pages(chapter, SOURCE_ID)
assertEquals(mapOf("Referer" to "https://source.test"), fetched.first().headers, "source headers are merged in")
val saved = database.pageCache(chapter.id).single()
assertEquals(listOf<Any?>(now, SOURCE_ID, "1.0.0"), listOf(saved.fetchedAt, saved.sourceId, saved.sourceVersion))
now += PAGE_LIST_TTL_MS - 1
assertEquals(fetched, resolver.pages(chapter, SOURCE_ID))
assertEquals(1, runtimes.pageListCalls, "a fresh saved list is served without the source")
now += 1
resolver.pages(chapter, SOURCE_ID)
assertEquals(2, runtimes.pageListCalls, "the list expires at the TTL")
database.upsertSource(source.copy(version = "1.1.0"))
resolver.pages(chapter, SOURCE_ID)
assertEquals(3, runtimes.pageListCalls, "an extension update makes the list stale")
assertEquals("1.1.0", database.pageCache(chapter.id).single().sourceVersion)
resolver.pages(chapter, SOURCE_ID, forceRefresh = true)
assertEquals(4, runtimes.pageListCalls)
}
@Test
fun listsWithoutAFetchTimeOrFromAnotherSourceAreStale() {
val saved = DbChapterPageUrls(chapterId = 1, urls = listOf("u"), fetchedAt = now, sourceId = SOURCE_ID, sourceVersion = "1.0.0")
assertTrue(saved.isFresh(SOURCE_ID, "1.0.0", now))
assertFalse(saved.copy(fetchedAt = null).isFresh(SOURCE_ID, "1.0.0", now), "lists saved before timestamps")
assertFalse(saved.isFresh(SOURCE_ID, "1.0.0", now - 1), "fetched in the future: the clock moved back")
assertFalse(saved.isFresh(OTHER_SOURCE_ID, "1.0.0", now))
}
@Test
fun invalidatingASourceDropsOnlyItsChaptersLists() {
val database = database(
DbChapterPageUrls(chapterId = 10, urls = listOf("a"), fetchedAt = now, sourceId = SOURCE_ID),
DbChapterPageUrls(chapterId = 11, urls = listOf("legacy")), // saved before lists recorded their source
DbChapterPageUrls(chapterId = 20, urls = listOf("b"), fetchedAt = now, sourceId = OTHER_SOURCE_ID),
)
ChapterPageResolver(DefaultYokanRepository(database), database, PageListRuntimeFactory()).invalidateSource(SOURCE_ID)
assertEquals(listOf(20L), database.pageCache().map { it.chapterId })
}
@Test
fun theOfflineFallbackOnlyStandsInWithAFreshListAndIsNeverSaved() = runTest {
val stale = DbChapterPageUrls(chapterId = 10, chapterUrl = "/c10", urls = listOf("https://img/old.jpg"), sourceId = SOURCE_ID, sourceVersion = "1.0.0")
val database = database(stale)
val runtimes = PageListRuntimeFactory(failure = IllegalStateException("engine crashed"))
val resolver = ChapterPageResolver(DefaultYokanRepository(database), database, runtimes, clock = { now })
val readerChapter = Chapter(id = 10, mangaId = MANGA_ID, name = "Chapter 10", url = "/c10")
var reported: Throwable? = null
val pages = resolver.pages(readerChapter, SOURCE_ID, onFallback = { reported = it })
assertNotNull(reported)
assertEquals(listOf("/c10"), pages.map { it.url }, "a stale list is not passed off as live")
assertEquals(stale, database.pageCache(10).single(), "the fallback answer is not saved")
database.upsertPageCache(stale.copy(fetchedAt = nowMillis()))
assertEquals(
listOf("https://img/old.jpg"),
DatabaseFallbackRuntimeService(source, database).pageList("/c10").map { it.url },
"a fresh saved list does stand in",
)
}
@Test
fun pageCacheWriteAfterChapterDeletionIsDiscarded() = runTest {
val database = database()
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
val resolver = ChapterPageResolver(
DefaultYokanRepository(database),
database,
PageListRuntimeFactory(beforePageList = {
entered.complete(Unit)
release.await()
}),
clock = { now },
)
val resolving = async {
resolver.pages(chapter, SOURCE_ID)
}
entered.await()
database.removeChapter(chapter.id)
release.complete(Unit)
resolving.await()
assertTrue(database.pageCache(chapter.id).isEmpty())
}
@Test
fun canceledCallerCannotReadAFreshSavedList() = runTest {
val database = database(DbChapterPageUrls(
chapterId = 10, urls = listOf("saved"), fetchedAt = now,
sourceId = SOURCE_ID, sourceVersion = "1.0.0",
))
val runtimes = PageListRuntimeFactory()
val resolver = ChapterPageResolver(DefaultYokanRepository(database), database, runtimes, clock = { now })
val request = async {
currentCoroutineContext().cancel()
assertFailsWith<CancellationException> { resolver.pages(chapter, SOURCE_ID) }
}
request.join()
assertEquals(0, runtimes.pageListCalls)
}
@Test
fun canceledNonCancellablePageResultIsNeitherDeliveredNorCached() = runTest {
val database = database()
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
val resolver = ChapterPageResolver(DefaultYokanRepository(database), database,
PageListRuntimeFactory(beforePageList = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
}), clock = { now })
val request = async { resolver.pages(chapter, SOURCE_ID) }
entered.await(); request.cancel(); release.complete(Unit)
assertFailsWith<CancellationException> { request.await() }
assertTrue(database.pageCache(10).isEmpty())
}
@Test
fun pageHeadersOverrideSourceHeadersCaseInsensitively() {
val pages = mergeSourcePageHeaders(
sourceHeaders = mapOf("Referer" to "source", "User-Agent" to "source-agent"),
pages = listOf(
DbPageUrl(
url = "https://example.com/page.jpg",
headers = mapOf("referer" to "page", "Authorization" to "Bearer token"),
),
),
)
assertEquals(
mapOf(
"User-Agent" to "source-agent",
"referer" to "page",
"Authorization" to "Bearer token",
),
pages.single().headers,
)
}
private companion object {
const val SOURCE_ID = 7L
const val OTHER_SOURCE_ID = 8L
const val MANGA_ID = 1L
const val OTHER_MANGA_ID = 2L
}
}
/** Runtimes whose `pageList(url)` answers three pages under `url` (or throws [failure]) and counts calls. */
internal class PageListRuntimeFactory(
private val headers: Map<String, String> = emptyMap(),
private val failure: Throwable? = null,
private val beforePageList: suspend () -> Unit = {},
) : ExtensionRuntimeFactory {
var pageListCalls = 0
private set
override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {
override suspend fun headers(): Map<String, String> = headers
override suspend fun pageList(url: String): List<DbPageUrl> {
beforePageList()
failure?.let { throw it }
pageListCalls += 1
return List(3) { DbPageUrl("https://img.test$url/$pageListCalls-$it.jpg") }
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionRuntimeFactoryTest.kt
- Source · test / fixture · 78 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
19: class ExtensionRuntimeFactoryTest {
31: fun legacyCommonJsNovelUsesLnReaderRuntime() {
42: fun reusesRuntimesAndDisposesEvictedOnesOnlyAfterTheirCallFinishes() = runTest {
69: private class RecordingEngine : JavaScriptEngine {
72: override fun evaluate(script: String, isCancelled: () -> Boolean): String =
75: override fun close() {
Exact file bytes / download · SHA-256 a23b0451f94182e504c8ca25a6020c9eae788fd57722d879124bebe69a40f639.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.services.extensions.lnreader.LnReaderExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptEngine
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
class ExtensionRuntimeFactoryTest {
private val engines = mutableListOf<RecordingEngine>()
private val factory = DynamicExtensionRuntimeFactory(
database = InMemoryYokanDatabase(),
http = HttpService { error("offline") },
javaScriptEngineFactory = { RecordingEngine().also { engines += it } },
)
private val sources = (1L..5L).map { id ->
DbSource(id = id, name = "Source $id", sourceCode = "// fixture", sourceCodeLanguage = DbSourceCodeLanguage.JavaScript)
}
@Test
fun legacyCommonJsNovelUsesLnReaderRuntime() {
val source = sources.first().copy(itemType = DbItemType.Novel, sourceCode = """
exports.default = { popularNovels: function() { return []; }, parseNovel: function() { return {}; } };
""")
val runtime = factory.create(source)
try { assertTrue(runtime is LnReaderExtensionRuntimeService) } finally { runtime.dispose() }
val mangayomi = factory.create(source.copy(sourceCode = "class DefaultExtension extends MProvider {} // exports.default popularNovels parseNovel"))
try { assertTrue(mangayomi is JavaScriptExtensionRuntimeService) } finally { mangayomi.dispose() }
}
@Test
fun reusesRuntimesAndDisposesEvictedOnesOnlyAfterTheirCallFinishes() = runTest {
val booted = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
val held = launch {
factory.withRuntime(sources[0]) { runtime ->
runtime.popular(1)
booted.complete(Unit)
release.await()
}
}
booted.await()
sources.drop(1).forEach { source -> factory.withRuntime(source) { it.popular(1) } }
factory.withRuntime(sources[1]) { it.popular(2) }
assertEquals(5, engines.size, "a cached source must not boot a second engine")
assertFalse(engines[0].closed, "the evicted runtime is still serving a call")
release.complete(Unit)
held.join()
assertTrue(engines[0].closed)
assertTrue(engines.drop(1).none { it.closed })
factory.clear()
assertTrue(engines.all { it.closed })
}
}
private class RecordingEngine : JavaScriptEngine {
var closed = false
override fun evaluate(script: String, isCancelled: () -> Boolean): String =
if ("__yokanValue" in script) """{"list": [], "hasNextPage": false}""" else ""
override fun close() {
closed = true
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/ProfileReaderContentTest.kt
- Source · test / fixture · 511 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
48: class ProfileReaderContentTest {
405: internal class Fixture(
440: override fun writeBytes(path: String, bytes: ByteArray) = error("Unexpected write")
441: override fun readBytes(path: String): ByteArray = error("Unexpected read")
442: override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray = localBytes
443: override fun canonicalPath(path: String) = path
444: override fun exists(path: String) = fileExists
445: override fun deleteRecursively(path: String) = error("Unexpected delete")
446: override fun directorySize(path: String) = 0L
447: override fun openLocation(path: String) = false
448: override fun listLocalEntries(root: String) = emptyList<LocalEntry>()
449: override fun listFiles(root: String) = localFiles
452: override fun listPages(archivePath: String): List<DbPageUrl> {
456: override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {
461: override fun readEpubChapter(archivePath: String, index: Int): String {
466: override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? {
471: override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null
477: suspend fun close() { content.closeAndJoin(); owner.cancelAndJoin() }
480: internal class RuntimeFactory(val db: YokanDatabase, label: String) : ExtensionRuntimeFactory {
489: override fun create(source: DbSource): ExtensionRuntimeService {
492: override fun dispose() { disposed++ }
493: override suspend fun headers() = headerAction()
494: override suspend fun pageList(url: String) = pageAction()
495: override suspend fun videoList(url: String) = videoAction()
496: override suspend fun htmlContent(name: String, url: String) = htmlAction()
497: override suspend fun cleanHtmlContent(html: String): String { cleaned++; return html }
500: override suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
Exact file bytes / download · SHA-256 748ec7f6135d76e9f24aa08cc8b9b6532bd041a2eecb6df0ef70433ddcc38a7d.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbVideo
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.files.LocalArchiveService
import eu.friedcutlet.yokan.services.files.LocalEpubChapter
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import androidx.compose.ui.text.LinkAnnotation
import eu.friedcutlet.yokan.ui.screens.novel.NovelContentBlock
import eu.friedcutlet.yokan.ui.screens.novel.NovelImageSource
import eu.friedcutlet.yokan.ui.screens.novel.loadNovelDocument
import kotlin.test.assertContentEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.withContext
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
@OptIn(ExperimentalCoroutinesApi::class)
class ProfileReaderContentTest {
@Test fun downloadedEpisodeUsesLocalMediaBeforeAnySourceExtraction() = runTest {
val f = Fixture(this)
try {
f.localFiles = listOf(LocalFileEntry("/A/episode/0001.mp4", "0001.mp4", 500, 0))
val video = f.content.videos(f.source, chapter.copy(archivePath = "/A/episode")).single()
assertEquals("file:///A/episode/0001.mp4", video.url)
assertEquals("Downloaded", video.quality)
assertEquals(0, f.factory.created)
f.fileExists = true
assertEquals("file:///A/movie.mp4", f.content.videos(null, chapter.copy(url = "/A/movie.mp4")).single().url)
} finally { f.close() }
}
@Test fun downloadedNovelHtmlIsReadOfflineWithoutSourceRuntime() = runTest {
val f = Fixture(this)
try {
f.localFiles = listOf(LocalFileEntry("/A/novel/0001.html", "0001.html", 100, 0))
f.localBytes = "<p>Offline novel chapter</p>".encodeToByteArray()
val parsed = loadNovelDocument(f.content, f.source, "Novel", chapter.copy(archivePath = "/A/novel")).parse()
assertEquals("Offline novel chapter", parsed.plainText)
assertEquals(0, f.factory.created)
} finally { f.close() }
}
@Test fun remotePagesMergeHeadersAndCacheOnlyInCapturedDatabase() = runTest {
val a = Fixture(this, "A")
val b = Fixture(this, "B")
try {
val pages = a.content.pages(a.source, chapter, false)
assertEquals(mapOf("User-Agent" to "A", "referer" to "page"), pages.single().headers)
assertEquals(listOf("A/page"), a.db.pageCache(10).single().urls)
assertTrue(b.db.pageCache(10).isEmpty())
assertEquals(pages, a.content.pages(a.source, chapter, false))
assertEquals(1, a.factory.created)
assertEquals(1, a.factory.disposed)
a.content.pages(a.source, chapter, true)
assertEquals(2, a.factory.created)
} finally { a.close(); b.close() }
}
@Test fun localArchiveUsesCapturedFilesWithoutAllocatingRuntime() = runTest {
val f = Fixture(this, "A")
try {
f.archivePages = listOf(DbPageUrl("file://A/local/1.jpg"))
val local = chapter.copy(archivePath = "/A/local/book.cbz#chapter")
assertEquals(f.archivePages, f.content.pages(f.source, local, false))
assertEquals(listOf("/A/local/book.cbz"), f.archivePaths)
assertEquals(0, f.factory.created)
assertTrue(f.db.pageCache(10).isEmpty())
} finally { f.close() }
}
@Test fun localImageAndContentUriKeepTheirOriginalAddress() = runTest {
val f = Fixture(this)
try {
f.fileExists = true
for ((path, expected) in listOf("/local/page.png" to "file:///local/page.png",
"content://books/page.png" to "content://books/page.png")) {
val pages = f.content.pages(null, chapter.copy(url = path), false)
assertEquals(expected, pages.single().url)
assertEquals("page.png", pages.single().fileName)
}
assertEquals(0, f.factory.created)
} finally { f.close() }
}
@Test fun headerFailurePreservesOfflineFallback() = runTest {
val f = Fixture(this)
try {
f.factory.headerAction = { error("Runtime unavailable") }
assertEquals(mapOf("User-Agent" to f.db.settings().userAgent), f.content.headers(f.source))
assertEquals(1, f.factory.disposed)
} finally { f.close() }
}
@Test fun episodeFailureDoesNotFabricateAStreamFromTheChapterUrl() = runTest {
val f = Fixture(this)
try {
f.factory.videoAction = { error("Extraction failed") }
assertFailsWith<IllegalStateException> { f.content.videos(f.source, chapter) }
assertEquals(1, f.factory.disposed)
assertEquals("https://cdn.test/movie", f.content.videos(null, chapter.copy(url = "//cdn.test/movie")).single().url)
assertTrue(f.content.videos(null, chapter.copy(url = "/episode.html")).isEmpty())
} finally { f.close() }
}
@Test fun novelExtractionRetainsCleanedMarkupAndUsesCapturedRuntime() = runTest {
val f = Fixture(this, "A")
try {
assertEquals("<p>A novel</p>", f.content.novelText(f.source, "Novel", chapter.url))
assertEquals(1, f.factory.cleaned)
assertEquals(1, f.factory.disposed)
assertEquals("inline text", f.content.novelText(null, "Novel", "inline text"))
assertEquals(1, f.factory.created)
} finally { f.close() }
}
@Test fun ownerCancellationDiscardsNonCancellablePageResultAndCache() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
f.factory.pageAction = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
listOf(DbPageUrl("late"))
}
val request = async { f.content.pages(f.source, chapter, true) }
entered.await()
f.owner.cancel()
assertFalse(request.isCompleted)
release.complete(Unit)
assertFailsWith<CancellationException> { request.await() }
f.close()
assertTrue(f.db.pageCache(10).isEmpty())
assertEquals(1, f.factory.disposed)
}
@Test fun retirementAdmissionDiscardsLatePagesEvenBeforeOwnerJobCancellation() = runTest {
val f = Fixture(this)
f.factory.pageAction = { f.open = false; listOf(DbPageUrl("late")) }
try {
assertFailsWith<CancellationException> { f.content.pages(f.source, chapter, true) }
assertTrue(f.db.pageCache(10).isEmpty())
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun retirementDuringRuntimeFinalizationPreventsPageCacheWrite() = runTest {
val f = Fixture(this)
f.factory.finalizer = { f.open = false }
try {
assertFailsWith<CancellationException> { f.content.pages(f.source, chapter, true) }
assertTrue(f.db.pageCache(10).isEmpty())
assertEquals(1, f.factory.disposed)
} finally { f.close() }
}
@Test fun lateHeadersCannotStartAnotherExtractionAfterCancellation() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
var pageCalls = 0
f.factory.headerAction = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
emptyMap()
}
f.factory.pageAction = { pageCalls++; listOf(DbPageUrl("late")) }
val request = async { f.content.pages(f.source, chapter, true) }
entered.await(); f.owner.cancel(); release.complete(Unit)
assertFailsWith<CancellationException> { request.await() }
f.close()
assertEquals(0, pageCalls)
assertTrue(f.db.pageCache(10).isEmpty())
assertEquals(1, f.factory.disposed)
}
@Test fun lateNovelHtmlCannotStartCleanupAfterCallerCancellation() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
f.factory.htmlAction = {
withContext(NonCancellable) { entered.complete(Unit); release.await() }
"late"
}
val request = async { f.content.novelText(f.source, "Novel", chapter.url) }
entered.await(); request.cancel()
runCurrent()
assertFalse(request.isCompleted, "caller waits for its owned extraction")
release.complete(Unit)
request.join()
assertEquals(0, f.factory.cleaned)
assertEquals(1, f.factory.disposed)
assertTrue(f.owner.isActive)
f.close()
}
@Test fun callerCancellationJoinsRuntimeFinalizerAndLeavesOtherRequestsUsable() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred<Unit>()
val finalizing = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
f.factory.videoAction = { entered.complete(Unit); awaitCancellation() }
f.factory.finalizer = { finalizing.complete(Unit); release.await() }
val request = async { f.content.videos(f.source, chapter) }
entered.await(); request.cancel(); finalizing.await()
assertFalse(request.isCompleted)
release.complete(Unit); request.join()
assertEquals(1, f.factory.disposed)
f.factory.finalizer = {}
assertEquals(mapOf("User-Agent" to "A", "Referer" to "source"), f.content.headers(f.source))
assertTrue(f.owner.isActive)
f.close()
}
@Test fun closeJoinsRuntimeCleanupRejectsRetainedRequestsAndPreservesParent() = runTest {
val f = Fixture(this)
val entered = CompletableDeferred<Unit>()
val finalizing = CompletableDeferred<Unit>()
val release = CompletableDeferred<Unit>()
f.factory.videoAction = { entered.complete(Unit); awaitCancellation() }
f.factory.finalizer = { finalizing.complete(Unit); release.await() }
val request = async { f.content.videos(f.source, chapter) }
entered.await()
val closing = async { f.content.closeAndJoin() }
finalizing.await()
assertFalse(closing.isCompleted)
release.complete(Unit); closing.await()
assertFailsWith<CancellationException> { request.await() }
assertTrue(f.owner.isActive)
assertFailsWith<CancellationException> { f.content.pages(null, chapter, false) }
assertFailsWith<CancellationException> { f.content.headers(f.source) }
assertFailsWith<CancellationException> { f.content.videos(null, chapter) }
assertFailsWith<CancellationException> { f.content.novelText(null, "Novel", "inline") }
assertEquals(1, f.factory.created)
assertTrue(f.archivePaths.isEmpty())
f.close()
}
@Test fun localNovelParsesCapturedChapterAndEmbeddedImagesWithoutExtension() = runTest {
val f = Fixture(this)
val other = Fixture(this, "B")
try {
f.epubChapters = listOf(LocalEpubChapter("First", "OEBPS/first.xhtml"), LocalEpubChapter("Second", "OEBPS/Text/second.xhtml"))
f.epubHtml = "<h2>Second</h2><p><a href='https://book.test/next'>Next</a></p><img src='../Images/cover%20art.png?size=2#x'>"
f.epubResources["OEBPS/Images/cover art.png"] = byteArrayOf(1, 2, 3)
val opened = mutableListOf<String>()
val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel).parse(opened::add)
assertEquals("Second", assertIs<NovelContentBlock.Text>(parsed.blocks[0]).text.text)
val paragraph = assertIs<NovelContentBlock.Text>(parsed.blocks[1]).text
val link = assertIs<LinkAnnotation.Url>(paragraph.getLinkAnnotations(0, paragraph.length).single().item)
link.linkInteractionListener?.onClick(link)
assertEquals(listOf("https://book.test/next"), opened)
assertContentEquals(byteArrayOf(1, 2, 3), assertIs<NovelImageSource.Embedded>(assertIs<NovelContentBlock.Image>(parsed.blocks[2]).source).bytes)
assertEquals(listOf("/A/book.epub" to 1), f.epubChapterReads)
assertEquals(listOf("/A/book.epub" to "OEBPS/Images/cover art.png"), f.epubResourceReads)
assertEquals(0, f.factory.created)
assertTrue(other.epubChapterReads.isEmpty())
assertTrue(other.epubResourceReads.isEmpty())
} finally { f.close(); other.close() }
}
@Test fun blankLocalChapterFallsBackToRemoteMarkupWithItsLocalResources() = runTest {
val f = Fixture(this)
try {
f.epubHtml = " "
f.factory.htmlAction = { "<p>Remote</p><img src='../Images/cover.png'>" }
f.epubResources["OEBPS/Images/cover.png"] = byteArrayOf(4)
val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel).parse()
assertEquals("Remote", assertIs<NovelContentBlock.Text>(parsed.blocks[0]).text.text)
assertContentEquals(byteArrayOf(4), assertIs<NovelImageSource.Embedded>(assertIs<NovelContentBlock.Image>(parsed.blocks[1]).source).bytes)
assertEquals(1, f.factory.created)
assertEquals(1, f.factory.disposed)
} finally { f.close() }
}
@Test fun malformedEpubIndexDefaultsToZeroAndMissingHrefDoesNotReadImages() = runTest {
val f = Fixture(this)
try {
f.epubChapters = emptyList()
f.epubHtml = "<p>Local</p><img src='https://img.test/cover.png'>"
val parsed = loadNovelDocument(f.content, f.source, "Book", localNovel.copy(archivePath = "/A/book.EPUB#bad")).parse()
assertEquals(listOf("/A/book.EPUB" to 0), f.epubChapterReads)
assertIs<NovelImageSource.Remote>(assertIs<NovelContentBlock.Image>(parsed.blocks[1]).source)
assertTrue(f.epubResourceReads.isEmpty())
} finally { f.close() }
}
@Test fun embeddedResourceCapabilityExpiresAfterParsingEvenWithALiveOwner() = runTest {
val f = Fixture(this)
try {
var retained: ProfileNovelContent? = null
f.content.novelContent(f.source, "Book", localNovel) { retained = it }
assertFailsWith<CancellationException> { assertNotNull(retained).readEmbeddedResource("cover.png") }
assertTrue(f.epubResourceReads.isEmpty())
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun cancellationDuringEpubInventoryPreventsChapterReadAndParsing() = runTest {
val f = Fixture(this)
var parsed = false
f.beforeEpubInventory = { f.owner.cancel() }
try {
assertFailsWith<CancellationException> {
f.content.novelContent(f.source, "Book", localNovel) { parsed = true }
}
assertTrue(f.epubChapterReads.isEmpty())
assertEquals(0, f.factory.created)
assertFalse(parsed)
} finally { f.close() }
}
@Test fun retirementDuringEpubReadPreventsFallbackAndParsing() = runTest {
val f = Fixture(this)
var parsed = false
f.epubHtml = ""
f.beforeEpubChapterRead = { f.open = false }
try {
assertFailsWith<CancellationException> {
f.content.novelContent(f.source, "Book", localNovel) { parsed = true }
}
assertEquals(0, f.factory.created)
assertFalse(parsed)
} finally { f.close() }
}
@Test fun archiveFailureAfterRetirementIsCancellationAndCannotStartUiFallback() = runTest {
val f = Fixture(this)
f.beforeEpubChapterRead = { f.open = false; error("Archive failed after retirement") }
var fallback = false
try {
assertFailsWith<CancellationException> {
eu.friedcutlet.yokan.services.catchingNonCancellation {
loadNovelDocument(f.content, f.source, "Book", localNovel)
}.getOrElse { fallback = true; throw it }
}
assertFalse(fallback)
assertEquals(0, f.factory.created)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun retirementDuringEmbeddedImageReadRejectsTheEntireParsedResult() = runTest {
val f = Fixture(this)
f.epubHtml = "<img src='../Images/first.png'><img src='../Images/second.png'>"
f.beforeEpubResourceRead = { f.open = false }
try {
assertFailsWith<CancellationException> { loadNovelDocument(f.content, f.source, "Book", localNovel) }
assertEquals(1, f.epubResourceReads.size)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun parserFailurePreservesTheContentServiceAndParent() = runTest {
val f = Fixture(this)
try {
assertFailsWith<IllegalArgumentException> {
f.content.novelContent(f.source, "Book", localNovel) { throw IllegalArgumentException("Malformed content") }
}
assertEquals("A epub", loadNovelDocument(f.content, f.source, "Book", localNovel).parse().plainText)
assertTrue(f.owner.isActive)
} finally { f.close() }
}
@Test fun retiredContentCannotReadAnEpubOrStartParsing() = runTest {
val f = Fixture(this)
try {
f.content.closeAndJoin()
assertFailsWith<CancellationException> {
f.content.novelContent(f.source, "Book", localNovel) { error("Retired parser") }
}
assertTrue(f.epubInventoryPaths.isEmpty())
assertTrue(f.epubChapterReads.isEmpty())
assertTrue(f.epubResourceReads.isEmpty())
} finally { f.close() }
}
internal class Fixture(
test: TestScope,
label: String = "A",
fileDispatcher: CoroutineDispatcher = StandardTestDispatcher(test.testScheduler),
) {
val owner = SupervisorJob()
val scope = CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))
val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
sources = listOf(DbSource(id = 7, name = label, version = "1", isAdded = true)),
mangas = listOf(DbManga(id = 1, sourceId = 7)),
chapters = listOf(DbChapter(id = 10, mangaId = 1, url = "/chapter")),
pageCache = emptyList(),
))
val repository = DefaultYokanRepository(db)
val source = requireNotNull(repository.source(7))
val factory = RuntimeFactory(db, label)
var open = true
var archivePages = emptyList<DbPageUrl>()
val archivePaths = mutableListOf<String>()
var fileExists = false
var localFiles = emptyList<LocalFileEntry>()
var localBytes = byteArrayOf()
var epubChapters = listOf(LocalEpubChapter("Chapter", "OEBPS/Text/chapter.xhtml"), LocalEpubChapter("Next", "OEBPS/Text/next.xhtml"))
var epubHtml = "<p>$label epub</p>"
val epubResources = mutableMapOf<String, ByteArray>()
val epubInventoryPaths = mutableListOf<String>()
val epubChapterReads = mutableListOf<Pair<String, Int>>()
val epubResourceReads = mutableListOf<Pair<String, String>>()
var beforeEpubInventory: () -> Unit = {}
var beforeEpubChapterRead: () -> Unit = {}
var beforeEpubResourceRead: () -> Unit = {}
val files = object : LocalFileService {
override val downloadRoot = "/$label/downloads"
override val backupRoot = "/$label/backups"
override val cacheRoot = "/$label/cache"
override fun writeBytes(path: String, bytes: ByteArray) = error("Unexpected write")
override fun readBytes(path: String): ByteArray = error("Unexpected read")
override suspend fun readBytesAsync(path: String, maxBytes: Long): ByteArray = localBytes
override fun canonicalPath(path: String) = path
override fun exists(path: String) = fileExists
override fun deleteRecursively(path: String) = error("Unexpected delete")
override fun directorySize(path: String) = 0L
override fun openLocation(path: String) = false
override fun listLocalEntries(root: String) = emptyList<LocalEntry>()
override fun listFiles(root: String) = localFiles
}
val archives = object : LocalArchiveService {
override fun listPages(archivePath: String): List<DbPageUrl> {
archivePaths += archivePath
return archivePages
}
override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {
epubInventoryPaths += archivePath
beforeEpubInventory()
return epubChapters
}
override fun readEpubChapter(archivePath: String, index: Int): String {
epubChapterReads += archivePath to index
beforeEpubChapterRead()
return epubHtml
}
override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? {
epubResourceReads += archivePath to resourcePath
beforeEpubResourceRead()
return epubResources[resourcePath]
}
override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? = null
}
val content = ProfileReaderContent(
ProfileId.Default, db, factory, ChapterPageResolver(repository, db, factory),
files, archives, scope, fileDispatcher, { open },
)
suspend fun close() { content.closeAndJoin(); owner.cancelAndJoin() }
}
internal class RuntimeFactory(val db: YokanDatabase, label: String) : ExtensionRuntimeFactory {
var created = 0
var disposed = 0
var cleaned = 0
var headerAction: suspend () -> Map<String, String> = { mapOf("User-Agent" to label, "Referer" to "source") }
var pageAction: suspend () -> List<DbPageUrl> = { listOf(DbPageUrl("$label/page", headers = mapOf("referer" to "page"))) }
var videoAction: suspend () -> List<DbVideo> = { listOf(DbVideo(url = "$label/video", quality = "Auto", originalUrl = "$label/video")) }
var htmlAction: suspend () -> String = { "<p>$label novel</p>" }
var finalizer: suspend () -> Unit = {}
override fun create(source: DbSource): ExtensionRuntimeService {
created++
return object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, db) {
override fun dispose() { disposed++ }
override suspend fun headers() = headerAction()
override suspend fun pageList(url: String) = pageAction()
override suspend fun videoList(url: String) = videoAction()
override suspend fun htmlContent(name: String, url: String) = htmlAction()
override suspend fun cleanHtmlContent(html: String): String { cleaned++; return html }
}
}
override suspend fun <T> withRuntime(source: DbSource, block: suspend (ExtensionRuntimeService) -> T): T {
val runtime = create(source)
try { return block(runtime) }
finally { withContext(NonCancellable) { try { finalizer() } finally { runtime.dispose() } } }
}
}
private companion object {
val chapter = Chapter(id = 10, mangaId = 1, name = "Chapter", url = "/chapter")
val localNovel = chapter.copy(archivePath = "/A/book.epub#1")
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/SourceCastTest.kt
- Source · test / fixture · 84 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
17: class SourceCastTest {
46: fun refresh(cast: String?) = repository.upsertRemoteDetail(source.toDomain(), remoteDetailFromJson(Json.parseToJsonElement(
Exact file bytes / download · SHA-256 332b50e1ea6973ec6a5f222d40a124859fca0846d37f539f7bd8872c3517a996.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.extensions.js.remoteDetailFromJson
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlin.test.*
class SourceCastTest {
@Test fun sourcePortraitsResolveWebReferencesWithoutGrantingFileAccess() {
val base = "https://source.example/catalog?token=private#section"
val input = listOf(
"https://cdn.example/a%20b.jpg", "http://cdn.example/b.jpg", "//cdn.example/c.jpg",
"/images/d.jpg", "images/e.jpg", "file:///private/portrait.jpg", "content://provider/portrait",
"opfs://other/portrait", "data:image/png;base64,a", "javascript:alert(1)",
"https://user:secret@cdn.example/f.jpg", "https://cdn.example/line\nbreak.jpg",
"https://cdn.example\\private.jpg", "http:/missing-host", "https://", "https://[broken", "//",
)
val result = normalizeSourceCast(input.mapIndexed { index, url -> TitleCredit("Actor $index", imageUrl = url) }, base)
assertEquals(listOf(
"https://cdn.example/a%20b.jpg", "http://cdn.example/b.jpg", "https://cdn.example/c.jpg",
"https://source.example/images/d.jpg", "https://source.example/catalog/images/e.jpg",
), result.take(5).map { it.imageUrl })
result.drop(5).forEachIndexed { index, credit -> assertNull(credit.imageUrl, input[index + 5]) }
assertNull(normalizeSourceCast(listOf(TitleCredit("Actor", imageUrl = "images/a.jpg")), "file:///local").single().imageUrl)
assertNull(normalizeSourceCast(listOf(TitleCredit("Actor", imageUrl = "a.jpg")), "https://user:pass@source.example").single().imageUrl)
assertEquals("https://cdn.example/a.jpg", normalizeSourceCast(listOf(TitleCredit("Actor", imageUrl = "https://cdn.example/a.jpg")), "").single().imageUrl)
}
@Test fun extensionCastRefreshesPreserveUserDataAndDistinguishOmissionFromClear() {
val source = DbSource(id = 42, name = "Anime source", baseUrl = "https://source.example", itemType = DbItemType.Anime)
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(DbManga(id = 1, name = "Title", link = "/anime/title", sourceId = source.id,
itemType = source.itemType, favorite = true, privateNote = "Keep my note", cast = listOf(TitleCredit("Old actor")))),
chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Episode 1", url = "/episode/1", isRead = true, isBookmarked = true, lastPageRead = "5")),
))
val repository = DefaultYokanRepository(database)
fun refresh(cast: String?) = repository.upsertRemoteDetail(source.toDomain(), remoteDetailFromJson(Json.parseToJsonElement(
"""{"title":"Title","url":"/anime/title","episodes":[{"name":"Episode 1","url":"/episode/1"}]${cast?.let { ",\"cast\":$it" }.orEmpty()}}""",
)))
val saved = refresh("""[{"name":"Actor","character":"Hero","image_url":"/portraits/a.jpg"}]""")
assertEquals(listOf(TitleCredit("Actor", character = "Hero", imageUrl = "https://source.example/portraits/a.jpg")), saved.cast)
assertEquals(saved.cast, refresh(null).cast)
assertEquals(saved.cast, refresh("""[{"name":12}]""").cast)
assertEquals(saved.cast, refresh("{}").cast)
assertEquals(emptyList(), refresh("[]").cast)
assertEquals("Keep my note", database.manga(1)?.privateNote)
assertTrue(requireNotNull(database.manga(1)).favorite)
val chapter = requireNotNull(database.chapter(10))
assertTrue(chapter.isRead)
assertTrue(chapter.isBookmarked)
assertEquals("5", chapter.lastPageRead)
}
@Test fun offlineDetailsStayWithinTheRequestedSourceIncludingCreditsAndChapters() = runTest {
val source = DbSource(id = 42, name = "Requested", itemType = DbItemType.Anime)
val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(
mangas = listOf(
DbManga(id = 1, name = "Other source", link = "/same", sourceId = 43, itemType = DbItemType.Anime, cast = listOf(TitleCredit("Other actor"))),
DbManga(id = 2, name = "Mine", link = "/same", sourceId = 42, itemType = DbItemType.Anime, cast = listOf(TitleCredit("My actor"))),
DbManga(id = 3, name = "Legacy", source = "Requested", link = "/legacy", itemType = DbItemType.Anime, cast = listOf(TitleCredit("Legacy actor"))),
),
chapters = listOf(
DbChapter(id = 10, mangaId = 1, name = "Other episode", url = "/other"),
DbChapter(id = 20, mangaId = 2, name = "My episode", url = "/mine"),
),
))
val fallback = DatabaseFallbackRuntimeService(source, database)
assertEquals(listOf(TitleCredit("My actor")), fallback.detail("/same").cast)
assertEquals(listOf("/mine"), fallback.detail("/same").chapters.map { it.url })
assertEquals(listOf(TitleCredit("Legacy actor")), fallback.detail("/legacy").cast)
assertTrue(fallback.detail("/missing").chapters.isEmpty())
assertNull(fallback.detail("/missing").cast)
assertTrue(DatabaseFallbackRuntimeService(source.copy(id = 44, name = "Unrelated"), database).detail("/same").chapters.isEmpty())
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/SourceCatalogServiceTest.kt
- Source · test / fixture · 257 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
19: class SourceCatalogServiceTest {
21: fun resolvesAndFetchesPublishedAssetsFromHttpIndex() = runTest {
42: fun resolvesQueryFragmentAndDotSegments() = runTest {
55: fun loadsIndexAndPayloadThroughFileTransport() = runTest {
74: fun officialLnReaderCatalogSelectsNovelRuntime() = runTest {
91: fun mihonEntriesKeepUpstreamSourceIds() = runTest {
111: fun readsGzipProtobufRepository() = runTest {
134: fun rejectsEmptyAndBlankPayloads() = runTest {
164: private class MapHttpService(
167: override suspend fun request(request: HttpRequest): HttpResponse {
174: private class MapLocalFileService(
181: override fun writeBytes(path: String, bytes: ByteArray) = error("Read-only fixture")
182: override fun readBytes(path: String): ByteArray = files[path] ?: ByteArray(0)
183: override fun canonicalPath(path: String): String = path.removePrefix("file://")
184: override fun exists(path: String): Boolean = path in files
185: override fun deleteRecursively(path: String): Boolean = false
186: override fun directorySize(path: String): Long = 0L
187: override fun openLocation(path: String): Boolean = false
188: override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()
189: override fun listFiles(root: String): List<LocalFileEntry> = emptyList()
257: private fun String.hexBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
Exact file bytes / download · SHA-256 21c5159a616a4cab91f83538c941942cc15c352db78c0a1528769c91097098e9.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.files.LocalEntry
import eu.friedcutlet.yokan.services.files.LocalFileEntry
import eu.friedcutlet.yokan.services.files.LocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
class SourceCatalogServiceTest {
@Test
fun resolvesAndFetchesPublishedAssetsFromHttpIndex() = runTest {
val repoUrl = "https://example.test/repos/yokan/index.json"
val sourceUrl = "https://example.test/repos/yokan/sources/manga/mangadex/source.js"
val service = HttpSourceCatalogService(
MapHttpService(
mapOf(
repoUrl to RepositoryIndex.encodeToByteArray(),
sourceUrl to ExtensionSource.encodeToByteArray(),
),
),
)
val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())
assertEquals(sourceUrl, source.sourceCodeUrl)
assertEquals("https://example.test/icons/mangadex.png", source.iconUrl)
assertEquals(DbItemType.Manga, source.itemType)
assertEquals(ExtensionSource, service.fetchSourcePayload(source)?.decodeToString())
}
@Test
fun resolvesQueryFragmentAndDotSegments() = runTest {
val repoUrl = "https://example.test/repos/yokan/indexes/index.json?token=secret#catalog"
val service = HttpSourceCatalogService(
MapHttpService(mapOf(repoUrl to RelativeReferenceIndex.encodeToByteArray())),
)
val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())
assertEquals("https://example.test/repos/yokan/payloads/mangadex.js?raw=1", source.sourceCodeUrl)
assertEquals("https://example.test/repos/yokan/indexes/icons/mangadex.png#icon", source.iconUrl)
}
@Test
fun loadsIndexAndPayloadThroughFileTransport() = runTest {
val repoUrl = "file:///tmp/yokan-sauces/build/repository/manga_index.json"
val sourceUrl = "file:///tmp/yokan-sauces/build/repository/sources/manga/mangadex/source.js"
val files = MapLocalFileService(
mapOf(
repoUrl to RepositoryIndex.encodeToByteArray(),
sourceUrl to ExtensionSource.encodeToByteArray(),
),
)
val service = HttpSourceCatalogService(MapHttpService(emptyMap()), files)
val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())
assertEquals(sourceUrl, source.sourceCodeUrl)
assertEquals("file:///icons/mangadex.png", source.iconUrl)
assertEquals(ExtensionSource, service.fetchSourcePayload(source)?.decodeToString())
}
@Test
fun officialLnReaderCatalogSelectsNovelRuntime() = runTest {
val repoUrl = "https://example.test/plugins.min.json"
val payloadUrl = "https://example.test/novelupdates.js"
val index = """[{
"id":"novelupdates", "name":"Novel Updates", "site":"https://www.novelupdates.com/",
"lang":"English", "version":"0.9.9", "url":"$payloadUrl", "iconUrl":"https://example.test/icon.png"
}]"""
val service = HttpSourceCatalogService(MapHttpService(mapOf(
repoUrl to index.encodeToByteArray(), payloadUrl to "exports.default = {};".encodeToByteArray(),
)))
val source = service.fetchSources(repoUrl, DbItemType.Novel).single()
assertEquals(DbSourceCodeLanguage.LnReader, source.sourceCodeLanguage)
assertEquals("en", source.lang)
assertEquals("exports.default = {};", service.fetchSourcePayload(source)?.decodeToString())
}
@Test
fun mihonEntriesKeepUpstreamSourceIds() = runTest {
val repoUrl = "https://example.test/repos/mihon/index.min.json"
val service = HttpSourceCatalogService(
MapHttpService(mapOf(repoUrl to MihonRepositoryIndex.encodeToByteArray())),
)
val sources = service.fetchSources(repoUrl, DbItemType.Anime)
assertEquals(2, sources.size)
assertEquals(
listOf(
"""{"sourceId":"4864082317433034574"}""",
"""{"sourceId":"8842237058298566885"}""",
),
sources.map { it.additionalParams },
)
assertEquals(sources.size, sources.map { it.id }.toSet().size)
}
@Test
fun readsGzipProtobufRepository() = runTest {
val repoUrl = "https://example.test/repos/yokan/index.pb?token=secret#catalog"
val service = HttpSourceCatalogService(
MapHttpService(mapOf(repoUrl to ProtobufRepositoryIndex)),
)
val source = assertNotNull(service.fetchSources(repoUrl, DbItemType.Manga).singleOrNull())
assertEquals("PB Source", source.name)
assertEquals("https://example.test/pb", source.baseUrl)
assertEquals("en", source.lang)
assertEquals(12345L, source.id)
assertEquals("""{"sourceId":"12345"}""", source.additionalParams)
assertEquals("https://example.test/repos/yokan/payload.apk", source.sourceCodeUrl)
assertEquals("https://example.test/repos/yokan/icons/pb.png", source.iconUrl)
assertEquals("1.2.3", source.version)
assertTrue(source.isNsfw)
assertEquals(DbItemType.Manga, source.itemType)
assertEquals(DbSourceCodeLanguage.Mihon, source.sourceCodeLanguage)
assertTrue(service.validateRepository(repoUrl))
}
@Test
fun rejectsEmptyAndBlankPayloads() = runTest {
val httpRepoUrl = "https://example.test/repos/yokan/index.json"
val httpSourceUrl = "https://example.test/repos/yokan/sources/manga/mangadex/source.js"
val httpService = HttpSourceCatalogService(
MapHttpService(
mapOf(
httpRepoUrl to RepositoryIndex.encodeToByteArray(),
httpSourceUrl to " ".encodeToByteArray(),
),
),
)
val httpSource = assertNotNull(httpService.fetchSources(httpRepoUrl, DbItemType.Manga).singleOrNull())
assertNull(httpService.fetchSourcePayload(httpSource))
val fileRepoUrl = "file:///tmp/yokan-sauces/build/repository/index.json"
val fileSourceUrl = "file:///tmp/yokan-sauces/build/repository/sources/manga/mangadex/source.js"
val fileService = HttpSourceCatalogService(
MapHttpService(emptyMap()),
MapLocalFileService(
mapOf(
fileRepoUrl to RepositoryIndex.encodeToByteArray(),
fileSourceUrl to ByteArray(0),
),
),
)
val fileSource = assertNotNull(fileService.fetchSources(fileRepoUrl, DbItemType.Manga).singleOrNull())
assertNull(fileService.fetchSourcePayload(fileSource))
}
}
private class MapHttpService(
private val responses: Map<String, ByteArray>,
) : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse {
val bytes = responses[request.url]
?: return HttpResponse(statusCode = 404, body = "")
return HttpResponse(statusCode = 200, body = bytes.decodeToString(), bodyBytes = bytes)
}
}
private class MapLocalFileService(
private val files: Map<String, ByteArray>,
) : LocalFileService {
override val downloadRoot: String = ""
override val backupRoot: String = ""
override val cacheRoot: String = ""
override fun writeBytes(path: String, bytes: ByteArray) = error("Read-only fixture")
override fun readBytes(path: String): ByteArray = files[path] ?: ByteArray(0)
override fun canonicalPath(path: String): String = path.removePrefix("file://")
override fun exists(path: String): Boolean = path in files
override fun deleteRecursively(path: String): Boolean = false
override fun directorySize(path: String): Long = 0L
override fun openLocation(path: String): Boolean = false
override fun listLocalEntries(root: String): List<LocalEntry>? = emptyList()
override fun listFiles(root: String): List<LocalFileEntry> = emptyList()
}
private const val RepositoryIndex = """
[
{
"id": 810342358,
"name": "MangaDex",
"baseUrl": "https://mangadex.org",
"lang": "en",
"itemType": "Manga",
"sourceCodeLanguage": "JavaScript",
"sourceCodeUrl": "sources/manga/mangadex/source.js",
"iconUrl": "/icons/mangadex.png",
"version": "0.3.0"
},
{
"id": 920451267,
"name": "AnimePahe",
"baseUrl": "https://animepahe.pw",
"lang": "en",
"itemType": "Anime",
"sourceCodeLanguage": "JavaScript",
"sourceCodeUrl": "sources/anime/animepahe/source.js",
"version": "0.3.0"
}
]
"""
private const val RelativeReferenceIndex = """
[
{
"id": 810342358,
"name": "MangaDex",
"baseUrl": "https://mangadex.org",
"lang": "en",
"itemType": "Manga",
"sourceCodeLanguage": "JavaScript",
"sourceCodeUrl": "../payloads/./mangadex.js?raw=1",
"iconUrl": "./icons/../icons/mangadex.png#icon",
"version": "0.3.0"
}
]
"""
private const val ExtensionSource = "class DefaultExtension extends MProvider {}"
private const val MihonRepositoryIndex = """
[
{
"name": "Aniyomi: MyReadingManga",
"pkg": "eu.kanade.tachiyomi.animeextension.all.myreadingmanga",
"apk": "aniyomi-all.myreadingmanga-v14.2.apk",
"lang": "all",
"code": 2,
"version": "14.2",
"nsfw": 1,
"sources": [
{"name": "MyReadingManga", "lang": "ar", "id": "4864082317433034574", "baseUrl": "https://myreadingmanga.info"},
{"name": "MyReadingManga", "lang": "id", "id": "8842237058298566885", "baseUrl": "https://myreadingmanga.info"}
]
}
]
"""
private val ProtobufRepositoryIndex =
"1f8b08000000000002ff5bc556cf55cbc513e0a4e05a51929a579c999f27c4955aaa57925a5ca2579024a5c9c55d905899939f98a29758902dc493999c9f57ac5f90a4579097be4a1e2e979558a4a165c46aa867a4676cc1eca4cdb1334188136868707e695172aa14536a9e927846494941b195be7e6a45626e414e2ad80aa0490026f04bc782000000".hexBytes()
private fun String.hexBytes(): ByteArray = chunked(2).map { it.toInt(16).toByte() }.toByteArray()
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/SourceInstallServiceTest.kt
- Source · test / fixture · 62 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
17: class SourceInstallServiceTest {
19: fun freshInstallDiscoversNothingUntilTheUserAddsRepositories() = runTest {
25: override suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource> {
29: override suspend fun validateRepository(repoUrl: String): Boolean = true
30: override suspend fun fetchSourcePayload(source: DbSource): ByteArray? {
36: override fun create(source: DbSource): ExtensionRuntimeService =
Exact file bytes / download · SHA-256 2eb370f3de643b574d1124fd9bd2f25399cb4ff1a6ef433fcfb8ca09b4aaf59a.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.toDb
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbRepo
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.domain.ItemType
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class SourceInstallServiceTest {
@Test
fun freshInstallDiscoversNothingUntilTheUserAddsRepositories() = runTest {
val database = InMemoryYokanDatabase()
val repository = DefaultYokanRepository(database)
val catalogRequests = mutableListOf<Pair<String, DbItemType>>()
var payloadRequests = 0
val catalog = object : SourceCatalogService {
override suspend fun fetchSources(repoUrl: String, itemType: DbItemType): List<DbSource> {
catalogRequests += repoUrl to itemType
return listOf(DbSource(id = itemType.ordinal.toLong() + 1, name = "User source", itemType = itemType))
}
override suspend fun validateRepository(repoUrl: String): Boolean = true
override suspend fun fetchSourcePayload(source: DbSource): ByteArray? {
payloadRequests++
return null
}
}
val runtimeFactory = object : ExtensionRuntimeFactory {
override fun create(source: DbSource): ExtensionRuntimeService =
error("Repository discovery must not execute extensions")
}
val service = SourceInstallService(
database, repository, catalog, runtimeFactory,
SettingsStore(repository, backgroundScope) {},
ChapterPageResolver(repository, database, runtimeFactory),
)
service.refreshAllRepositories()
assertTrue(catalogRequests.isEmpty(), "Startup refresh must not contact any catalog on a fresh install")
assertTrue(database.sources().isEmpty())
ItemType.entries.forEach { assertTrue(repository.repositories(it).isEmpty()) }
val userRepositories = ItemType.entries.associateWith { type ->
DbRepo(name = "User repository", jsonUrl = "https://catalog.example/${type.name.lowercase()}/index.json")
}
userRepositories.forEach { (type, repo) -> repository.upsertRepository(type, repo) }
service.refreshAllRepositories()
assertEquals(userRepositories.map { (type, repo) -> repo.jsonUrl to type.toDb() }, catalogRequests)
assertEquals(ItemType.entries.size, database.sources().size)
database.sources().forEach { assertFalse(it.isAdded, "Discovering a user catalog must not install extensions") }
assertEquals(0, payloadRequests)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/SourceRepositoryUrlsTest.kt
- Source · test / fixture · 87 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class SourceRepositoryUrlsTest {
12: fun detectsDuplicatesWithCaseInsensitivityAndTrailingSlashes() {
42: fun deduplicatesListOfReposPreservingFirstOccurrence() {
57: fun infersSensibleRepoNameFromUrlWhenNameIsIndexJsonOrEmpty() {
Exact file bytes / download · SHA-256 aad368c4c683dab3beb0cb7387749e7d8d4d34c9c8164be5475259a42f813d0c.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbRepo
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class SourceRepositoryUrlsTest {
@Test
fun detectsDuplicatesWithCaseInsensitivityAndTrailingSlashes() {
val existingRepos = listOf(
DbRepo(
name = "Keiyoushi",
jsonUrl = "https://raw.githubusercontent.com/keiyoushi/extensions/repo/index.min.json",
),
DbRepo(
name = "TestRepo",
jsonUrl = "https://example.com/repo/",
),
)
assertTrue(
SourceRepositoryUrls.isDuplicate(
"https://raw.githubusercontent.com/keiyoushi/extensions/repo/index.min.json",
existingRepos,
)
)
assertTrue(
SourceRepositoryUrls.isDuplicate(
"HTTPS://RAW.GITHUBUSERCONTENT.COM/KEIYOUSHI/EXTENSIONS/REPO/INDEX.MIN.JSON",
existingRepos,
)
)
assertTrue(SourceRepositoryUrls.isDuplicate("https://example.com/repo", existingRepos))
assertTrue(SourceRepositoryUrls.isDuplicate("https://example.com/repo/", existingRepos))
assertFalse(SourceRepositoryUrls.isDuplicate("https://example.com/other-repo", existingRepos))
}
@Test
fun deduplicatesListOfReposPreservingFirstOccurrence() {
val repos = listOf(
DbRepo(name = "First", jsonUrl = "https://example.com/repo1.json"),
DbRepo(name = "Duplicate", jsonUrl = "https://example.com/repo1.json"),
DbRepo(name = "Case Variant", jsonUrl = "HTTPS://EXAMPLE.COM/REPO1.JSON"),
DbRepo(name = "Second", jsonUrl = "https://example.com/repo2.json"),
)
val deduplicated = SourceRepositoryUrls.deduplicate(repos)
assertEquals(2, deduplicated.size)
assertEquals("First", deduplicated.first().name)
assertEquals("Second", deduplicated.last().name)
}
@Test
fun infersSensibleRepoNameFromUrlWhenNameIsIndexJsonOrEmpty() {
assertEquals(
"Mangayomi extensions (m2k3a)",
SourceRepositoryUrls.resolveDisplayName(
"Mangayomi extensions (m2k3a)",
"https://m2k3a.github.io/mangayomi-extensions/index.json",
)
)
assertEquals(
"mangayomi-extensions",
SourceRepositoryUrls.resolveDisplayName(
"index.json",
"https://m2k3a.github.io/mangayomi-extensions/index.json",
)
)
assertEquals(
"mangayomi-extensions",
SourceRepositoryUrls.resolveDisplayName(
null,
"https://m2k3a.github.io/mangayomi-extensions/index.json",
)
)
assertEquals(
"custom-repo",
SourceRepositoryUrls.resolveDisplayName(
"",
"https://example.com/custom-repo/",
)
)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/VersionComparisonTest.kt
- Source · test / fixture · 75 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class VersionComparisonTest {
10: fun standardSemverComparisons() {
19: fun multiDigitSegmentComparison() {
30: fun differentSegmentLengths() {
39: fun handlesLeadingVPrefix() {
47: fun handlesBuildMetadataAndPreReleaseSuffixes() {
64: fun handlesLetterSuffixes() {
71: fun handlesWhitespaceGracefully() {
Exact file bytes / download · SHA-256 307015ad70b6ca616924193149c41e89a8fc634abe1d6806195378565318dda0.
Complete file
package eu.friedcutlet.yokan.services.extensions
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class VersionComparisonTest {
@Test
fun standardSemverComparisons() {
assertEquals(0, VersionComparison.compare("0.9.1", "0.9.1"))
assertTrue(VersionComparison.compare("0.9.1", "0.9.2") < 0)
assertTrue(VersionComparison.compare("0.9.2", "0.9.1") > 0)
assertTrue(VersionComparison.compare("0.9.1", "1.0.0") < 0)
assertTrue(VersionComparison.compare("1.0.0", "0.9.1") > 0)
}
@Test
fun multiDigitSegmentComparison() {
// Critical regression test from Mangayomi ed4f411b: 9 must be less than 10
assertTrue(VersionComparison.compare("0.9.1", "0.10.0") < 0)
assertTrue(VersionComparison.compare("0.9", "0.10") < 0)
assertTrue(VersionComparison.compare("0.10.0", "0.9.1") > 0)
assertTrue(VersionComparison.compare("0.2", "0.11") < 0)
assertTrue(VersionComparison.compare("0.11", "0.2") > 0)
assertTrue(VersionComparison.compare("0.100.0", "0.99.9") > 0)
}
@Test
fun differentSegmentLengths() {
assertEquals(0, VersionComparison.compare("0.9", "0.9.0"))
assertEquals(0, VersionComparison.compare("0.9.0", "0.9"))
assertTrue(VersionComparison.compare("0.9.1", "0.9.1.1") < 0)
assertTrue(VersionComparison.compare("0.9.1.1", "0.9.1") > 0)
assertEquals(0, VersionComparison.compare("1", "1.0.0.0"))
}
@Test
fun handlesLeadingVPrefix() {
assertEquals(0, VersionComparison.compare("v0.9.1", "0.9.1"))
assertEquals(0, VersionComparison.compare("V0.9.1", "v0.9.1"))
assertTrue(VersionComparison.compare("v0.9.1", "v0.10.0") < 0)
assertTrue(VersionComparison.compare("v0.10.0", "v0.9.1") > 0)
}
@Test
fun handlesBuildMetadataAndPreReleaseSuffixes() {
// Build metadata ignored
assertEquals(0, VersionComparison.compare("0.9.1+119", "0.9.1"))
assertTrue(VersionComparison.compare("0.9.1+119", "0.10.0") < 0)
// Normal release > pre-release
assertTrue(VersionComparison.compare("0.9.1", "0.9.1-beta") > 0)
assertTrue(VersionComparison.compare("0.9.1-beta", "0.9.1") < 0)
assertTrue(VersionComparison.compare("v0.9.1-alpha.1", "0.9.2") < 0)
// Pre-release ordering
assertTrue(VersionComparison.compare("1.0.0-alpha", "1.0.0-beta") < 0)
assertTrue(VersionComparison.compare("1.0.0-beta.1", "1.0.0-beta.2") < 0)
assertTrue(VersionComparison.compare("1.0.0-beta.2", "1.0.0-beta.10") < 0)
}
@Test
fun handlesLetterSuffixes() {
assertTrue(VersionComparison.compare("1.4a", "1.4b") < 0)
assertTrue(VersionComparison.compare("1.4b", "1.4") < 0) // pre-release b vs full 1.4
assertTrue(VersionComparison.compare("1.4", "1.3b") > 0)
}
@Test
fun handlesWhitespaceGracefully() {
assertEquals(0, VersionComparison.compare(" 0.9.1 ", "0.9.1"))
assertTrue(VersionComparison.compare(" v0.9.1 ", " 0.10.0 ") < 0)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuExtensionTest.kt
- Source · test / fixture · 287 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
20: class AidokuExtensionTest {
22: private class ScriptedHttpService(
25: override suspend fun request(request: HttpRequest): HttpResponse = handler(request)
26: override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
34: fun postcardSerializesAndDeserializesPrimitives() {
72: fun postcardSerializesAndDeserializesMangaPageResult() {
121: fun aidokuPackageFromZipEntriesParsesMetadataAndCreatesDbSource() {
165: fun aidokuWasmRuntimeDisposalFreesResources() = runTest {
190: fun aidokuExtensionRuntimeServiceExecutesCallsAndDisposes() = runTest {
Exact file bytes / download · SHA-256 b8d32e20d5a51c09f451b96c6e996582ae422e1dbb048ed5bb521cdaae72af4b.
Complete file
package eu.friedcutlet.yokan.services.extensions.aidoku
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.HttpStreamResponse
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class AidokuExtensionTest {
private class ScriptedHttpService(
private val handler: suspend (HttpRequest) -> HttpResponse,
) : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse = handler(request)
override suspend fun stream(request: HttpRequest, onChunk: suspend (ByteArray) -> Unit): HttpStreamResponse {
val res = request(request)
if (res.bodyBytes.isNotEmpty()) onChunk(res.bodyBytes)
return HttpStreamResponse(res.statusCode, res.headers, res.setCookies)
}
}
@Test
fun postcardSerializesAndDeserializesPrimitives() {
val writer = AidokuPostcardWriter()
writer.writeBool(true)
writer.writeBool(false)
writer.writeU8(255)
writer.writeI8(-12)
writer.writeU16(65535)
writer.writeI16(-32000)
writer.writeU32(4000000000L)
writer.writeI32(-2000000000)
writer.writeI64(-9000000000000000000L)
writer.writeF32(3.1415f)
writer.writeF64(2.718281828459045)
writer.writeString("Hello, Aidoku Postcard!")
writer.writeBytes(byteArrayOf(1, 2, 3, 4, 5))
val bytes = writer.toByteArray()
val reader = AidokuPostcardReader(bytes)
assertTrue(reader.readBool())
assertTrue(!reader.readBool())
assertEquals(255, reader.readU8())
assertEquals(-12, reader.readI8())
assertEquals(65535, reader.readU16())
assertEquals(-32000, reader.readI16())
assertEquals(4000000000L, reader.readU32())
assertEquals(-2000000000, reader.readI32())
assertEquals(-9000000000000000000L, reader.readI64())
assertEquals(3.1415f, reader.readF32())
assertEquals(2.718281828459045, reader.readF64())
assertEquals("Hello, Aidoku Postcard!", reader.readString())
val readBytes = reader.readBytes()
assertEquals(5, readBytes.size)
assertEquals(1, readBytes[0])
assertEquals(5, readBytes[4])
}
@Test
fun postcardSerializesAndDeserializesMangaPageResult() {
val manga1 = AidokuManga(
key = "manga-1",
title = "Sousou no Frieren",
cover = "https://example.com/cover.jpg",
artists = listOf("Abe Tsukasa"),
authors = listOf("Yamada Kanehito"),
description = "The adventure is over, but life goes on.",
url = "https://example.com/frieren",
tags = listOf("Adventure", "Drama", "Fantasy"),
status = 1,
contentRating = 1,
viewer = 2,
)
val manga2 = AidokuManga(
key = "manga-2",
title = "Dungeon Meshi",
status = 2,
)
val original = AidokuPageResult(
entries = listOf(manga1, manga2),
hasNextPage = true,
)
val writer = AidokuPostcardWriter()
writer.writeMangaPageResult(original)
val bytes = writer.toByteArray()
val decoded = AidokuPostcardReader(bytes).readMangaPageResult()
assertEquals(2, decoded.entries.size)
assertTrue(decoded.hasNextPage)
val decoded1 = decoded.entries[0]
assertEquals("manga-1", decoded1.key)
assertEquals("Sousou no Frieren", decoded1.title)
assertEquals("https://example.com/cover.jpg", decoded1.cover)
assertEquals(listOf("Abe Tsukasa"), decoded1.artists)
assertEquals(listOf("Yamada Kanehito"), decoded1.authors)
assertEquals("The adventure is over, but life goes on.", decoded1.description)
assertEquals(listOf("Adventure", "Drama", "Fantasy"), decoded1.tags)
assertEquals(1, decoded1.status)
val decoded2 = decoded.entries[1]
assertEquals("manga-2", decoded2.key)
assertEquals("Dungeon Meshi", decoded2.title)
assertEquals(2, decoded2.status)
}
@Test
fun aidokuPackageFromZipEntriesParsesMetadataAndCreatesDbSource() {
val sourceJson = """
{
"info": {
"id": "en.mangadex",
"name": "MangaDex",
"version": 2,
"url": "https://mangadex.org",
"languages": ["en", "ja"],
"contentRating": 0
},
"listings": [
{ "id": "popular", "name": "Popular", "kind": 0 },
{ "id": "latest", "name": "Latest Updates", "kind": 1 }
]
}
""".trimIndent()
val wasmBytes = byteArrayOf(0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00) // \0asm v1
val entries = mapOf(
"source.json" to sourceJson.encodeToByteArray(),
"main.wasm" to wasmBytes,
)
val pkg = AidokuPackage.fromZipEntries(entries)
assertNotNull(pkg)
assertEquals("en.mangadex", pkg.sourceInfo.id)
assertEquals("MangaDex", pkg.sourceInfo.name)
assertEquals(2, pkg.sourceInfo.version)
assertEquals("https://mangadex.org", pkg.sourceInfo.url)
assertEquals(listOf("en", "ja"), pkg.sourceInfo.languages)
assertEquals(2, pkg.sourceInfo.listings.size)
assertEquals("popular", pkg.sourceInfo.listings[0].id)
val dbSource = pkg.toDbSource("https://repo.example.com/mangadex.aidx")
assertEquals("MangaDex", dbSource.name)
assertEquals("en", dbSource.lang)
assertEquals("2.0.0", dbSource.version)
assertEquals(DbSourceCodeLanguage.Aidoku, dbSource.sourceCodeLanguage)
assertEquals(DbItemType.Manga, dbSource.itemType)
assertTrue(dbSource.isActive)
}
@Test
fun aidokuWasmRuntimeDisposalFreesResources() = runTest {
val info = AidokuSourceInfo(id = "test", name = "Test Source")
val pkg = AidokuPackage(
sourceInfo = info,
wasmBytes = byteArrayOf(0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00),
rawSourceJson = "{}",
)
val http = ScriptedHttpService { HttpResponse(200, "OK") }
val runtime = AidokuWasmRuntime(pkg, http)
assertTrue(runtime.isWasmValid)
runtime.store.add("sample-descriptor-data")
assertNotNull(runtime.store.get(1))
runtime.dispose()
assertEquals(null, runtime.store.get(1))
// `runTest` returns a Promise on JS/wasm instead of rethrowing, so a nested
// `runTest` inside assertFailsWith never surfaces the failure. Await the call here.
assertFailsWith<IllegalStateException> {
runtime.getMangaList(AidokuListing("popular", "Popular"), 1)
}
}
@Test
fun aidokuExtensionRuntimeServiceExecutesCallsAndDisposes() = runTest {
val info = AidokuSourceInfo(
id = "en.sample",
name = "Sample Aidoku",
url = "https://sample.example.com",
listings = listOf(AidokuListing("popular", "Popular")),
)
val pkg = AidokuPackage(
sourceInfo = info,
wasmBytes = byteArrayOf(0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00),
rawSourceJson = "{}",
)
// Mock WASM handler for tests
AidokuWasmRuntime.activeMockHandler = { name, input, page ->
val writer = AidokuPostcardWriter()
when (name) {
"get_manga_list", "get_search_manga_list" -> {
writer.writeMangaPageResult(
AidokuPageResult(
entries = listOf(
AidokuManga(key = "frieren", title = "Frieren", cover = "https://img.com/1.jpg"),
),
hasNextPage = false,
),
)
}
"get_manga_details" -> {
writer.writeManga(
AidokuManga(
key = "frieren",
title = "Sousou no Frieren",
authors = listOf("Yamada"),
status = 1,
),
)
}
"get_chapter_list" -> {
writer.writeList(
listOf(
AidokuChapter(key = "ch-1", title = "Chapter 1", chapterNumber = 1.0f),
),
) { w, ch -> w.writeChapter(ch) }
}
"get_page_list" -> {
writer.writeList(
listOf(
AidokuPage(index = 0, url = "https://img.com/p1.jpg"),
AidokuPage(index = 1, url = "https://img.com/p2.jpg"),
),
) { w, p ->
w.writeVarUint(p.index.toLong())
w.writeU8(0) // url type
w.writeString(p.url)
w.writeU8(0) // no context
w.writeOption<String>(null) { _, _ -> }
w.writeOption<String>(null) { _, _ -> }
}
}
}
writer.toByteArray()
}
try {
val dbSource = DbSource(
id = 99999L,
name = "Sample Aidoku",
baseUrl = "https://sample.example.com",
sourceCodeLanguage = DbSourceCodeLanguage.Aidoku,
)
val http = ScriptedHttpService { HttpResponse(200, "OK") }
val runtimeService = AidokuExtensionRuntimeService(
source = dbSource,
http = http,
packageOverride = pkg,
)
val popular = runtimeService.popular(1)
assertEquals(1, popular.items.size)
assertEquals("Frieren", popular.items[0].title)
val detail = runtimeService.detail("https://sample.example.com/manga/frieren")
assertEquals("Sousou no Frieren", detail.title)
assertEquals("Yamada", detail.author)
assertEquals(1, detail.chapters.size)
assertEquals("Chapter 1", detail.chapters[0].title)
val pages = runtimeService.pageList("https://sample.example.com/manga/frieren/ch-1")
assertEquals(2, pages.size)
assertEquals("https://img.com/p1.jpg", pages[0].url)
assertEquals("https://img.com/p2.jpg", pages[1].url)
runtimeService.dispose()
} finally {
AidokuWasmRuntime.activeMockHandler = null
}
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlSelectorMatcherTest.kt
- Source · test / fixture · 41 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class HtmlSelectorMatcherTest {
20: fun matchesClassSelector() {
26: fun matchesIdSelector() {
32: fun matchesAttributeSelector() {
38: fun returnsEmptyListWhenNothingMatches() {
Exact file bytes / download · SHA-256 2cd2a04ca6364093d9f9ed4feeeb99666dec1f40c42382b2ffa98eddc7bf772c.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class HtmlSelectorMatcherTest {
private val sample = """
<html>
<body>
<div class="title">Hello world</div>
<a class="link" href="/one">First</a>
<a class="link" href="/two">Second</a>
<p id="description">Lorem ipsum</p>
</body>
</html>
""".trimIndent()
@Test
fun matchesClassSelector() {
val matches = HtmlSelectorMatcher.match(sample, ".link")
assertEquals(listOf("First", "Second"), matches)
}
@Test
fun matchesIdSelector() {
val matches = HtmlSelectorMatcher.match(sample, "#description")
assertEquals(listOf("Lorem ipsum"), matches)
}
@Test
fun matchesAttributeSelector() {
val matches = HtmlSelectorMatcher.match(sample, "a[href]")
assertTrue(matches.containsAll(listOf("First", "Second")))
}
@Test
fun returnsEmptyListWhenNothingMatches() {
assertEquals(emptyList(), HtmlSelectorMatcher.match(sample, "nope"))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlXPathMatcherTest.kt
- Source · test / fixture · 46 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class HtmlXPathMatcherTest {
19: fun extractsTextNodes() {
25: fun extractsAttributeValues() {
31: fun honorsContainsClassPredicate() {
37: fun elementsMatchOnlyWhenTheirClosingTagExists() {
Exact file bytes / download · SHA-256 17cc13dcc42d6995c390d954fe7b0fade055dee396a5d1d2ccfca43617a439ff.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class HtmlXPathMatcherTest {
private val sample = """
<root>
<item><name>One</name></item>
<item><name>Two</name></item>
<link href="/foo">Foo</link>
<link href="/bar">Bar</link>
<p class="warn">Watch out</p>
</root>
""".trimIndent()
@Test
fun extractsTextNodes() {
val names = HtmlXPathMatcher.match(sample, "//name/text()")
assertEquals(listOf("One", "Two"), names)
}
@Test
fun extractsAttributeValues() {
val hrefs = HtmlXPathMatcher.match(sample, "//link/@href")
assertEquals(listOf("/foo", "/bar"), hrefs)
}
@Test
fun honorsContainsClassPredicate() {
val matches = HtmlXPathMatcher.match(sample, "//p[contains(@class,'warn')]")
assertTrue(matches.any { it.contains("Watch out") })
}
@Test
fun elementsMatchOnlyWhenTheirClosingTagExists() {
val voidImages = "<img src=\"/a.jpg\"><p>x</p><img src=\"/b.jpg\">"
assertEquals(emptyList(), HtmlXPathMatcher.match(voidImages, "//img/@src"))
assertEquals(emptyList(), HtmlSelectorMatcher.match(voidImages, "img[src]"))
val closedImage = "$voidImages<img src=\"/c.jpg\">cap</img>"
assertEquals(listOf("/a.jpg"), HtmlXPathMatcher.match(closedImage, "//img/@src"))
assertEquals(listOf("<p>x</p><img src=\"/b.jpg\"><img src=\"/c.jpg\">cap"), HtmlSelectorMatcher.match(closedImage, "img[src]"))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptExtensionRuntimeServiceTest.kt
- Source · test / fixture · 149 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
22: class JavaScriptExtensionRuntimeServiceTest {
35: fun popularReturnsMappedListing() = runTest {
49: fun searchReturnsMappedListing() = runTest {
62: fun detailReturnsParsedMetadata() = runTest {
77: fun retriesOnceAfterTransientQuickJsStackFailure() = runTest {
86: object : JavaScriptEngine {
87: override fun evaluate(script: String, isCancelled: () -> Boolean): String = error("stack overflow")
88: override fun close() {
109: private class NoopHttpService : HttpService {
110: override suspend fun request(request: HttpRequest): HttpResponse =
115: private class SampleEngine : JavaScriptEngine {
116: override fun evaluate(script: String, isCancelled: () -> Boolean): String {
148: override fun close() = Unit
Exact file bytes / download · SHA-256 566b0131c9485058132fd3e4a8ead714d3353066841f65858ff8ae7c67412ddf.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
/**
* Wires a synthetic Yokan-style JS extension through the JS runtime service. Verifies
* popular / search / detail round-trip the JSON shapes the JS bridge expects.
*
* Tests that execute JavaScript itself live in desktopTest because QuickJS has no Android JVM
* native library. These tests keep the runtime-service mapping and retry coverage platform-neutral.
*/
class JavaScriptExtensionRuntimeServiceTest {
private val source = DbSource(
id = 42L,
name = "Sample JS",
baseUrl = "https://example.org",
lang = "en",
itemType = DbItemType.Manga,
sourceCodeLanguage = DbSourceCodeLanguage.JavaScript,
sourceCode = SampleExtensionSource,
supportLatest = true,
)
@Test
fun popularReturnsMappedListing() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source,
http = NoopHttpService(),
engineFactory = { _ -> SampleEngine() },
)
val listing = service.popular(1)
assertEquals(2, listing.items.size)
assertEquals("Title A", listing.items.first().title)
assertTrue(listing.hasNextPage)
service.dispose()
}
@Test
fun searchReturnsMappedListing() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source,
http = NoopHttpService(),
engineFactory = { _ -> SampleEngine() },
)
val listing = service.search("alpha", 1, emptyList())
assertEquals(1, listing.items.size)
assertEquals("Search Match", listing.items.first().title)
service.dispose()
}
@Test
fun detailReturnsParsedMetadata() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source,
http = NoopHttpService(),
engineFactory = { _ -> SampleEngine() },
)
val detail = service.detail("/manga/title-a")
assertEquals("Title A", detail.title)
assertEquals("Author A", detail.author)
assertEquals(listOf(TitleCredit("Actor A", "Voice actor", "Hero", "/portraits/a.jpg")), detail.cast)
assertEquals(1, detail.chapters.size)
service.dispose()
}
@Test
fun retriesOnceAfterTransientQuickJsStackFailure() = runTest {
var creations = 0
var failedEngineCloses = 0
val service = JavaScriptExtensionRuntimeService(
source = source,
http = NoopHttpService(),
engineFactory = {
creations += 1
if (creations == 1) {
object : JavaScriptEngine {
override fun evaluate(script: String, isCancelled: () -> Boolean): String = error("stack overflow")
override fun close() {
failedEngineCloses += 1
}
}
} else {
SampleEngine()
}
},
)
val listing = service.popular(1)
assertEquals("Title A", listing.items.first().title)
assertEquals(2, creations)
assertEquals(1, failedEngineCloses)
service.dispose()
}
}
private const val SampleExtensionSource: String = "// fixture (engine emulates extension methods)"
private class NoopHttpService : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse =
HttpResponse(statusCode = 200, body = "", headers = emptyMap())
}
/** Stand-in for QuickJS-backed evaluation used by mapping tests. */
private class SampleEngine : JavaScriptEngine {
override fun evaluate(script: String, isCancelled: () -> Boolean): String {
val expression = Regex("var __yokanValue = (extention\\.[^;]+);")
.find(script)
?.groupValues
?.get(1)
?: return ""
return when {
expression.startsWith("extention.getPopular") -> """
{
"list": [
{"name": "Title A", "imageUrl": "https://example.org/a.jpg", "link": "/manga/title-a"},
{"name": "Title B", "imageUrl": "https://example.org/b.jpg", "link": "/manga/title-b"}
],
"hasNextPage": true
}
""".trimIndent()
expression.startsWith("extention.search") -> """
{"list": [{"name": "Search Match", "link": "/manga/match"}], "hasNextPage": false}
""".trimIndent()
expression.startsWith("extention.getDetail") -> """
{
"name": "Title A", "author": "Author A", "artist": "Artist A",
"description": "Sample synopsis.", "genre": ["Action", "Adventure"],
"status": 0, "imageUrl": "https://example.org/a.jpg",
"cast": [{"name":"Actor A","role":"Voice actor","character":"Hero","image_url":"/portraits/a.jpg"}],
"chapters": [{"name": "Chapter 1", "url": "/manga/title-a/c1", "dateUpload": "1700000000000"}]
}
""".trimIndent()
else -> "null"
}
}
override fun close() = Unit
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptSourceNormalizationTest.kt
- Source · test / fixture · 68 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
6: class JavaScriptSourceNormalizationTest {
8: fun stringsCommentsAndRegularExpressionsKeepTheirContents() {
21: fun minifiedAwaitExpressionsBecomeSynchronous() {
27: fun multilineAwaitDoesNotIntroduceAutomaticSemicolonInsertion() {
35: fun templatesNormalizeExpressionsAndPreserveNestedLiteralText() {
42: fun regexAfterControlFlowAndDivisionAfterObjectsStayIntact() {
49: fun ordinaryIdentifiersAndCommentSeparatedModifiersWork() {
59: fun largePluginPreservesLiteralTextAcrossThousandsOfMethods() {
Exact file bytes / download · SHA-256 9a2d136f7b4907bcfd23b0ec47b0df5ea7bc617c49c729e1179f17644f8655b2.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
class JavaScriptSourceNormalizationTest {
@Test
fun stringsCommentsAndRegularExpressionsKeepTheirContents() {
val source = """
const title = 'Please await your turn';
const query = "async function(example)";
const matcher = /await\s+async function\(/g;
// async function(comment) and await value
/* await response */
const template = `await your turn: ${'$'}{'async function(x)'}`;
""".trimIndent()
assertEquals(source, synchronousJavaScriptSource(source))
}
@Test
fun minifiedAwaitExpressionsBecomeSynchronous() {
assertEquals("function f(){return (fetch('url'));}",
synchronousJavaScriptSource("async function f(){return await(fetch('url'));}").trim())
}
@Test
fun multilineAwaitDoesNotIntroduceAutomaticSemicolonInsertion() {
assertEquals("function f(){return fetch('url');}",
synchronousJavaScriptSource("async function f(){return await\nfetch('url');}"))
assertEquals("function f(){return fetch('url');}",
synchronousJavaScriptSource("async function f(){return await // completed value\nfetch('url');}"))
}
@Test
fun templatesNormalizeExpressionsAndPreserveNestedLiteralText() {
val source = """async function f(){return `await text: ${'$'}{await(fetch('await value'))} ${'$'}{`async function(x) ${'$'}{await(fetch('nested'))}`}`;}"""
assertEquals("""function f(){return `await text: ${'$'}{(fetch('await value'))} ${'$'}{`async function(x) ${'$'}{(fetch('nested'))}`}`;}""",
synchronousJavaScriptSource(source))
}
@Test
fun regexAfterControlFlowAndDivisionAfterObjectsStayIntact() {
val source = """if (ready) /await value/.test(text); const ratio = {n: 1} / 2; async function f(){return await(fetch('/await value/'));}"""
assertEquals("""if (ready) /await value/.test(text); const ratio = {n: 1} / 2; function f(){return (fetch('/await value/'));}""",
synchronousJavaScriptSource(source))
}
@Test
fun ordinaryIdentifiersAndCommentSeparatedModifiersWork() {
assertEquals("const x={await:1, await(){return 2;}}; x.await ();",
synchronousJavaScriptSource("const x={await:1, await(){return 2;}}; x.await ();"))
assertEquals("/* modifier */function f(){return /* result */fetch('url');}",
synchronousJavaScriptSource("async/* modifier */function f(){return await/* result */fetch('url');}"))
val identifiers = "const ${'$'}await = 1, await${'$'} = 2, ${'$'}async = 3;"
assertEquals(identifiers, synchronousJavaScriptSource(identifiers))
}
@Test
fun largePluginPreservesLiteralTextAcrossThousandsOfMethods() {
val source = buildString {
repeat(2_000) { append("async function f$it(){return await(fetch('await value $it'));}\n") }
}
val expected = buildString {
repeat(2_000) { append("function f$it(){return (fetch('await value $it'));}\n") }
}
assertEquals(expected, synchronousJavaScriptSource(source))
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/PageUrlFromJsonTest.kt
- Source · test / fixture · 18 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class PageUrlFromJsonTest {
9: fun prefersImageUrlOverAtHomeMetadataUrl() {
Exact file bytes / download · SHA-256 f7217919c7f51b94a921bf4bef0e35f949e4099ab04c58a86ec9e87e0f6c57a0.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
class PageUrlFromJsonTest {
@Test
fun prefersImageUrlOverAtHomeMetadataUrl() {
val page = pageUrlFromJson(
Json.parseToJsonElement(
"""{"url":"width=1200,height=1800,headers=...","imageUrl":"https://cdn.example/page.jpg"}""",
),
)
assertEquals("https://cdn.example/page.jpg", page?.url)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/SourceRelationsCodecTest.kt
- Source · test / fixture · 29 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
6: class SourceRelationsCodecTest {
Exact file bytes / download · SHA-256 ce1d9bd76fac516178e93abe0540686cbb7c4d6812c63fc17fb0ff8744b24dad.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlinx.serialization.json.Json
import kotlin.test.*
class SourceRelationsCodecTest {
@Test fun groupsKeepSourceOrderMergeLabelsDeduplicateAndValidateWebImages() {
val result = sourceRelationsFromJson(Json.parseToJsonElement("""[
{"name":"Sequel","animes":[{"title":"Next","url":"/next","thumbnail_url":"/next.jpg"},
{"title":"Duplicate","url":"/next"},{"title":"Invalid","url":"file:///private/title"}]},
{"name":"Adaptation","items":[{"name":"Manga","link":"/manga","imageUrl":"content://private/image"}]},
{"name":"Sequel","animes":[{"title":"Next again","url":"/next"},{"title":"Finale","url":"/finale"}]},
{"name":"Empty","animes":[]},{"name":"Malformed","animes":[null,{}, {"title":4,"url":"/bad"}]}
]"""), "https://source.example")
assertTrue(result.supported)
assertEquals(listOf("Sequel", "Adaptation"), result.groups.map { it.name })
assertEquals(listOf("Next", "Finale"), result.groups[0].items.map { it.title })
assertEquals("https://source.example/next.jpg", result.groups[0].items[0].thumbnailUrl)
assertNull(result.groups[1].items.single().thumbnailUrl)
}
@Test fun malformedRootAndOversizedResponsesFailInsteadOfPretendingThereAreNoRelations() {
assertFailsWith<IllegalStateException> { sourceRelationsFromJson(Json.parseToJsonElement("{}"), "https://source.example") }
assertFailsWith<IllegalArgumentException> { sourceRelationsFromJson(Json.parseToJsonElement(List(51) { "{}" }.joinToString(",", "[", "]")), "") }
val rows = List(1_001) { "{}" }.joinToString(",", "[", "]")
assertFailsWith<IllegalArgumentException> { sourceRelationsFromJson(Json.parseToJsonElement("""[{"name":"Too large","items":$rows}]"""), "") }
assertTrue(sourceRelationsFromJson(Json.parseToJsonElement("[]"), "").groups.isEmpty())
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/VideoFromJsonTest.kt
- Source · test / fixture · 36 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class VideoFromJsonTest {
11: fun spriteTrackListedAsSubtitleBecomesTheSeekPreviewTrack() {
25: fun explicitThumbnailTrackWinsAndOrdinaryVideosHaveNone() {
Exact file bytes / download · SHA-256 48829bdfba9d6dde4ba8e3129be62d830e53ab226148337144f68b4cb4c39035.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbVideoTrack
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class VideoFromJsonTest {
@Test
fun spriteTrackListedAsSubtitleBecomesTheSeekPreviewTrack() {
val video = videoFromJson(
Json.parseToJsonElement(
"""{"url":"https://cdn.example/a.m3u8","quality":"1080p","subtitles":[
{"file":"https://cdn.example/en.vtt","label":"English"},
{"file":"https://cdn.example/thumbs.vtt","label":"thumbnails"}]}""",
),
)
assertEquals(listOf(DbVideoTrack("https://cdn.example/en.vtt", "English")), video?.subtitles)
assertEquals("https://cdn.example/thumbs.vtt", video?.thumbnailTrack)
}
@Test
fun explicitThumbnailTrackWinsAndOrdinaryVideosHaveNone() {
val explicit = videoFromJson(
Json.parseToJsonElement("""{"url":"u","thumbnailTrack":"https://cdn.example/sprites.vtt","subtitles":[{"file":"s","label":"Sprites"}]}"""),
)
assertEquals("https://cdn.example/sprites.vtt", explicit?.thumbnailTrack)
assertEquals(emptyList(), explicit?.subtitles)
val plain = videoFromJson(Json.parseToJsonElement("""{"url":"u","subtitles":[{"file":"s","label":"Storyboard commentary"}]}"""))
assertNull(plain?.thumbnailTrack, "only whole-label matches are sprite tracks")
assertEquals(1, plain?.subtitles?.size)
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/lnreader/LnReaderExtensionRuntimeServiceTest.kt
- Source · test / fixture · 83 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
17: class LnReaderExtensionRuntimeServiceTest {
29: fun popularReturnsMappedItems() = runTest {
43: fun parseChapterReturnsString() = runTest {
55: private class FakeHttpService : HttpService {
56: override suspend fun request(request: HttpRequest): HttpResponse =
64: private class FakeEngine : JavaScriptEngine {
65: override fun evaluate(script: String, isCancelled: () -> Boolean): String {
82: override fun close() = Unit
Exact file bytes / download · SHA-256 b1603327c61bb64e010821603558d76f6de0fc8c6474a4048462a93270e15452.
Complete file
package eu.friedcutlet.yokan.services.extensions.lnreader
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptEngine
/** Smoke test that wires a fake JS engine and exercises the LNReader plugin bridge. */
class LnReaderExtensionRuntimeServiceTest {
private val source = DbSource(
id = 999L,
name = "Test LN",
baseUrl = "https://example.org",
lang = "en",
itemType = DbItemType.Novel,
sourceCodeLanguage = DbSourceCodeLanguage.LnReader,
sourceCode = "module.exports = { plugin: 'test' };",
)
@Test
fun popularReturnsMappedItems() = runTest {
val service = LnReaderExtensionRuntimeService(
source = source,
http = FakeHttpService(),
engineFactory = { _ -> FakeEngine() },
)
val listing = service.popular(1)
assertEquals(2, listing.items.size)
assertEquals("Test One", listing.items.first().title)
assertTrue(listing.hasNextPage)
service.dispose()
}
@Test
fun parseChapterReturnsString() = runTest {
val service = LnReaderExtensionRuntimeService(
source = source,
http = FakeHttpService(),
engineFactory = { _ -> FakeEngine() },
)
val text = service.htmlContent("Test One", "https://example.org/chapter/1")
assertEquals("Chapter body", text)
service.dispose()
}
}
private class FakeHttpService : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse =
HttpResponse(statusCode = 200, body = "{}", headers = emptyMap())
}
/**
* Records the last expression we were asked to evaluate and returns canned JSON for the LNReader
* bridge calls. Anything else is treated as the bootstrap/plugin source code and ignored.
*/
private class FakeEngine : JavaScriptEngine {
override fun evaluate(script: String, isCancelled: () -> Boolean): String {
return when {
script.startsWith("lnReaderResult(plugin.popularNovels(") -> """
[
{"name": "Test One", "url": "/novel/one", "cover": "https://example.org/one.jpg"},
{"name": "Test Two", "url": "/novel/two"}
]
""".trimIndent()
script.startsWith("lnReaderResult(plugin.searchNovels(") -> "[]"
script.startsWith("lnReaderResult(plugin.parseNovel(") -> """
{"name": "Test One", "summary": "Story", "author": "Anon", "chapters": []}
""".trimIndent()
script.startsWith("lnReaderResult(plugin.parseChapter(") -> "\"Chapter body\""
else -> "null"
}
}
override fun close() = Unit
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerManagerTest.kt
- Source · test / fixture · 374 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
24: class ExtensionServerManagerTest {
26: fun installsBundleAndPersistsDeviceLocalPaths() = runTest {
41: fun persistsLocalProxyOnlyAfterHealthCheckSucceeds() = runTest {
63: fun configurationRequiresResolvedBundlePaths() {
78: fun remoteProxyUsesExistingSettingWithoutLocalServerLifecycle() = runTest {
95: fun startsBundledRuntimeWithoutPersistedPaths() = runTest {
119: fun startsOnAllocatedFreePortAndPersistsProxy() = runTest {
151: fun everyLocalModeRequestsEphemeralPortAndPersistsAllocatedPort() = runTest {
190: fun keepsHealthyRunningServerInsteadOfReprobingPorts() = runTest {
222: fun rejectsInstallBeforeNetworkWhenPlatformRuntimeIsUnavailable() = runTest {
245: fun parsesConfiguredPortWithSafeFallback() {
252: fun loopbackProxyResolvesToOwnServerNeverTheSavedForeignPort() = runTest {
273: fun loopbackProxyFailsInsteadOfFallingBackWhenProfileCannotRunServer() = runTest {
284: fun browserKeepsUserLoopbackUrl() = runTest {
296: fun bridgePreferencesKeepLegacyNamesOnlyForDefault() {
302: private fun releaseHttp() = HttpService {
317: private class FakeAdapter(
327: override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? {
334: override suspend fun install(
348: override suspend fun detect(path: String) = InstalledExtensionServerBundle(
356: private class FakeServer : ExtensionServer {
363: override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus =
371: override suspend fun stop(): ExtensionServerStatus =
Exact file bytes / download · SHA-256 0535aa44dc14b5d66d6b936dcf2f58c4a15bc89a8415bce724c90d5189455493.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.ext.ExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServerConfig
import eu.friedcutlet.yokan.ext.ExtensionServerException
import eu.friedcutlet.yokan.ext.ExtensionServerPhase
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.ExtensionServerStatus
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.test.runTest
class ExtensionServerManagerTest {
@Test
fun installsBundleAndPersistsDeviceLocalPaths() = runTest {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
val adapter = FakeAdapter(requiresBundleDownload = true)
val service = DefaultExtensionServerRuntimeService(database, releaseHttp(), adapter)
val installed = service.installLatest()
assertEquals("1.2.3", installed.version)
assertEquals("/runtime/bin/java", database.settings().jrePath)
assertEquals("/runtime/MExtensionServer.jar", database.settings().extensionServerPath)
assertEquals(ExtensionServerInstallPhase.Installed, service.installation.value.phase)
assertEquals(100, service.installation.value.downloadedBytes)
}
@Test
fun persistsLocalProxyOnlyAfterHealthCheckSucceeds() = runTest {
val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
settings = seedDatabaseSnapshot().settings.copy(
jrePath = "/runtime/bin/java",
extensionServerPath = "/runtime/MExtensionServer.jar",
androidProxyServer = null,
),
),
)
val adapter = FakeAdapter(requiresBundleDownload = false)
val healthyHttp = HttpService { HttpResponse(200, "MExtensionServer Running") }
val service = DefaultExtensionServerRuntimeService(database, healthyHttp, adapter, findAvailablePort = { 43123 })
val status = service.start(43123)
assertEquals(ExtensionServerPhase.Running, status.phase)
assertEquals("http://127.0.0.1:43123", database.settings().androidProxyServer)
assertEquals("http://127.0.0.1:43123", adapter.server.status.value.baseUrl)
}
@Test
fun configurationRequiresResolvedBundlePaths() {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
val service = DefaultExtensionServerRuntimeService(database, releaseHttp(), FakeAdapter(requiresBundleDownload = true))
assertFalse(service.isConfigured())
database.updateSettings(
database.settings().copy(
jrePath = "/runtime/bin/java",
extensionServerPath = "/runtime/MExtensionServer.jar",
),
)
assertTrue(service.isConfigured())
}
@Test
fun remoteProxyUsesExistingSettingWithoutLocalServerLifecycle() = runTest {
val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
settings = seedDatabaseSnapshot().settings.copy(
androidProxyServer = "https://extensions.example",
),
),
)
val adapter = FakeAdapter(requiresBundleDownload = false, supportsRemoteBaseUrl = true)
val service = DefaultExtensionServerRuntimeService(database, releaseHttp(), adapter)
assertTrue(service.isConfigured())
assertEquals(null, service.startIfConfigured(8080))
assertEquals(0, adapter.server.startCalls)
}
@Test
fun startsBundledRuntimeWithoutPersistedPaths() = runTest {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
val bundledConfig = ExtensionServerConfig(
port = 8080,
jvmPath = "/app/java-21-openjdk",
serverJarPath = "/app/MExtensionServer.jar",
)
val adapter = FakeAdapter(
requiresBundleDownload = false,
bundledConfig = bundledConfig,
)
val healthyHttp = HttpService { HttpResponse(200, "MExtensionServer Running") }
val service = DefaultExtensionServerRuntimeService(database, healthyHttp, adapter, findAvailablePort = { 8080 })
val status = service.startIfConfigured(8080)
assertEquals(ExtensionServerPhase.Running, status?.phase)
assertEquals(bundledConfig, adapter.server.startedConfig)
assertEquals("http://127.0.0.1:8080", database.settings().androidProxyServer)
assertEquals("/app/java-21-openjdk", database.settings().jrePath)
assertEquals("/app/MExtensionServer.jar", database.settings().extensionServerPath)
}
@Test
fun startsOnAllocatedFreePortAndPersistsProxy() = runTest {
val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
settings = seedDatabaseSnapshot().settings.copy(
jrePath = "/runtime/bin/java",
extensionServerPath = "/runtime/MExtensionServer.jar",
androidProxyServer = "http://127.0.0.1:8080",
),
),
)
val adapter = FakeAdapter(requiresBundleDownload = false)
val healthyHttp = HttpService { HttpResponse(200, "MExtensionServer Running") }
var requestedPort: Int? = null
val service = DefaultExtensionServerRuntimeService(
database,
healthyHttp,
adapter,
findAvailablePort = { preferred ->
requestedPort = preferred
45871
},
)
val status = service.start(8080)
assertEquals(0, requestedPort)
assertEquals(45871, status.port)
assertEquals(45871, adapter.server.startedConfig?.port)
assertEquals("http://127.0.0.1:45871", database.settings().androidProxyServer)
}
@Test
fun everyLocalModeRequestsEphemeralPortAndPersistsAllocatedPort() = runTest {
val healthyHttp = HttpService { HttpResponse(200, "MExtensionServer Running") }
listOf(
ExtensionServerRuntimeMode.AndroidApkBridge,
ExtensionServerRuntimeMode.DesktopDownloadedJvm,
ExtensionServerRuntimeMode.IosSideloadedJvm,
).forEach { mode ->
val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
settings = seedDatabaseSnapshot().settings.copy(
jrePath = "/runtime/bin/java",
extensionServerPath = "/runtime/MExtensionServer.jar",
androidProxyServer = null,
),
),
)
val adapter = FakeAdapter(requiresBundleDownload = false, mode = mode)
var requestedPort: Int? = null
val service = DefaultExtensionServerRuntimeService(
database,
healthyHttp,
adapter,
findAvailablePort = { preferred ->
requestedPort = preferred
45872
},
)
val status = service.start(8080)
assertEquals(0, requestedPort, mode.toString())
assertEquals(45872, status.port, mode.toString())
assertEquals(45872, adapter.server.startedConfig?.port, mode.toString())
assertEquals("http://127.0.0.1:45872", database.settings().androidProxyServer, mode.toString())
}
}
@Test
fun keepsHealthyRunningServerInsteadOfReprobingPorts() = runTest {
val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
settings = seedDatabaseSnapshot().settings.copy(
jrePath = "/runtime/bin/java",
extensionServerPath = "/runtime/MExtensionServer.jar",
androidProxyServer = null,
),
),
)
val adapter = FakeAdapter(requiresBundleDownload = false)
val healthyHttp = HttpService { HttpResponse(200, "MExtensionServer Running") }
val requestedPorts = mutableListOf<Int>()
val service = DefaultExtensionServerRuntimeService(
database,
healthyHttp,
adapter,
findAvailablePort = { preferred ->
requestedPorts += preferred
43123
},
)
service.start(43123)
val second = service.start(8080)
assertEquals(listOf(0), requestedPorts)
assertEquals(43123, second.port)
assertEquals("http://127.0.0.1:43123", database.settings().androidProxyServer)
}
@Test
fun rejectsInstallBeforeNetworkWhenPlatformRuntimeIsUnavailable() = runTest {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
var requests = 0
val http = HttpService {
requests += 1
HttpResponse(500, "")
}
val service = DefaultExtensionServerRuntimeService(
database,
http,
FakeAdapter(
requiresBundleDownload = true,
installationAvailable = false,
),
)
val error = assertFailsWith<ExtensionServerException> { service.installLatest() }
assertEquals("MISSING_JAVA", error.code)
assertEquals(0, requests)
}
@Test
fun parsesConfiguredPortWithSafeFallback() {
assertEquals(43123, extensionServerPortFromUrl("http://127.0.0.1:43123"))
assertEquals(8080, extensionServerPortFromUrl("https://example.test"))
assertEquals(8080, extensionServerPortFromUrl("http://localhost:99999"))
}
@Test
fun loopbackProxyResolvesToOwnServerNeverTheSavedForeignPort() = runTest {
// The saved port may now belong to another profile's live server.
val foreign = "http://127.0.0.1:45000"
val database = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
settings = seedDatabaseSnapshot().settings.copy(androidProxyServer = foreign),
),
)
val healthyHttp = HttpService { HttpResponse(200, "MExtensionServer Running") }
val adapter = FakeAdapter(requiresBundleDownload = false, bundledConfig = ExtensionServerConfig(1))
val service = DefaultExtensionServerRuntimeService(database, healthyHttp, adapter, findAvailablePort = { 51000 })
assertEquals("http://127.0.0.1:51000", service.resolveMihonProxy(foreign))
assertEquals(51000, adapter.server.startedConfig?.port)
// Once running, the session's own server answers without another start.
assertEquals("http://127.0.0.1:51000", service.resolveMihonProxy(foreign))
assertEquals(1, adapter.server.startCalls)
assertEquals("https://remote.example", service.resolveMihonProxy("https://remote.example"))
}
@Test
fun loopbackProxyFailsInsteadOfFallingBackWhenProfileCannotRunServer() = runTest {
val database = InMemoryYokanDatabase(seedDatabaseSnapshot())
val adapter = FakeAdapter(requiresBundleDownload = false, unavailableReason = "default profile only")
val service = DefaultExtensionServerRuntimeService(database, releaseHttp(), adapter)
val error = assertFailsWith<ExtensionServerException> { service.resolveMihonProxy("http://127.0.0.1:8080") }
assertEquals("PROFILE_UNSUPPORTED", error.code)
assertEquals(0, adapter.server.startCalls)
}
@Test
fun browserKeepsUserLoopbackUrl() = runTest {
val adapter = FakeAdapter(
requiresBundleDownload = false,
supportsRemoteBaseUrl = true,
mode = ExtensionServerRuntimeMode.Unsupported,
)
val service = DefaultExtensionServerRuntimeService(InMemoryYokanDatabase(seedDatabaseSnapshot()), releaseHttp(), adapter)
assertEquals("http://127.0.0.1:9000", service.resolveMihonProxy("http://127.0.0.1:9000"))
}
@Test
fun bridgePreferencesKeepLegacyNamesOnlyForDefault() {
val extra = ProfileId("p_" + "a".repeat(32))
assertEquals("", mihonBridgePreferencesPrefix(ProfileId.Default))
assertEquals("p_${"a".repeat(32)}__", mihonBridgePreferencesPrefix(extra))
}
private fun releaseHttp() = HttpService {
HttpResponse(
200,
"""{
"tag_name":"v1.2.3",
"assets":[{
"name":"macOS-arm64-bundle.zip",
"browser_download_url":"https://example.test/bundle.zip",
"size":100,
"digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}]
}""",
)
}
private class FakeAdapter(
override val requiresBundleDownload: Boolean,
override val installationAvailable: Boolean = true,
override val supportsRemoteBaseUrl: Boolean = false,
override val mode: ExtensionServerRuntimeMode = ExtensionServerRuntimeMode.DesktopDownloadedJvm,
private val bundledConfig: ExtensionServerConfig? = null,
override val unavailableReason: String? = null,
) : PlatformExtensionServerAdapter {
override val server = FakeServer()
override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? {
if (jvmPath.isBlank() || serverJarPath.isBlank()) {
return bundledConfig?.copy(port = port)
}
return ExtensionServerConfig(port, jvmPath, serverJarPath)
}
override suspend fun install(
release: ExtensionServerRelease,
onProgress: (Long, Long) -> Unit,
): InstalledExtensionServerBundle {
onProgress(50, 100)
onProgress(100, 100)
return InstalledExtensionServerBundle(
release.version,
"/runtime",
"/runtime/bin/java",
"/runtime/MExtensionServer.jar",
)
}
override suspend fun detect(path: String) = InstalledExtensionServerBundle(
"manual",
path,
"$path/bin/java",
"$path/MExtensionServer.jar",
)
}
private class FakeServer : ExtensionServer {
private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
var startCalls = 0
var startedConfig: ExtensionServerConfig? = null
private set
override val status: StateFlow<ExtensionServerStatus> = mutableStatus
override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus =
ExtensionServerStatus(ExtensionServerPhase.Running, config.port, "Running")
.also {
startCalls++
startedConfig = config
mutableStatus.value = it
}
override suspend fun stop(): ExtensionServerStatus =
ExtensionServerStatus.Stopped.also { mutableStatus.value = it }
}
}
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/MihonExtensionRuntimeServiceTest.kt
- Source · test / fixture · 481 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
28: class MihonExtensionRuntimeServiceTest {
41: fun popularRoundTripsThroughDalvik() = runTest {
68: fun preparesLocalServerBeforeFirstDalvikRequest() = runTest {
85: fun searchSendsFilterListAndMapsResults() = runTest {
105: fun detailParsesMetadataAndChapters() = runTest {
137: fun cloudflareResponseSurfacesUsefulError() = runTest {
146: fun missingDalvikEndpointSurfacesActionableError() = runTest {
155: fun bridgeJsonErrorIsUnwrapped() = runTest {
169: fun browserFetchFailureSurfacesCorsHint() = runTest {
178: fun multiSourceContextRidesInPreferences() = runTest {
194: fun sourcesWithoutUpstreamIdSendNoBridgeContext() = runTest {
205: fun extensionHandleReplacesApkPayloadOnSubsequentCalls() = runTest {
226: fun staleHandleRetriesWithApkAfterConflict() = runTest {
254: fun updatedApkPayloadInvalidatesCachedHandle() = runTest {
275: fun fetchMetadataRetrievesAllMetadataForManga() = runTest {
319: fun fetchMetadataRetrievesAnimeMethodsForAnimeSource() = runTest {
353: fun fetchMetadataToleratesServerFailureGracefully() = runTest {
368: fun sourcePreferencesFetchesFromDalvikWhenEmptyAndSavesToDb() = runTest {
419: fun sourcePreferencesUsesExistingListWithoutNetworkRequest() = runTest {
439: fun userPreferenceOverridesAppliedInDalvikRequests() = runTest {
479: private class MihonFakeHttpService(private val handler: (HttpRequest) -> HttpResponse) : HttpService {
480: override suspend fun request(request: HttpRequest): HttpResponse = handler(request)
Exact file bytes / download · SHA-256 f1ee6f8d982526574c251aacb63a253175c5fce41a87027a14f4049dba79d390.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.DbSourcePreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory
/**
* Integration-style test: drives `MihonExtensionRuntimeService` against a fake `HttpService` that
* replays canned ApkBridge `/dalvik` responses, covering the popular/search/detail round trips,
* Cloudflare HTTP 503, ApkBridge HTTP 404, and bridge-level error JSON.
*/
class MihonExtensionRuntimeServiceTest {
private val source = DbSource(
id = 555L,
name = "Mihon Sample",
baseUrl = "https://example.org",
lang = "en",
itemType = DbItemType.Manga,
sourceCodeLanguage = DbSourceCodeLanguage.Mihon,
sourceCode = "BASE64_BUNDLE",
supportLatest = true,
)
@Test
fun popularRoundTripsThroughDalvik() = runTest {
val http = MihonFakeHttpService { request ->
assertEquals("$PROXY/dalvik", request.url)
assertEquals("POST", request.method)
assertTrue(request.body!!.contains("\"method\":\"getPopularManga\""))
HttpResponse(
statusCode = 200,
body = """
{
"list": [
{"name": "Apex", "link": "/manga/apex", "imageUrl": "https://example.org/apex.jpg"},
{"name": "Bravo", "link": "/manga/bravo"}
],
"hasNextPage": true
}
""".trimIndent(),
)
}
val service = MihonExtensionRuntimeService(source, http, PROXY)
val listing = service.popular(0)
assertEquals(2, listing.items.size)
assertEquals("Apex", listing.items.first().title)
assertTrue(listing.hasNextPage)
service.dispose()
}
@Test
fun preparesLocalServerBeforeFirstDalvikRequest() = runTest {
var preparations = 0
val http = MihonFakeHttpService { request ->
assertEquals("http://localhost:7788/dalvik", request.url)
HttpResponse(200, """{"list": [], "hasNextPage": false}""")
}
val service = MihonExtensionRuntimeService(source, http, PROXY) {
preparations += 1
"http://localhost:7788"
}
service.popular(0)
assertEquals(1, preparations)
}
@Test
fun searchSendsFilterListAndMapsResults() = runTest {
val http = MihonFakeHttpService { request ->
assertTrue(request.body!!.contains("\"method\":\"getSearchManga\""))
assertTrue(request.body.contains("\"search\":\"hero\""))
assertTrue(request.body.contains("\"filterList\""))
HttpResponse(
statusCode = 200,
body = """
{"list": [{"name": "Hero Match", "link": "/manga/hero-match"}], "hasNextPage": false}
""".trimIndent(),
)
}
val service = MihonExtensionRuntimeService(source, http, PROXY)
val listing = service.search("hero", 1, emptyList())
assertEquals(1, listing.items.size)
assertEquals("Hero Match", listing.items.first().title)
service.dispose()
}
@Test
fun detailParsesMetadataAndChapters() = runTest {
val responses = ArrayDeque(
listOf(
"""
{
"name": "Apex",
"url": "/manga/apex",
"description": "Synopsis here.",
"author": "Anon",
"artist": "Anon",
"cast": [{"name":"Actor A","character":"Hero","image_url":"https://cdn.example/a.jpg"}]
}
""".trimIndent(),
"""
[
{"name": "Chapter 1", "url": "/manga/apex/c1", "dateUpload": "1700000000"},
{"name": "Chapter 2", "url": "/manga/apex/c2", "dateUpload": "1700100000", "scanlator": "Scans"}
]
""".trimIndent(),
),
)
val http = MihonFakeHttpService { _ -> HttpResponse(statusCode = 200, body = responses.removeFirst()) }
val service = MihonExtensionRuntimeService(source, http, PROXY)
val detail = service.detail("/manga/apex")
assertEquals("Apex", detail.title)
assertEquals(listOf(TitleCredit("Actor A", character = "Hero", imageUrl = "https://cdn.example/a.jpg")), detail.cast)
assertEquals(2, detail.chapters.size)
assertEquals("Scans", detail.chapters[1].scanlator)
service.dispose()
}
@Test
fun cloudflareResponseSurfacesUsefulError() = runTest {
val http = MihonFakeHttpService { _ -> HttpResponse(statusCode = 503, body = "challenge page") }
val service = MihonExtensionRuntimeService(source, http, PROXY)
val exception = assertFailsWith<IllegalStateException> { service.popular(0) }
assertTrue("Cloudflare" in exception.message.orEmpty())
service.dispose()
}
@Test
fun missingDalvikEndpointSurfacesActionableError() = runTest {
val http = MihonFakeHttpService { _ -> HttpResponse(statusCode = 404, body = "Not Found") }
val service = MihonExtensionRuntimeService(source, http, PROXY)
val exception = assertFailsWith<IllegalStateException> { service.popular(0) }
assertTrue("404" in exception.message.orEmpty())
service.dispose()
}
@Test
fun bridgeJsonErrorIsUnwrapped() = runTest {
val http = MihonFakeHttpService { _ ->
HttpResponse(
statusCode = 200,
body = """{"error": "APK payload invalid", "code": "MIHON_APK_INVALID"}""",
)
}
val service = MihonExtensionRuntimeService(source, http, PROXY)
val exception = assertFailsWith<IllegalStateException> { service.popular(0) }
assertTrue("APK" in exception.message.orEmpty() || "Re-install" in exception.message.orEmpty())
service.dispose()
}
@Test
fun browserFetchFailureSurfacesCorsHint() = runTest {
val http = MihonFakeHttpService { _ -> throw IllegalStateException("TypeError: Failed to fetch") }
val service = MihonExtensionRuntimeService(source, http, "https://extensions.example")
val exception = assertFailsWith<IllegalStateException> { service.popular(0) }
assertTrue("CORS" in exception.message.orEmpty())
service.dispose()
}
@Test
fun multiSourceContextRidesInPreferences() = runTest {
val factorySource = source.copy(
id = 601L,
additionalParams = """{"sourceId":"8842237058298566885"}""",
)
val http = MihonFakeHttpService { request ->
assertTrue(request.body!!.contains("\"__mangayomi_bridge_context__\""))
assertTrue(request.body.contains("\"sourceId\":\"8842237058298566885\""))
HttpResponse(statusCode = 200, body = """{"list": [], "hasNextPage": false}""")
}
val service = MihonExtensionRuntimeService(factorySource, http, PROXY)
service.popular(0)
service.dispose()
}
@Test
fun sourcesWithoutUpstreamIdSendNoBridgeContext() = runTest {
val http = MihonFakeHttpService { request ->
assertTrue("__mangayomi_bridge_context__" !in request.body!!)
HttpResponse(statusCode = 200, body = """{"list": [], "hasNextPage": false}""")
}
val service = MihonExtensionRuntimeService(source.copy(id = 602L), http, PROXY)
service.popular(0)
service.dispose()
}
@Test
fun extensionHandleReplacesApkPayloadOnSubsequentCalls() = runTest {
val handleSource = source.copy(id = 603L)
val bodies = mutableListOf<String>()
val http = MihonFakeHttpService { request ->
bodies += request.body!!
HttpResponse(
statusCode = 200,
body = """{"list": [], "hasNextPage": false}""",
headers = mapOf("X-Mangayomi-Extension-Id" to "handle-603"),
)
}
val service = MihonExtensionRuntimeService(handleSource, http, PROXY)
service.popular(0)
service.popular(0)
assertTrue("\"data\":\"BASE64_BUNDLE\"" in bodies[0])
assertTrue("extensionId" !in bodies[0])
assertTrue("\"extensionId\":\"handle-603\"" in bodies[1])
assertTrue("BASE64_BUNDLE" !in bodies[1])
}
@Test
fun staleHandleRetriesWithApkAfterConflict() = runTest {
val handleSource = source.copy(id = 604L)
val bodies = mutableListOf<String>()
var conflictSent = false
val http = MihonFakeHttpService { request ->
bodies += request.body!!
when {
"extensionId" in request.body && !conflictSent -> {
conflictSent = true
HttpResponse(statusCode = 409, body = """{"error":"Extension not loaded","code":409}""")
}
else -> HttpResponse(
statusCode = 200,
body = """{"list": [], "hasNextPage": false}""",
headers = mapOf("X-Mangayomi-Extension-Id" to "handle-604"),
)
}
}
val service = MihonExtensionRuntimeService(handleSource, http, PROXY)
service.popular(0)
val listing = service.popular(0)
assertEquals(0, listing.items.size)
assertEquals(3, bodies.size)
assertTrue("\"extensionId\":\"handle-604\"" in bodies[1])
assertTrue("\"data\":\"BASE64_BUNDLE\"" in bodies[2])
}
@Test
fun updatedApkPayloadInvalidatesCachedHandle() = runTest {
val handleSource = source.copy(id = 605L)
val bodies = mutableListOf<String>()
val http = MihonFakeHttpService { request ->
bodies += request.body!!
HttpResponse(
statusCode = 200,
body = """{"list": [], "hasNextPage": false}""",
headers = mapOf("X-Mangayomi-Extension-Id" to "handle-605"),
)
}
val factory = DynamicExtensionRuntimeFactory(InMemoryYokanDatabase(), http)
factory.withRuntime(handleSource) { it.popular(0) }
factory.withRuntime(handleSource) { it.popular(0) }
factory.withRuntime(handleSource.copy(sourceCode = "UPDATED_BUNDLE")) { it.popular(0) }
assertTrue("\"extensionId\":\"handle-605\"" in bodies[1])
assertTrue("\"data\":\"UPDATED_BUNDLE\"" in bodies[2])
assertTrue("extensionId" !in bodies[2])
}
@Test
fun fetchMetadataRetrievesAllMetadataForManga() = runTest {
val requests = mutableListOf<HttpRequest>()
val http = MihonFakeHttpService { request ->
requests += request
val body = request.body.orEmpty()
when {
"\"method\":\"headersManga\"" in body -> HttpResponse(
statusCode = 200,
body = """["User-Agent", "Test-Agent/1.0", "Referer", "https://example.org/"]""",
)
"\"method\":\"supportLatestManga\"" in body -> HttpResponse(
statusCode = 200,
body = "true",
)
"\"method\":\"filtersManga\"" in body -> HttpResponse(
statusCode = 200,
body = """[{"name":"Sort","type_name":"SortFilter","state":{"index":0,"ascending":true},"values":["A","B"]}]""",
)
"\"method\":\"preferencesManga\"" in body -> HttpResponse(
statusCode = 200,
body = """[{"key":"pref1","switchPreferenceCompat":{"title":"Pref 1","value":true}}]""",
)
else -> HttpResponse(statusCode = 404, body = "Not Found")
}
}
val service = MihonExtensionRuntimeService(source, http, PROXY)
val metadata = service.fetchMetadata()
assertEquals(4, requests.size)
// Verify sourceId and lang are sent
assertTrue(requests.all { it.body!!.contains("\"sourceId\":\"555\"") })
assertTrue(requests.all { it.body!!.contains("\"lang\":\"en\"") })
assertNotNull(metadata.headers)
assertTrue(metadata.headers.contains("\"User-Agent\":\"Test-Agent/1.0\""))
assertEquals(true, metadata.supportLatest)
assertNotNull(metadata.filterList)
assertTrue(metadata.filterList.contains("SortFilter"))
assertNotNull(metadata.preferenceList)
assertTrue(metadata.preferenceList.contains("switchPreferenceCompat"))
service.dispose()
}
@Test
fun fetchMetadataRetrievesAnimeMethodsForAnimeSource() = runTest {
val animeSource = source.copy(itemType = DbItemType.Anime)
val calledMethods = mutableListOf<String>()
val http = MihonFakeHttpService { request ->
val body = request.body.orEmpty()
when {
"headersAnime" in body -> {
calledMethods += "headersAnime"
HttpResponse(200, """["User-Agent", "AnimeUA"]""")
}
"supportLatestAnime" in body -> {
calledMethods += "supportLatestAnime"
HttpResponse(200, "false")
}
"filtersAnime" in body -> {
calledMethods += "filtersAnime"
HttpResponse(200, "[]")
}
"preferencesAnime" in body -> {
calledMethods += "preferencesAnime"
HttpResponse(200, "[]")
}
else -> HttpResponse(404, "Not Found")
}
}
val service = MihonExtensionRuntimeService(animeSource, http, PROXY)
val metadata = service.fetchMetadata()
assertEquals(listOf("headersAnime", "supportLatestAnime", "filtersAnime", "preferencesAnime"), calledMethods)
assertEquals(false, metadata.supportLatest)
service.dispose()
}
@Test
fun fetchMetadataToleratesServerFailureGracefully() = runTest {
val http = MihonFakeHttpService { _ ->
throw IllegalStateException("Connection refused")
}
val service = MihonExtensionRuntimeService(source, http, PROXY)
val metadata = service.fetchMetadata()
assertNull(metadata.headers)
assertNull(metadata.supportLatest)
assertNull(metadata.filterList)
assertNull(metadata.preferenceList)
service.dispose()
}
@Test
fun sourcePreferencesFetchesFromDalvikWhenEmptyAndSavesToDb() = runTest {
val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(sources = listOf(source)))
val http = MihonFakeHttpService { request ->
assertTrue(request.body!!.contains("\"method\":\"preferencesManga\""))
HttpResponse(
statusCode = 200,
body = """
[
{
"key": "pref_theme",
"listPreference": {
"title": "Theme",
"summary": "Choose theme",
"valueIndex": 1,
"entries": ["Light", "Dark"],
"entryValues": ["light", "dark"]
}
},
{
"key": "pref_auto_download",
"switchPreferenceCompat": {
"title": "Auto Download",
"summary": "Download new chapters",
"value": true
}
}
]
""".trimIndent(),
)
}
val service = MihonExtensionRuntimeService(source, http, PROXY, database = db)
val prefs = service.sourcePreferences()
assertEquals(2, prefs.size)
assertEquals("pref_theme", prefs[0].key)
assertEquals("Theme", prefs[0].title)
assertEquals("dark", prefs[0].value)
assertEquals("listPreference", prefs[0].type)
assertEquals(listOf("light", "dark"), prefs[0].values)
assertEquals("pref_auto_download", prefs[1].key)
assertEquals("true", prefs[1].value)
// Verify the raw JSON array was persisted in the database for the source
val updatedSource = db.source(source.id)
assertNotNull(updatedSource?.preferenceList)
assertTrue(updatedSource.preferenceList.contains("pref_theme"))
service.dispose()
}
@Test
fun sourcePreferencesUsesExistingListWithoutNetworkRequest() = runTest {
var networkCalls = 0
val sourceWithPrefs = source.copy(
preferenceList = """[{"key":"cached_pref","switchPreferenceCompat":{"title":"Cached","value":true}}]""",
)
val http = MihonFakeHttpService { _ ->
networkCalls += 1
HttpResponse(200, "[]")
}
val service = MihonExtensionRuntimeService(sourceWithPrefs, http, PROXY)
val prefs = service.sourcePreferences()
assertEquals(0, networkCalls)
assertEquals(1, prefs.size)
assertEquals("cached_pref", prefs.first().key)
assertEquals("true", prefs.first().value)
service.dispose()
}
@Test
fun userPreferenceOverridesAppliedInDalvikRequests() = runTest {
val sourceWithPrefs = source.copy(
preferenceList = """
[
{"key":"pref_dark","switchPreferenceCompat":{"title":"Dark Mode","value":false}},
{"key":"pref_quality","listPreference":{"title":"Quality","valueIndex":0,"entries":["Low","High"],"entryValues":["low","high"]}}
]
""".trimIndent(),
)
val db = InMemoryYokanDatabase(
seedDatabaseSnapshot().copy(
sources = listOf(sourceWithPrefs),
settings = seedDatabaseSnapshot().settings.copy(
sourcePreferences = listOf(
DbSourcePreference(sourceId = sourceWithPrefs.id, key = "pref_dark", value = "true"),
DbSourcePreference(sourceId = sourceWithPrefs.id, key = "pref_quality", value = "high"),
),
),
),
)
var capturedBody = ""
val http = MihonFakeHttpService { request ->
capturedBody = request.body.orEmpty()
HttpResponse(200, """{"list":[],"hasNextPage":false}""")
}
val service = MihonExtensionRuntimeService(sourceWithPrefs, http, PROXY, database = db)
service.popular(0)
assertTrue(capturedBody.contains("\"pref_dark\""))
assertTrue(capturedBody.contains("\"value\":true"))
assertTrue(capturedBody.contains("\"pref_quality\""))
assertTrue(capturedBody.contains("\"valueIndex\":1"))
service.dispose()
}
companion object {
private const val PROXY = "https://extensions.example"
}
}
private class MihonFakeHttpService(private val handler: (HttpRequest) -> HttpResponse) : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse = handler(request)
}
composeApp/src/desktopMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerAdapter.desktop.kt
- Source · implementation · 50 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
17: internal actual fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter =
23: internal fun extensionServerDataDir(dataRoot: File, profileId: ProfileId): File? =
27: private class DesktopExtensionServerAdapter(dataDir: File?) : PlatformExtensionServerAdapter {
34: override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? {
39: override suspend fun install(
48: override suspend fun detect(path: String): InstalledExtensionServerBundle =
Exact file bytes / download · SHA-256 2aa818b628dff30aa9648f2aef079cd1c23e38fe5cd0c7f186780a0b159783bd.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.domain.ProfileStorageNamespace
import eu.friedcutlet.yokan.ext.DesktopExtensionServer
import eu.friedcutlet.yokan.ext.DesktopExtensionServerInstaller
import eu.friedcutlet.yokan.ext.ExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServerConfig
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
import eu.friedcutlet.yokan.ext.currentDesktopHost
import eu.friedcutlet.yokan.ext.selectBundle
import eu.friedcutlet.yokan.services.files.desktopDataRoot
import java.io.File
import java.nio.file.Path
internal actual fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter =
DesktopExtensionServerAdapter(extensionServerDataDir(desktopDataRoot, profileId))
internal actual val defaultMihonProxyUrl: String = "http://127.0.0.1:8080"
/** Extra profiles confine the server JVM under their owned root; Default keeps legacy locations. */
internal fun extensionServerDataDir(dataRoot: File, profileId: ProfileId): File? =
ProfileStorageNamespace(profileId).relativeRoot?.let { File(dataRoot, "$it/extension-server-data") }
// The downloaded server bundle stays shared; only runtime state is per profile.
private class DesktopExtensionServerAdapter(dataDir: File?) : PlatformExtensionServerAdapter {
override val mode = ExtensionServerRuntimeMode.DesktopDownloadedJvm
override val requiresBundleDownload = true
override val installationAvailable = true
override val server: ExtensionServer = DesktopExtensionServer(dataDir)
private val installer = DesktopExtensionServerInstaller(desktopDataRoot.toPath().resolve("extension-server"))
override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? {
if (jvmPath.isBlank() || serverJarPath.isBlank()) return null
return ExtensionServerConfig(port, jvmPath, serverJarPath)
}
override suspend fun install(
release: ExtensionServerRelease,
onProgress: (Long, Long) -> Unit,
): InstalledExtensionServerBundle = installer.install(
release = release,
asset = release.selectBundle(currentDesktopHost()),
onProgress = onProgress,
)
override suspend fun detect(path: String): InstalledExtensionServerBundle =
installer.detectBundle(Path.of(path.removePrefix("file://")))
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionHostContractTest.kt
- Source · test / fixture · 112 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
26: class ExtensionHostContractTest {
28: fun everySourceExercisesHostContractWithoutDefects() = runTest {
69: private suspend fun exercise(name: String, step: String, block: suspend () -> Any?): String? {
80: fun isHostDefect(message: String): Boolean {
90: private object FixtureHttpService : HttpService {
110: override suspend fun request(request: HttpRequest): HttpResponse =
Exact file bytes / download · SHA-256 bf5f14d668f033354febb25131c014432a3f4cd8765de4024f704f080a7afe99.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import java.nio.file.Path
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService
/**
* Drives every generated source's popular / search / detail / video-or-page
* paths through the real QuickJS runtime using canned HTML (no network), to
* prove the host contract is complete — no missing globals, JS builtins,
* `SharedPreferences` accessors, `Crypto` helpers, or DOM methods. Errors are
* classified: host/runtime defects fail the test; domain errors (a source
* throwing because the fixture doesn't match its site, or JSON.parse on HTML)
* are expected and ignored.
*
* Deterministic and offline, so it runs in the default suite whenever
* `-Dyokan.generated.repository` points at a built anime index.
*/
class ExtensionHostContractTest {
@Test
fun everySourceExercisesHostContractWithoutDefects() = runTest {
val repoProperty = System.getProperty("yokan.generated.repository") ?: return@runTest
val repositoryPath = Path.of(repoProperty).toAbsolutePath().normalize()
val repositoryUrl = repositoryPath.toUri().toString()
val files = JvmLocalFileService(
downloadRoot = repositoryPath.parent.toString(),
backupRoot = repositoryPath.parent.toString(),
cacheRoot = repositoryPath.parent.toString(),
)
val catalog = HttpSourceCatalogService(FixtureHttpService, files)
val sources = catalog.fetchSources(repositoryUrl, DbItemType.Anime)
assertTrue(sources.isNotEmpty(), "no anime sources found")
val defects = mutableListOf<String>()
for (source in sources) {
val payload = catalog.fetchSourcePayload(source)?.decodeToString() ?: continue
val runtime = JavaScriptExtensionRuntimeService(source = source.copy(sourceCode = payload), http = FixtureHttpService)
try {
exercise(source.name, "popular") { runtime.popular(1) }?.let { defects += it }
exercise(source.name, "search") { runtime.search("a", 1, emptyList()) }?.let { defects += it }
val listing = runCatching { runtime.popular(1) }.getOrNull()
val entry = listing?.items?.firstOrNull()
if (entry != null) {
val detail = runCatching { runtime.detail(entry.url) }.getOrNull()
exercise(source.name, "detail") { runtime.detail(entry.url) }?.let { defects += it }
val chapter = detail?.chapters?.firstOrNull()
if (chapter != null) {
exercise(source.name, "videoList") { runtime.videoList(chapter.url) }?.let { defects += it }
}
}
} finally {
runtime.dispose()
}
}
assertTrue(
defects.isEmpty(),
"Host-contract defects in ${defects.size} path(s):\n${defects.joinToString("\n")}",
)
}
/** Returns a defect description if the step hit a host/runtime gap, else null. */
private suspend fun exercise(name: String, step: String, block: suspend () -> Any?): String? {
return try {
block()
null
} catch (error: Throwable) {
val message = (generateSequence(error) { it.cause }.lastOrNull()?.message ?: error.message).orEmpty()
if (isHostDefect(message)) "$name.$step: ${message.take(160)}" else null
}
}
private companion object {
fun isHostDefect(message: String): Boolean {
val lower = message.lowercase()
return "is not a function" in lower || "is not defined" in lower || "no setter" in lower ||
"not a constructor" in lower || "bridge channel" in lower ||
"is not an object" in lower
}
}
}
/** Serves a rich generic anime/listing HTML for any URL so parsing code paths execute. */
private object FixtureHttpService : HttpService {
private val html = """
<!doctype html><html><head><title>Fixture</title>
<meta property="og:image" content="/img/cover.jpg">
<meta itemprop="embedUrl" content="https://player.test/embed/1"></head><body>
<div class="listupd"><article class="bs"><a class="tip" href="/anime/one"><div class="tt">One</div>
<h2>One</h2><img class="ts-post-image" src="/i/1.jpg" data-src="/i/1.jpg" data-original="/i/1.jpg"></a></article></div>
<div class="result"><div class="item"><a href="/anime/one"><div class="title">One</div><img src="/i/1.jpg"></a></div></div>
<ul class="episodios"><li><div class="episodiotitle"><a href="/ep/1">Ep 1</a></div></li></ul>
<ul class="eplister"><li><a href="/ep/1"><div class="epl-num">1</div><div class="epl-title">E1</div></a></li></ul>
<div class="pagination"><a class="next page-numbers" href="/page/2">Next</a></div>
<div class="image-container"><div class="image-wrapper"><a class="overlay" href="/v/1">V1</a><img src="/t/1.jpg" data-original="/t/1.jpg"></div></div>
<div class="download-container"><a class="download-button" href="/dl/1">DL</a></div>
<select class="mirror"><option data-index="0" value="s1">S1</option></select>
<article><h1 class="entry-title">Title</h1><div class="entry-content" itemprop="description">Desc</div></article>
<div id="pembed"><iframe src="https://player.test/embed/1"></iframe></div>
<script>var config = {"file":"https://cdn.test/master.m3u8","sources":[{"file":"https://cdn.test/1.mp4","label":"720p"}]};</script>
</body></html>
""".trimIndent()
override suspend fun request(request: HttpRequest): HttpResponse =
HttpResponse(statusCode = 200, body = html, headers = mapOf("content-type" to "text/html"))
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionLiveFlowTest.kt
- Source · test / fixture · 309 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
46: class ExtensionLiveFlowTest {
48: fun runsLiveFlowForSelectedExtensions() {
117: private fun runFlow(source: DbSource, resolveCloudflare: Boolean, completeFlow: Boolean): FlowReport {
185: private fun <T> step(report: FlowReport, name: String, block: suspend () -> T): T? {
205: private fun selectSources(sources: List<DbSource>, selection: String): List<DbSource> = when {
219: private fun summary(reports: List<FlowReport>): String {
247: fun isValidLink(url: String): Boolean {
254: fun isCloudflare(message: String): Boolean {
261: fun isHostDefect(message: String): Boolean {
279: private class FlowReport(val name: String) {
294: fun render(): String {
Exact file bytes / download · SHA-256 bf2ff3a89a5e5e423ee7efa03ef437d024c2ee42d992e7538d4220d50ece5ab3.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.files.createPlatformLocalFileService
import eu.friedcutlet.yokan.services.http.EnhancedHttpService
import eu.friedcutlet.yokan.services.http.cookies.CookieJar
import eu.friedcutlet.yokan.services.http.createPlatformHttpService
import eu.friedcutlet.yokan.services.webview.WebViewRequest
import eu.friedcutlet.yokan.services.webview.createPlatformWebViewService
import java.nio.file.Path
import kotlin.test.Test
import org.junit.Assume.assumeTrue
import kotlin.test.fail
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService
/**
* Live end-to-end flow for repository extensions, exercised through the real
* QuickJS runtime and real OkHttp network stack. For each selected source it
* runs: popular -> latest (if supported) -> search -> detail -> page/video links
* (validating the returned links), and reports Cloudflare handling.
*
* Opt-in and network-bound, so it never runs in the default suite. Enable with:
*
* ./gradlew :composeApp:desktopTest --tests '*ExtensionLiveFlowTest*' \
* -Dyokan.generated.repository=/abs/path/build/repository/anime_index.json \
* -Dyokan.live.extensions=all # or sample:12, or a comma list of names/ids
* -Dyokan.live.parallelism=8 # source flows; QuickJS itself is globally bounded
* -Dyokan.live.itemType=anime # anime (default), manga, or novel
* -Dyokan.live.resolveCloudflare=true # defaults off for all-source audits
* -Dyokan.live.fullFlow=true # all-mode defaults to popular-page smoke coverage
*
* The test fails only on genuine host/runtime defects (missing globals, QuickJS
* exceptions, unported bridge calls). External outcomes — network errors,
* geo-blocks, and Cloudflare challenges — are classified and reported, not
* failed, because they are properties of the live site, not of Yokan.
*/
class ExtensionLiveFlowTest {
@Test
fun runsLiveFlowForSelectedExtensions() {
val selection = System.getProperty(SelectionProperty)?.trim().orEmpty()
val repoProperty = System.getProperty(RepositoryProperty)?.trim().orEmpty()
assumeTrue(
"set -D$SelectionProperty and -D$RepositoryProperty to run.",
selection.isNotBlank() && repoProperty.isNotBlank(),
)
val repositoryPath = Path.of(repoProperty).toAbsolutePath().normalize()
val repositoryUrl = repositoryPath.toUri().toString()
val itemType = when (System.getProperty(ItemTypeProperty)?.trim()?.lowercase()) {
null, "", "anime" -> DbItemType.Anime
"manga" -> DbItemType.Manga
"novel" -> DbItemType.Novel
else -> error("$ItemTypeProperty must be anime, manga, or novel.")
}
val catalogDatabase = InMemoryYokanDatabase()
val catalogCookieJar = CookieJar(catalogDatabase)
val catalogHttp = EnhancedHttpService(createPlatformHttpService(), catalogDatabase, catalogCookieJar)
val files = JvmLocalFileService(
downloadRoot = repositoryPath.parent.toString(),
backupRoot = repositoryPath.parent.toString(),
cacheRoot = repositoryPath.parent.toString(),
)
val catalog = HttpSourceCatalogService(catalogHttp, files)
val allSources = runBlocking { catalog.fetchSources(repositoryUrl, itemType) }
val selected = selectSources(allSources, selection)
check(selected.isNotEmpty()) { "No sources matched selection '$selection' (of ${allSources.size})." }
val parallelism = System.getProperty(ParallelismProperty)?.toIntOrNull()?.coerceIn(1, 8) ?: 8
val resolveCloudflare = System.getProperty(ResolveCloudflareProperty)?.toBooleanStrictOrNull()
?: !selection.equals("all", ignoreCase = true)
val completeFlow = System.getProperty(FullFlowProperty)?.toBooleanStrictOrNull()
?: !selection.equals("all", ignoreCase = true)
println(
"[live-flow] running ${selected.size} source(s) with parallelism $parallelism " +
"mode=${if (completeFlow) "complete" else "popular-smoke"} from $repositoryUrl",
)
val prepared = selected.map { source ->
val payload = runBlocking { catalog.fetchSourcePayload(source) }
source to payload
}
val dispatcher = Dispatchers.IO.limitedParallelism(parallelism)
val reports = runBlocking {
prepared.map { (source, payload) ->
async(dispatcher) {
if (payload == null) {
FlowReport(source.name).apply { hostError = "missing payload" }
} else {
runFlow(source.copy(sourceCode = payload.decodeToString()), resolveCloudflare, completeFlow)
}
}
}.awaitAll()
}
reports.forEachIndexed { index, report ->
println("[live-flow] (${index + 1}/${selected.size}) ${report.render()}")
}
val hostFailures = reports.filter { it.hostError != null }
println(summary(reports))
if (hostFailures.isNotEmpty()) {
fail(
"Host/runtime defects in ${hostFailures.size} source(s):\n" +
hostFailures.joinToString("\n") { " ${it.name}: ${it.hostError}" },
)
}
}
private fun runFlow(source: DbSource, resolveCloudflare: Boolean, completeFlow: Boolean): FlowReport {
val database = InMemoryYokanDatabase()
val cookieJar = CookieJar(database)
val http = EnhancedHttpService(createPlatformHttpService(), database, cookieJar)
val webView = createPlatformWebViewService(http, cookieJar, createPlatformLocalFileService())
val report = FlowReport(source.name)
val runtime = JavaScriptExtensionRuntimeService(source = source, http = http, database = database)
try {
// 1. Popular (with a Cloudflare cookie-refresh retry through the WebView resolver).
val popular = step(report, "popular") { runtime.popular(1) }
if (resolveCloudflare && report.cloudflare && popular == null) {
report.cloudflareResolveAttempted = true
val resolved = runCatching {
runBlocking {
webView.resolveCloudflare(WebViewRequest(url = source.baseUrl, title = source.name))
withTimeoutOrNull(StepTimeoutMs) { runtime.popular(1) }
}
}.getOrNull()
report.cloudflareResolved = resolved != null && resolved.items.isNotEmpty()
}
val listing = popular ?: (if (report.cloudflareResolved) runCatching { runBlocking { runtime.popular(1) } }.getOrNull() else null)
report.popularCount = listing?.items?.size ?: report.popularCount
if (!completeFlow) return report
// 2. Latest (only when advertised).
if (source.supportLatest == true || runCatching { runBlocking { runtime.supportsLatest() } }.getOrDefault(false)) {
val latest = step(report, "latest") { runtime.latest(1) }
report.latestCount = latest?.items?.size ?: -1
} else {
report.latestCount = -2 // not supported
}
// 3. Search — reuse a popular title so the query is meaningful.
val query = listing?.items?.firstOrNull()?.title?.split(Regex("\\s+"))?.firstOrNull()?.takeIf { it.length > 1 } ?: "a"
val search = step(report, "search") { runtime.search(query, 1, runtime.filterList()) }
report.searchCount = search?.items?.size ?: report.searchCount
// 4. Detail of the first popular (or search) item.
val entry = listing?.items?.firstOrNull() ?: search?.items?.firstOrNull()
if (entry != null) {
val detail = step(report, "detail") { runtime.detail(entry.url) }
if (detail != null) {
report.detailTitle = detail.title
report.chapterCount = detail.chapters.size
// 5. Page list / video list for the first chapter/episode; validate links.
val chapter = detail.chapters.firstOrNull()
if (chapter != null) {
if (source.itemType == DbItemType.Anime) {
val videos = step(report, "videoList") { runtime.videoList(chapter.url) }
report.linkCount = videos?.size ?: -1
report.validLinks = videos?.count { isValidLink(it.url) } ?: 0
report.firstLink = videos?.firstOrNull()?.url
} else {
val pages = step(report, "pageList") { runtime.pageList(chapter.url) }
report.linkCount = pages?.size ?: -1
report.validLinks = pages?.count { isValidLink(it.url) } ?: 0
report.firstLink = pages?.firstOrNull()?.url
}
}
}
}
} finally {
runtime.dispose()
}
return report
}
/** Run one flow step; classify host defects vs external failures; note Cloudflare. */
private fun <T> step(report: FlowReport, name: String, block: suspend () -> T): T? {
return try {
runBlocking { withTimeout(StepTimeoutMs) { block() } }
} catch (error: Throwable) {
val message = (generateSequence(error) { it.cause }.lastOrNull()?.message ?: error.message).orEmpty()
if (message.contains("stack overflow", ignoreCase = true)) {
println("[live-flow] ${report.name} $name stack trace:\n${error.stackTraceToString()}")
}
if (isCloudflare(message)) {
report.cloudflare = true
report.notes += "$name: cloudflare"
} else if (isHostDefect(message)) {
report.hostError = "$name: ${message.take(160)}"
} else {
report.notes += "$name: ${message.take(80)}"
}
null
}
}
private fun selectSources(sources: List<DbSource>, selection: String): List<DbSource> = when {
selection.equals("all", ignoreCase = true) -> sources
selection.startsWith("sample:", ignoreCase = true) -> {
val n = selection.substringAfter(":").toIntOrNull() ?: 12
// Spread the sample across the catalog rather than taking a contiguous block.
val stride = (sources.size / n).coerceAtLeast(1)
sources.filterIndexed { i, _ -> i % stride == 0 }.take(n)
}
else -> {
val tokens = selection.split(",").map { it.trim().lowercase() }.filter { it.isNotEmpty() }.toSet()
sources.filter { it.name.lowercase() in tokens || it.id.toString() in tokens }
}
}
private fun summary(reports: List<FlowReport>): String {
val popular = reports.count { it.popularCount > 0 }
val search = reports.count { it.searchCount > 0 }
val detail = reports.count { it.detailTitle != null }
val links = reports.count { it.validLinks > 0 }
val cloudflare = reports.count { it.cloudflare }
val cfResolved = reports.count { it.cloudflareResolved }
val hostErrors = reports.count { it.hostError != null }
return buildString {
appendLine("[live-flow] summary of ${reports.size} source(s):")
appendLine(" popular>0: $popular")
appendLine(" search>0: $search")
appendLine(" detail ok: $detail")
appendLine(" video/page links>0: $links")
appendLine(" cloudflare detected: $cloudflare (resolved via WebView: $cfResolved)")
appendLine(" host/runtime defects: $hostErrors")
}
}
private companion object {
const val SelectionProperty = "yokan.live.extensions"
const val RepositoryProperty = "yokan.generated.repository"
const val ItemTypeProperty = "yokan.live.itemType"
const val ParallelismProperty = "yokan.live.parallelism"
const val ResolveCloudflareProperty = "yokan.live.resolveCloudflare"
const val FullFlowProperty = "yokan.live.fullFlow"
const val StepTimeoutMs = 30_000L
fun isValidLink(url: String): Boolean {
val trimmed = url.trim()
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false
val host = trimmed.removePrefix("https://").removePrefix("http://").substringBefore("/").substringBefore("?")
return host.contains(".") && host.length > 3
}
fun isCloudflare(message: String): Boolean {
val lower = message.lowercase()
return "cloudflare" in lower || "anti-bot" in lower || "just a moment" in lower ||
"challenge" in lower || "http 403" in lower || "http 503" in lower ||
"ddos-guard" in lower
}
fun isHostDefect(message: String): Boolean {
val lower = message.lowercase()
if (isCloudflare(message)) return false
// Network/transport failures are external, not host defects.
if ("unknownhost" in lower || "sslhandshake" in lower || "connect" in lower ||
"timeout" in lower || "timed out" in lower || "closedbytechannel" in lower ||
"econnreset" in lower || "no route" in lower || "interrupted" in lower
) return false
return "not a function" in lower || "is not defined" in lower || "no setter" in lower ||
"quickjsexception" in lower || "not a constructor" in lower ||
"cannot read prop" in lower || "not implemented" in lower ||
"bridge channel" in lower || "undefined is not" in lower ||
"not iterable" in lower || "is not an object" in lower || "is undefined" in lower ||
"stack overflow" in lower || "syntaxerror" in lower || "unexpected token" in lower ||
"redeclaration of" in lower || "invalid property name" in lower
}
}
private class FlowReport(val name: String) {
var popularCount = -1
var latestCount = -3 // -3 unrun, -2 unsupported, -1 error, >=0 count
var searchCount = -1
var detailTitle: String? = null
var chapterCount = -1
var linkCount = -1
var validLinks = 0
var firstLink: String? = null
var cloudflare = false
var cloudflareResolveAttempted = false
var cloudflareResolved = false
var hostError: String? = null
val notes = mutableListOf<String>()
fun render(): String {
val latest = when (latestCount) { -3 -> "-"; -2 -> "n/a"; -1 -> "err"; else -> "$latestCount" }
val cf = when {
cloudflareResolved -> "cf:resolved"
cloudflareResolveAttempted -> "cf:unresolved"
cloudflare -> "cf:detected"
else -> "cf:none"
}
val link = firstLink?.let { " first=${it.take(60)}" } ?: ""
val err = hostError?.let { " HOST-ERROR[$it]" } ?: ""
val note = if (notes.isEmpty()) "" else " notes[${notes.joinToString("; ")}]"
return "$name: popular=$popularCount latest=$latest search=$searchCount " +
"detail=${detailTitle?.take(24) ?: "-"} chapters=$chapterCount links=$validLinks/$linkCount $cf$link$err$note"
}
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/SourceCatalogFileSecurityTest.kt
- Source · test / fixture · 57 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
15: class SourceCatalogFileSecurityTest {
17: fun rejectsPayloadSymlinkEscapingRepositoryDirectory() = runTest {
54: private object MissingHttpService : HttpService {
55: override suspend fun request(request: HttpRequest): HttpResponse =
Exact file bytes / download · SHA-256 9bc52d32561f51b13d1998031e098577d34ae461845b2c03cfa991b41d16d2b6.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import java.nio.file.Files
import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlinx.coroutines.test.runTest
class SourceCatalogFileSecurityTest {
@Test
fun rejectsPayloadSymlinkEscapingRepositoryDirectory() = runTest {
val root = Files.createTempDirectory("yokan-source-repo-")
try {
val repository = Files.createDirectory(root.resolve("repository"))
val outsidePayload = Files.writeString(root.resolve("outside.js"), "class DefaultExtension extends MProvider {}")
Files.createSymbolicLink(repository.resolve("source.js"), outsidePayload)
val index = Files.writeString(
repository.resolve("index.json"),
"""
[{
"id": 1,
"name": "Escaping source",
"baseUrl": "https://example.test",
"lang": "en",
"itemType": "Manga",
"sourceCodeLanguage": "JavaScript",
"sourceCodeUrl": "source.js",
"version": "1.0.0"
}]
""".trimIndent(),
)
val files = JvmLocalFileService(
downloadRoot = root.resolve("downloads").toString(),
backupRoot = root.resolve("backups").toString(),
cacheRoot = root.resolve("cache").toString(),
)
val service = HttpSourceCatalogService(MissingHttpService, files)
val source = assertNotNull(service.fetchSources(index.toUri().toString(), DbItemType.Manga).singleOrNull())
assertNull(service.fetchSourcePayload(source))
} finally {
root.toFile().deleteRecursively()
}
}
}
private object MissingHttpService : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse =
HttpResponse(statusCode = 404, body = "")
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/YuzonoJavaScriptRepositoryCompatibilityTest.kt
- Source · test / fixture · 75 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
17: class YuzonoJavaScriptRepositoryCompatibilityTest {
19: fun everyGeneratedYuzonoSourceLoadsInQuickJs() = runTest {
72: private object RejectingHttpService : HttpService {
73: override suspend fun request(request: HttpRequest): HttpResponse =
Exact file bytes / download · SHA-256 65d0dbcead1ccda01e26fa9cb7620b4c4c595707228eafae48426148337c60ef.
Complete file
package eu.friedcutlet.yokan.services.extensions
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.files.JvmLocalFileService
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import java.nio.file.Path
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService
class YuzonoJavaScriptRepositoryCompatibilityTest {
@Test
fun everyGeneratedYuzonoSourceLoadsInQuickJs() = runTest {
val repositoryProperty = System.getProperty(RepositoryProperty) ?: return@runTest
val repositoryPath = Path.of(repositoryProperty).toAbsolutePath().normalize()
val repositoryUrl = repositoryPath.toUri().toString()
val files = JvmLocalFileService(
downloadRoot = repositoryPath.parent.toString(),
backupRoot = repositoryPath.parent.toString(),
cacheRoot = repositoryPath.parent.toString(),
)
val catalog = HttpSourceCatalogService(RejectingHttpService, files)
val sources = catalog.fetchSources(repositoryUrl, DbItemType.Anime)
assertTrue(
sources.size >= ExpectedYuzonoSourceCount,
"Expected at least $ExpectedYuzonoSourceCount anime sources, found ${sources.size}",
)
assertEquals(sources.size, sources.map { it.id }.toSet().size, "Anime index contains duplicate ids")
assertTrue(sources.all { it.sourceCodeLanguage == DbSourceCodeLanguage.JavaScript })
assertTrue(sources.none { it.sourceCodeUrl.endsWith(".apk", ignoreCase = true) })
val failures = mutableListOf<String>()
sources.forEach { source ->
val payload = catalog.fetchSourcePayload(source)
if (payload == null) {
failures += "${source.name} (${source.sourceCodeUrl}): missing payload"
return@forEach
}
val runtime = JavaScriptExtensionRuntimeService(
source = source.copy(sourceCode = payload.decodeToString()),
http = RejectingHttpService,
)
try {
runtime.pageList("contract://no-network")
} catch (error: Throwable) {
val cause = generateSequence(error) { it.cause }.last()
failures += "${source.name} (${source.sourceCodeUrl}): ${cause.message?.take(160)}"
} finally {
runtime.dispose()
}
}
assertTrue(
failures.isEmpty(),
"QuickJS failed to load ${failures.size} source(s):\n${failures.joinToString("\n")}",
)
}
private companion object {
const val RepositoryProperty = "yokan.generated.repository"
const val ExpectedYuzonoSourceCount = 310
}
}
private object RejectingHttpService : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse =
error("Repository compatibility test attempted network access: ${request.method} ${request.url}")
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/ExtensionRuntimeStressTest.kt
- Source · test / fixture · 72 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
20: class ExtensionRuntimeStressTest {
22: fun concurrentCallsStayIsolatedAcrossEightNativePluginRuntimes() = runTest(timeout = 60.seconds) {
49: fun repeatedPluginFailureRebootsCleanlyBeforeTheNextSuccessfulCall() = runTest(timeout = 60.seconds) {
68: private fun source(index: Int) = DbSource(
Exact file bytes / download · SHA-256 d0271a9da05f7a9d09a4b9510c2e83e46457497c1940b3e0a5b75554251be397.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.services.extensions.lnreader.LnReaderExtensionRuntimeService
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import java.util.concurrent.ConcurrentHashMap
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.time.Duration.Companion.seconds
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
class ExtensionRuntimeStressTest {
@Test
fun concurrentCallsStayIsolatedAcrossEightNativePluginRuntimes() = runTest(timeout = 60.seconds) {
val requests = ConcurrentHashMap.newKeySet<String>()
val http = HttpService { request ->
delay(1)
check(requests.add(request.url)) { "Duplicate dispatch: ${request.url}" }
HttpResponse(200, request.url)
}
val runtimes = (0 until 8).map { index ->
LnReaderExtensionRuntimeService(source(index).copy(sourceCode = """
exports.default = {
async popularNovels(page) {
const response = await(fetchApi('https://source$index.test/' + page));
return [{name:response.text(),path:String(page)}];
}
};
"""), http)
}
try {
val titles = (0 until 400).map { page ->
async(Dispatchers.Default) { runtimes[page % 8].popular(page).items.single().title }
}.awaitAll()
assertEquals((0 until 400).map { "https://source${it % 8}.test/$it" }, titles)
assertEquals(400, requests.size)
} finally { runtimes.forEach { it.dispose() } }
}
@Test
fun repeatedPluginFailureRebootsCleanlyBeforeTheNextSuccessfulCall() = runTest(timeout = 60.seconds) {
val runtime = LnReaderExtensionRuntimeService(source(0).copy(sourceCode = """
var calls = 0;
exports.default = {
popularNovels(page) {
calls++;
if (page < 0) throw new Error('Expected plugin failure');
return [{name:String(calls),path:String(page)}];
}
};
"""), HttpService { error("No network expected") })
try {
repeat(50) {
assertEquals("1", runtime.popular(1).items.single().title)
assertFailsWith<Exception> { runtime.popular(-1) }
}
} finally { runtime.dispose() }
}
private fun source(index: Int) = DbSource(
id = index.toLong() + 1, name = "Stress $index", baseUrl = "https://source$index.test/", lang = "en",
itemType = DbItemType.Novel, sourceCodeLanguage = DbSourceCodeLanguage.LnReader,
)
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptExtensionRuntimeNativeTest.kt
- Source · test / fixture · 164 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
19: class JavaScriptExtensionRuntimeNativeTest {
22: class DefaultExtension extends MProvider {
38: fun castFromExecutingExtensionPersistsAndAnOmittedFieldDoesNotEraseIt() = runTest {
41: class DefaultExtension extends MProvider {
63: fun minifiedAsyncCodePreservesScrapedTextRegexAndTemplates() = runTest {
66: class DefaultExtension extends MProvider {
82: fun asyncMangayomiMethodsUseSynchronousClientBridge() = runTest {
87: class DefaultExtension extends MProvider {
107: fun searchPreservesMangayomiFilterShape() = runTest {
112: class DefaultExtension extends MProvider {
161: private object NativeNoopHttpService : HttpService {
162: override suspend fun request(request: HttpRequest): HttpResponse =
Exact file bytes / download · SHA-256 2e1f8b21fd5d4da6a999ad6533481b2c386937c9be0d57afd69e33751a3cc832.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.toDomain
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.TitleCredit
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.test.runTest
/** QuickJS integration coverage; native Zipline binaries are available on desktop, not Android JVM. */
class JavaScriptExtensionRuntimeNativeTest {
@Test fun relatedEntriesExecuteTheOptionalSourceMethodWithTheOriginalUrl() = runTest {
val service = JavaScriptExtensionRuntimeService(source.copy(sourceCode = """
class DefaultExtension extends MProvider {
async getRelated(url) {
return [{name:'Sequel',animes:[{title:'Next',url:url + '/next',thumbnail_url:'/next.jpg'}]}];
}
}
"""), NativeNoopHttpService)
try {
val result = service.related("/parent")
assertEquals("/parent/next", result.groups.single().items.single().url)
assertEquals("https://example.org/next.jpg", result.groups.single().items.single().thumbnailUrl)
} finally { service.dispose() }
val old = JavaScriptExtensionRuntimeService(source.copy(sourceCode = "class DefaultExtension extends MProvider {}"), NativeNoopHttpService)
try { assertEquals(false, old.related("/parent").supported) } finally { old.dispose() }
}
@Test
fun castFromExecutingExtensionPersistsAndAnOmittedFieldDoesNotEraseIt() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source.copy(sourceCode = """
class DefaultExtension extends MProvider {
getDetail(url) {
const detail = {name:'Title',link:'/title',chapters:[]};
if (url === '/cast') detail.cast = [{name:'Actor',role:'Voice actor',character:'Hero',image_url:'/portraits/a.jpg'}];
if (url === '/clear') detail.cast = [];
return detail;
}
}
"""),
http = NativeNoopHttpService,
)
try {
val repository = DefaultYokanRepository(InMemoryYokanDatabase(seedDatabaseSnapshot()))
val cast = listOf(TitleCredit("Actor", "Voice actor", "Hero", "https://example.org/portraits/a.jpg"))
val first = repository.upsertRemoteDetail(source.toDomain(), service.detail("/cast"))
assertEquals(cast, first.cast)
assertEquals(cast, repository.upsertRemoteDetail(source.toDomain(), service.detail("/omitted")).cast)
assertEquals(emptyList(), repository.upsertRemoteDetail(source.toDomain(), service.detail("/clear")).cast)
} finally { service.dispose() }
}
@Test
fun minifiedAsyncCodePreservesScrapedTextRegexAndTemplates() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source.copy(sourceCode = """
class DefaultExtension extends MProvider {
async getPopular(page) {
const response = await(new Client().get('https://example.org/list'));
const title = /await value/.test('await value') ? 'Please await your turn' : 'wrong';
return await // The operand may be on the next line without changing return semantics.
{list:[{name:`${'$'}{title}: ${'$'}{await(response.body)}`,link:'/test'}],hasNextPage:false};
}
}
"""),
http = HttpService { HttpResponse(200, "async function(x)") },
)
try { assertEquals("Please await your turn: async function(x)", service.popular(1).items.single().title) }
finally { service.dispose() }
}
@Test
fun asyncMangayomiMethodsUseSynchronousClientBridge() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source.copy(
sourceCode =
"""
class DefaultExtension extends MProvider {
async getPopular(page) {
const response = await new Client().get("https://example.org/list");
return { list: [{ name: response.body, link: "/async" }], hasNextPage: false };
}
}
""".trimIndent(),
),
http = HttpService { HttpResponse(statusCode = 200, body = "Async Title", headers = emptyMap()) },
)
try {
val listing = service.popular(1)
assertEquals("Async Title", listing.items.single().title)
} finally {
service.dispose()
}
}
@Test
fun searchPreservesMangayomiFilterShape() = runTest {
val service = JavaScriptExtensionRuntimeService(
source = source.copy(
sourceCode =
"""
class DefaultExtension extends MProvider {
getFilterList() {
return [
{
type_name: "SelectFilter", name: "Sort", state: 0,
values: [
{ type_name: "SelectOption", name: "Popular", value: "popular" },
{ type_name: "SelectOption", name: "Latest", value: "latest" }
]
},
{
type_name: "GroupFilter", name: "Genres",
state: [{ type_name: "CheckBox", name: "Action", value: "action", state: false }]
}
];
}
search(query, page, filters) {
const sort = filters[0].values[filters[0].state].value;
const checked = filters[1].state[0].state;
return { list: [{ name: sort + ":" + checked, link: "/filtered" }], hasNextPage: false };
}
}
""".trimIndent(),
),
http = NativeNoopHttpService,
)
try {
val listing = service.search("query", 1, service.filterList())
assertEquals("popular:false", listing.items.single().title)
} finally {
service.dispose()
}
}
private companion object {
val source = DbSource(
id = 42L,
name = "Sample JS",
baseUrl = "https://example.org",
lang = "en",
itemType = DbItemType.Manga,
sourceCodeLanguage = DbSourceCodeLanguage.JavaScript,
sourceCode = "",
supportLatest = true,
)
}
}
private object NativeNoopHttpService : HttpService {
override suspend fun request(request: HttpRequest): HttpResponse =
HttpResponse(statusCode = 200, body = "", headers = emptyMap())
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptHostCancellationTest.kt
- Source · test / fixture · 50 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
15: class JavaScriptHostCancellationTest {
17: fun cancellingRunawayScriptReleasesHostForNextCall() = assertCancelledCallReleasesHost(
22: fun cancellingCallBlockedOnBridgeHttpReleasesHostForNextCall() = assertCancelledCallReleasesHost(
26: private fun assertCancelledCallReleasesHost(script: String) = runBlocking {
Exact file bytes / download · SHA-256 15e224acdb4291a52d42f74fd901d68e72acf034f5b1decd7f64eea15679c74b.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.services.http.HttpService
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.Duration.Companion.seconds
class JavaScriptHostCancellationTest {
@Test
fun cancellingRunawayScriptReleasesHostForNextCall() = assertCancelledCallReleasesHost(
script = "__bridge.sendMessage('entered', ''); while (true) {}",
)
@Test
fun cancellingCallBlockedOnBridgeHttpReleasesHostForNextCall() = assertCancelledCallReleasesHost(
script = "__bridge.sendMessage('entered', ''); __bridge.sendMessage('http_get', JSON.stringify([null, null, 'https://example.org', {}, null]));",
)
private fun assertCancelledCallReleasesHost(script: String) = runBlocking {
val entered = CompletableDeferred<Unit>()
val host = JavaScriptHost(
source = DbSource(id = 1L, name = "Runaway", sourceCode = "var ready = true;"),
http = HttpService { awaitCancellation() },
database = null,
engineFactory = { bridge -> QuickJsJavaScriptEngine(bridge) },
boot = { engine -> engine.evaluate("var ready = true;") },
channels = { channel, _ -> if (channel == "entered") "null".also { entered.complete(Unit) } else null },
)
try {
val blocked = launch(Dispatchers.Default) { host.call { it.evaluate(script) } }
entered.await()
blocked.cancel()
// Without cancellation support the first call holds the host for the 30 s evaluation timeout.
val next = withTimeout(5.seconds) { host.call { it.evaluate("1 + 1") } }
assertEquals("2", next)
} finally {
host.close()
}
}
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/LnReaderExtensionRuntimeNativeTest.kt
- Source · test / fixture · 133 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
18: class LnReaderExtensionRuntimeNativeTest {
20: fun commonJsDefaultExportImportsAndAsyncResultsUseHostServices() = runTest {
41: fun publishedNovelUpdatesPluginLoadsThroughLegacyJavaScriptImport() = runTest {
74: fun directModuleAndLegacyGlobalExportsStillWork() = runTest {
85: fun pluginFailuresSurfaceInsteadOfReturningEmptyResults() = runTest {
Exact file bytes / download · SHA-256 b5c789ea4e0ff514d03a1d262e356b0ffad5186f30b067a5df9e946ab1b2ade0.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.DbSourceCodeLanguage
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.lnreader.LnReaderExtensionRuntimeService
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
class LnReaderExtensionRuntimeNativeTest {
@Test
fun commonJsDefaultExportImportsAndAsyncResultsUseHostServices() = runTest {
val http = RecordingHttpService {
HttpResponse(200, """
<div class="search_main_box_nu"><div class="search_title"><a href="https://example.org/series/test/">Test & Title</a></div><img src="cover.jpg"></div>
""".trimIndent())
}
val runtime = LnReaderExtensionRuntimeService(source, http)
try {
assertEquals("Test & Title", runtime.popular(2).items.single().title)
assertEquals("series/test/", runtime.search("hello", 1, emptyList()).items.single().url)
assertTrue(runtime.supportsLatest())
runtime.latest(3)
assertEquals(listOf("https://example.org/popular/2", "https://example.org/search/hello/1", "https://example.org/latest/3"), http.requests.map { it.url })
val detail = runtime.detail("series/test/")
assertEquals("Test", detail.title)
assertEquals("chapter/1", detail.chapters.single().url)
assertEquals("<p>Chapter</p>", runtime.htmlContent("Test", "chapter/1"))
} finally { runtime.dispose() }
}
@Test
fun publishedNovelUpdatesPluginLoadsThroughLegacyJavaScriptImport() = runTest {
val plugin = checkNotNull(javaClass.getResource("/lnreader/novelupdates-0.9.9.js")).readText()
val http = RecordingHttpService { request ->
val body = when {
request.url.endsWith("admin-ajax.php") -> """<li class="sp_li_chp"><a>Group</a><a href="//translator.test/chapter/1">c1</a></li>"""
request.url.endsWith("series/test/") -> """
<div class="seriestitlenu">Test Novel</div><div id="authtag">Author</div>
<div id="seriesgenre"><a>Fantasy</a></div><div id="editstatus">Ongoing</div>
<div id="showtype">Web Novel</div><div id="editdescription">Summary</div>
<input id="mypostid" value="123">
"""
request.url.endsWith("chapter/test/") -> """<html><title>Chapter</title><body><article>Chapter body</article></body></html>"""
else -> """<div class="search_main_box_nu"><div class="search_title"><a href="https://www.novelupdates.com/series/test/">Test Novel</a></div><img src="cover.jpg"></div>"""
}
HttpResponse(200, body)
}
val factory = DynamicExtensionRuntimeFactory(InMemoryYokanDatabase(), http)
val runtime = factory.create(source.copy(sourceCodeLanguage = DbSourceCodeLanguage.JavaScript, sourceCode = plugin))
try {
assertEquals("Test Novel", runtime.popular(1).items.single().title)
assertEquals("series/test/", runtime.search("test", 1, emptyList()).items.single().url)
val detail = runtime.detail("series/test/")
assertEquals("Test Novel", detail.title)
assertEquals("Author", detail.author)
assertEquals("https://translator.test/chapter/1", detail.chapters.single().url)
val post = http.requests.last()
assertEquals("POST", post.method)
assertEquals("action=nd_getchapters&mygrr=0&mypostid=123", post.body)
assertTrue(runtime.htmlContent("Chapter", "chapter/test/").contains("Chapter body"))
} finally { runtime.dispose(); factory.clear() }
}
@Test
fun directModuleAndLegacyGlobalExportsStillWork() = runTest {
for (assignment in listOf("module.exports", "plugin")) {
val runtime = LnReaderExtensionRuntimeService(source.copy(sourceCode = """
$assignment = { popularNovels: function() { return [{name:cheerio.load('<b>Direct</b>')('b').text(), path:'direct'}]; } };
"""), HttpService { error("unused") })
try { assertEquals("Direct", runtime.popular(1).items.single().title) }
finally { runtime.dispose() }
}
}
@Test
fun pluginFailuresSurfaceInsteadOfReturningEmptyResults() = runTest {
val runtime = LnReaderExtensionRuntimeService(source.copy(sourceCode = """
exports.default = { popularNovels: function() { return Promise.reject(new Error('Plugin failed')); } };
"""), HttpService { error("unused") })
try {
val failure = assertFailsWith<Exception> { runtime.popular(1) }
assertTrue(failure.message.orEmpty().contains("Plugin failed"))
} finally { runtime.dispose() }
}
private val source = DbSource(
id = 999L, name = "LNReader", baseUrl = "https://example.org/", lang = "en",
itemType = DbItemType.Novel, sourceCodeLanguage = DbSourceCodeLanguage.LnReader,
sourceCode = """
Object.defineProperty(exports, '__esModule', { value: true });
var cheerio = require('cheerio');
var fetch = require('@libs/fetch');
var FilterTypes = require('@libs/filterInputs').FilterTypes;
function Plugin() {
this.filters = { sort: { type: FilterTypes.Picker, value: 'popular' } };
}
Plugin.prototype.popularNovels = function(page, options) {
// Published TypeScript __awaiter helpers construct Promise chains like this.
return new Promise(function(resolve, reject) {
Promise.resolve(fetch.fetchApi('https://example.org/' + (options.showLatestNovels ? 'latest' : options.filters.sort.value) + '/' + page))
.then(function(response) { return response.text(); })
.then(function(html) {
var items = [], select = cheerio.load(html);
select('div.search_main_box_nu').each(function(index, element) {
var link = select(element).find('.search_title > a');
items.push({name: link.text(), path: link.attr('href').replace('https://example.org/', ''), cover: select(element).find('img').attr('src')});
});
resolve(items);
}).catch(reject);
});
};
Plugin.prototype.searchNovels = async function(query, page) {
const response = await fetch.fetchApi('https://example.org/search/' + query + '/' + page);
const select = cheerio.load(await response.text());
return [{ name: select('.search_title > a').text(), path: 'series/test/' }];
};
Plugin.prototype.parseNovel = function(path) {
return Promise.resolve({ name: 'Test', path: path, chapters: [{name: 'Chapter 1', path: 'chapter/1'}] });
};
Plugin.prototype.parseChapter = function() { return Promise.resolve('<p>Chapter</p>'); };
exports.default = new Plugin();
""".trimIndent(),
)
}
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerDataDirTest.kt
- Source · test / fixture · 18 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class ExtensionServerDataDirTest {
11: fun extraProfilesGetOwnedServerDataDirAndDefaultKeepsLegacyLocations() {
Exact file bytes / download · SHA-256 c5e591d64926d0a249836b81a91fa4c0f5a1bd8baadd5c7cf098323662b6955a.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.domain.ProfileId
import java.io.File
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
class ExtensionServerDataDirTest {
@Test
fun extraProfilesGetOwnedServerDataDirAndDefaultKeepsLegacyLocations() {
val root = File("/data/yokan")
val extra = ProfileId("p_" + "a".repeat(32))
assertNull(extensionServerDataDir(root, ProfileId.Default))
assertEquals(File(root, "profiles/${extra.value}/extension-server-data"), extensionServerDataDir(root, extra))
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/GzipDecompress.ios.kt
- Source · implementation · 72 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray = memScoped {
Exact file bytes / download · SHA-256 addc2c543d8cae94aa60eacb31a972cadef3ec21a8e1a6029254b3498f52ffa1.
Complete file
package eu.friedcutlet.yokan.services.extensions
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.usePinned
import platform.zlib.Z_BUF_ERROR
import platform.zlib.Z_DATA_ERROR
import platform.zlib.Z_MEM_ERROR
import platform.zlib.Z_OK
import platform.zlib.Z_STREAM_END
import platform.zlib.inflate
import platform.zlib.inflateEnd
import platform.zlib.inflateInit2
import platform.zlib.z_stream
@OptIn(ExperimentalForeignApi::class)
internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray = memScoped {
val stream = alloc<z_stream>()
val input = if (bytes.isEmpty()) ByteArray(1) else bytes
val chunks = mutableListOf<ByteArray>()
var outputSize = 0
var initialized = false
try {
input.usePinned { pinnedInput ->
stream.next_in = pinnedInput.addressOf(0).reinterpret()
stream.avail_in = bytes.size.toUInt()
check(inflateInit2(stream.ptr, 31) == Z_OK) { "Could not initialize gzip decompression" }
initialized = true
while (true) {
val chunk = ByteArray(32 * 1024)
val result = chunk.usePinned { pinnedOutput ->
stream.next_out = pinnedOutput.addressOf(0).reinterpret()
stream.avail_out = chunk.size.toUInt()
inflate(stream.ptr, 0)
}
val produced = chunk.size - stream.avail_out.toInt()
if (produced > 0) {
check(produced <= MaxProtobufDecompressedBytes - outputSize) {
"Decompressed protobuf exceeds the 64 MiB limit"
}
chunks += chunk.copyOf(produced)
outputSize += produced
}
when (result) {
Z_STREAM_END -> break
Z_OK -> check(produced > 0 || stream.avail_in > 0u) {
"Gzip decompression made no progress"
}
Z_BUF_ERROR, Z_DATA_ERROR, Z_MEM_ERROR ->
error("Invalid gzip data (zlib error $result)")
else -> error("Gzip decompression failed (zlib error $result)")
}
}
}
ByteArray(outputSize).also { output ->
var offset = 0
chunks.forEach { chunk ->
chunk.copyInto(output, offset)
offset += chunk.size
}
}
} finally {
if (initialized) inflateEnd(stream.ptr)
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/QuickJsJavaScriptEngine.ios.kt
- Source · implementation · 67 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
21: internal actual fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher = NSThreadDispatcher(stackBytes)
23: private class NSThreadDispatcher(stackBytes: Long) : CloseableCoroutineDispatcher() {
36: override fun dispatch(context: CoroutineContext, block: Runnable) {
49: override fun close() {
56: private fun runTasks() {
Exact file bytes / download · SHA-256 e1ac3b5ce6c1ca7ca2013d503d2089ed5227a64720539e3d87b8c8b95ad5e467.
Complete file
@file:OptIn(ExperimentalCoroutinesApi::class, kotlinx.cinterop.BetaInteropApi::class)
package eu.friedcutlet.yokan.services.extensions.js
import kotlinx.cinterop.autoreleasepool
import kotlinx.coroutines.CloseableCoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Runnable
import platform.Foundation.NSCondition
import platform.Foundation.NSThread
import kotlin.coroutines.CoroutineContext
// zipline builds QuickJS for Kotlin/Native without optimization, so one JS call costs ~22 KiB of
// native stack here versus ~1 KiB on the JVM; 128 MiB buys ~5,900 levels (8 MiB would be ~370).
// Stack pages are only committed as deep JS actually touches them.
internal actual const val QuickJsMaxStackSizeBytes: Long = 128L * 1024L * 1024L
// Kotlin/Native workers (newSingleThreadContext) run on default 512 KiB pthread stacks, far below the
// QuickJS limit, so each engine gets an NSThread with an explicit stack size instead.
internal actual fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher = NSThreadDispatcher(stackBytes)
private class NSThreadDispatcher(stackBytes: Long) : CloseableCoroutineDispatcher() {
private val condition = NSCondition()
private val tasks = ArrayDeque<Runnable>()
private var closed = false
init {
NSThread { runTasks() }.apply {
name = "quickjs"
stackSize = stackBytes.toULong()
start()
}
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
condition.lock()
val accepted = !closed
if (accepted) {
tasks.addLast(block)
condition.signal()
}
condition.unlock()
// Like a shut-down JVM executor: late continuations (cancelled zipline jobs) finish elsewhere.
if (!accepted) Dispatchers.Default.dispatch(context, block)
}
/** Lets the thread finish the queued tasks, then exit. */
override fun close() {
condition.lock()
closed = true
condition.signal()
condition.unlock()
}
private fun runTasks() {
while (true) {
condition.lock()
while (tasks.isEmpty() && !closed) condition.wait()
val task = tasks.removeFirstOrNull()
condition.unlock()
if (task == null) return
// Host bridge calls create Objective-C objects; this thread has no run loop to drain them.
autoreleasepool { task.run() }
}
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerAdapter.ios.kt
- Source · implementation · 133 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
26: internal actual fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter =
35: private class IosExtensionServerAdapter(private val ownsEmbeddedRuntime: Boolean) : PlatformExtensionServerAdapter {
65: override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? =
68: override suspend fun install(
73: override suspend fun detect(path: String): InstalledExtensionServerBundle = unsupportedInstall()
75: private fun unsupportedInstall(): Nothing = throw ExtensionServerException(
80: private fun fileExists(path: String): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path)
83: private class EmbeddedMihonExtensionServer : ExtensionServer {
87: override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus {
112: override suspend fun stop(): ExtensionServerStatus {
Exact file bytes / download · SHA-256 ccdcfe3519d5aa8cbb818675103362820286335436792977840fdc8b3b37cc40.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.embeddedmihon.YokanEmbeddedMihonStart
import eu.friedcutlet.yokan.embeddedmihon.YokanEmbeddedMihonStop
import eu.friedcutlet.yokan.ext.ExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServerConfig
import eu.friedcutlet.yokan.ext.ExtensionServerException
import eu.friedcutlet.yokan.ext.ExtensionServerPhase
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.ExtensionServerStatus
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import platform.Foundation.NSBundle
import platform.Foundation.NSFileManager
import platform.Foundation.NSString
import platform.Foundation.NSUTF8StringEncoding
import platform.Foundation.stringWithContentsOfFile
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
internal actual fun createPlatformExtensionServerAdapter(profileId: ProfileId): PlatformExtensionServerAdapter =
IosExtensionServerAdapter(profileId == ProfileId.Default)
internal actual val defaultMihonProxyUrl: String = "https://bridge.mangayomi.30062022.xyz"
/**
* The embedded JVM is process-wide and its bridge state cannot be reset per profile, so only
* the Default profile may run it; other profiles can still use a remote server URL.
*/
private class IosExtensionServerAdapter(private val ownsEmbeddedRuntime: Boolean) : PlatformExtensionServerAdapter {
override val mode = ExtensionServerRuntimeMode.IosSideloadedJvm
override val requiresBundleDownload = false
override val unavailableReason: String? =
if (ownsEmbeddedRuntime) null else "The embedded Mihon runtime on iOS is only available in the default profile. Use a remote server URL here."
override val installationAvailable: Boolean
get() = ownsEmbeddedRuntime && fileExists(runtimeFrameworkPath) && fileExists(serverJarPath)
override val bundledServerVersion: String?
get() = runtimeMetadata["version"]?.takeIf { runtimeMetadata["server"] == "YES" && installationAvailable }
override val server: ExtensionServer = EmbeddedMihonExtensionServer()
private val resourcePath: String get() = NSBundle.mainBundle.resourcePath.orEmpty()
private val runtimeFrameworkPath: String
get() = "${NSBundle.mainBundle.bundlePath}/Frameworks/OpenJDKRuntime.framework/OpenJDKRuntime"
private val serverJarPath: String get() = "$resourcePath/MExtensionServer.jar"
private val runtimeMetadata by lazy {
NSString.stringWithContentsOfFile(
"$resourcePath/.yokan-extension-runtime-mode",
NSUTF8StringEncoding,
null,
).orEmpty()
.trim()
.split(';')
.mapNotNull { field ->
val separator = field.indexOf('=')
if (separator <= 0) null else field.take(separator) to field.drop(separator + 1)
}
.toMap()
}
override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? =
ExtensionServerConfig(port, serverJarPath = this.serverJarPath).takeIf { installationAvailable }
override suspend fun install(
release: ExtensionServerRelease,
onProgress: (Long, Long) -> Unit,
): InstalledExtensionServerBundle = unsupportedInstall()
override suspend fun detect(path: String): InstalledExtensionServerBundle = unsupportedInstall()
private fun unsupportedInstall(): Nothing = throw ExtensionServerException(
"INSTALL_NOT_SUPPORTED",
"The iOS extension server is bundled with sideloaded Yokan builds",
)
private fun fileExists(path: String): Boolean = NSFileManager.defaultManager.fileExistsAtPath(path)
}
private class EmbeddedMihonExtensionServer : ExtensionServer {
private val mutableStatus = MutableStateFlow(ExtensionServerStatus.Stopped)
override val status: StateFlow<ExtensionServerStatus> = mutableStatus
override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus {
mutableStatus.value = ExtensionServerStatus(ExtensionServerPhase.Starting, config.port, "Starting embedded Mihon runtime")
return suspendCoroutine { continuation ->
YokanEmbeddedMihonStart(config.port) { port, error ->
if (error != null) {
mutableStatus.value = ExtensionServerStatus(
ExtensionServerPhase.Failed,
message = error.localizedDescription,
)
continuation.resumeWithException(
ExtensionServerException("JVM_START_FAILED", error.localizedDescription),
)
} else {
val running = ExtensionServerStatus(
ExtensionServerPhase.Running,
port,
"Embedded Mihon runtime is listening on port $port",
)
mutableStatus.value = running
continuation.resume(running)
}
}
}
}
override suspend fun stop(): ExtensionServerStatus {
// The embedded JVM is process-wide: a session that never started it must not stop it.
if (mutableStatus.value.phase == ExtensionServerPhase.Stopped) return ExtensionServerStatus.Stopped
mutableStatus.value = mutableStatus.value.copy(phase = ExtensionServerPhase.Stopping)
return suspendCoroutine { continuation ->
YokanEmbeddedMihonStop { error ->
if (error != null) {
mutableStatus.value = ExtensionServerStatus(
ExtensionServerPhase.Failed,
message = error.localizedDescription,
)
continuation.resumeWithException(
ExtensionServerException("JVM_STOP_FAILED", error.localizedDescription),
)
} else {
mutableStatus.value = ExtensionServerStatus.Stopped
continuation.resume(ExtensionServerStatus.Stopped)
}
}
}
}
}
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerPorts.ios.kt
- Source · implementation · 65 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
22: internal actual fun findAvailableExtensionServerPort(preferred: Int): Int =
31: private fun probeLoopbackPort(port: Int): Int? = memScoped {
59: private fun portToNetworkOrder(port: Int): UShort =
62: private fun portFromNetworkOrder(port: UShort): Int {
Exact file bytes / download · SHA-256 8a3bb8935575f5c8c1ca7f9b8def9cf6e04548ae52ce4fe41e47a956223deab0.
Complete file
@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.ext.ExtensionServerException
import kotlinx.cinterop.alloc
import kotlinx.cinterop.convert
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.sizeOf
import kotlinx.cinterop.value
import platform.posix.AF_INET
import platform.posix.SOCK_STREAM
import platform.posix.bind
import platform.posix.close
import platform.posix.getsockname
import platform.posix.sockaddr_in
import platform.posix.socket
import platform.posix.socklen_tVar
internal actual fun findAvailableExtensionServerPort(preferred: Int): Int =
probeLoopbackPort(preferred)
?: probeLoopbackPort(0)
?: throw ExtensionServerException(
"NO_FREE_PORT",
"No loopback TCP port is available for the local extension server",
)
/** Returns the bound port when [port] (or a kernel-assigned port for 0) is bindable, else null. */
private fun probeLoopbackPort(port: Int): Int? = memScoped {
val fd = socket(AF_INET, SOCK_STREAM, 0)
if (fd < 0) return@memScoped null
try {
val address = alloc<sockaddr_in>()
address.sin_len = sizeOf<sockaddr_in>().convert()
address.sin_family = AF_INET.convert()
address.sin_port = portToNetworkOrder(port)
address.sin_addr.s_addr = LoopbackNetworkOrder
if (bind(fd, address.ptr.reinterpret(), sizeOf<sockaddr_in>().convert()) != 0) {
return@memScoped null
}
if (port != 0) return@memScoped port
val bound = alloc<sockaddr_in>()
val length = alloc<socklen_tVar>()
length.value = sizeOf<sockaddr_in>().convert()
if (getsockname(fd, bound.ptr.reinterpret(), length.ptr) != 0) return@memScoped null
portFromNetworkOrder(bound.sin_port)
} finally {
close(fd)
}
}
// Every Kotlin/Native Apple target is little-endian, so network order is a plain byte swap.
/** 127.0.0.1 in network byte order, written as the little-endian host value. */
private const val LoopbackNetworkOrder: UInt = 0x0100007Fu
private fun portToNetworkOrder(port: Int): UShort =
(((port and 0xFF) shl 8) or ((port ushr 8) and 0xFF)).toUShort()
private fun portFromNetworkOrder(port: UShort): Int {
val raw = port.toInt() and 0xFFFF
return ((raw and 0xFF) shl 8) or ((raw ushr 8) and 0xFF)
}
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/GzipDecompress.jvm.kt
- Source · implementation · 23 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
7: internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray {
Exact file bytes / download · SHA-256 10562ffe2fa9de3fd8cfaf5235899ea5727c24837025af1c9931a6f812b4def4.
Complete file
package eu.friedcutlet.yokan.services.extensions
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.GZIPInputStream
internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray {
val output = ByteArrayOutputStream()
val buffer = ByteArray(32 * 1024)
var outputSize = 0
GZIPInputStream(ByteArrayInputStream(bytes)).use { input ->
while (true) {
val count = input.read(buffer)
if (count < 0) break
check(count <= MaxProtobufDecompressedBytes - outputSize) {
"Decompressed protobuf exceeds the 64 MiB limit"
}
output.write(buffer, 0, count)
outputSize += count
}
}
return output.toByteArray()
}
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/QuickJsJavaScriptEngine.jvm.kt
- Source · implementation · 15 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
13: internal actual fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher =
Exact file bytes / download · SHA-256 5e9520fcdcd51d938f79be3ecdb00b80f6a3838890097afd99b296f99678386a.
Complete file
@file:OptIn(ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.extensions.js
import kotlinx.coroutines.CloseableCoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.Executors
internal actual const val QuickJsMaxStackSizeBytes: Long = 8L * 1024L * 1024L
// Daemon, so a runtime that is never disposed cannot keep the desktop JVM alive.
internal actual fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher =
Executors.newSingleThreadExecutor { task -> Thread(null, task, "quickjs", stackBytes).apply { isDaemon = true } }
.asCoroutineDispatcher()
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerPorts.jvm.kt
- Source · implementation · 22 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: internal actual fun findAvailableExtensionServerPort(preferred: Int): Int =
17: private fun probeLoopbackPort(port: Int): Int? = runCatching {
Exact file bytes / download · SHA-256 7c7a1d835c31455bc2e129495121e6039050ed5fb92eb0a590aada7bd710c425.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.ext.ExtensionServerException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
internal actual fun findAvailableExtensionServerPort(preferred: Int): Int =
probeLoopbackPort(preferred)
?: probeLoopbackPort(0)
?: throw ExtensionServerException(
"NO_FREE_PORT",
"No loopback TCP port is available for the local extension server",
)
/** Returns the bound port when [port] (or an ephemeral port for 0) is bindable, else null. */
private fun probeLoopbackPort(port: Int): Int? = runCatching {
ServerSocket().use { socket ->
socket.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), port))
socket.localPort
}
}.getOrNull()
composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerPortsJvmTest.kt
- Source · test / fixture · 34 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
11: class ExtensionServerPortsJvmTest {
13: fun returnsPreferredPortWhenItIsFree() {
23: fun fallsBackToAnotherFreePortWhenPreferredPortIsTaken() {
Exact file bytes / download · SHA-256 b164cb3b5ec0f640b9a39283544c03743a4c2d9edb49e15c87c4762b84a2b4e7.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
class ExtensionServerPortsJvmTest {
@Test
fun returnsPreferredPortWhenItIsFree() {
val free = ServerSocket().use { socket ->
socket.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), 0))
socket.localPort
}
assertEquals(free, findAvailableExtensionServerPort(free))
}
@Test
fun fallsBackToAnotherFreePortWhenPreferredPortIsTaken() {
ServerSocket().use { occupied ->
occupied.bind(InetSocketAddress(InetAddress.getLoopbackAddress(), 0))
val taken = occupied.localPort
val resolved = findAvailableExtensionServerPort(taken)
assertNotEquals(taken, resolved)
assertTrue(resolved in 1..65535, "resolved port out of range: $resolved")
}
}
}
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridge.nonWeb.kt
- Source · implementation · 42 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: actual fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? {
21: actual fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? {
27: actual fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? {
39: private fun aesCbcCipher(key: ByteArray): IvCipher = provider.get(AES.CBC)
Exact file bytes / download · SHA-256 d4a7a6a5162c16488f85dd006c863e09eed4ab6ab4c1660f44c08c36aa1ea120.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import dev.whyoleg.cryptography.CryptographyProvider
import dev.whyoleg.cryptography.DelicateCryptographyApi
import dev.whyoleg.cryptography.algorithms.AES
import dev.whyoleg.cryptography.operations.IvCipher
// JDK provider on Android/desktop, CryptoKit + CommonCrypto on iOS. Invalid key sizes and
// malformed ciphertext throw inside the provider; the JS bridge contract is null instead.
private val provider = CryptographyProvider.Default
private const val AES_BLOCK_SIZE = 16
@OptIn(DelicateCryptographyApi::class)
actual fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? {
if (iv.size != AES_BLOCK_SIZE) return null
return runCatching { aesCbcCipher(key).encryptWithIvBlocking(iv, data) }.getOrNull()
}
@OptIn(DelicateCryptographyApi::class)
actual fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? {
if (iv.size != AES_BLOCK_SIZE) return null
return runCatching { aesCbcCipher(key).decryptWithIvBlocking(iv, data) }.getOrNull()
}
@OptIn(DelicateCryptographyApi::class)
actual fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? {
if (block.size != AES_BLOCK_SIZE) return null
return runCatching {
provider.get(AES.ECB)
.keyDecoder()
.decodeFromByteArrayBlocking(AES.Key.Format.RAW, key)
.cipher(padding = false)
.encryptBlocking(block)
}.getOrNull()
}
// PKCS#7 padding, matching the previous `AES/CBC/PKCS5Padding` and `kCCOptionPKCS7Padding` actuals.
private fun aesCbcCipher(key: ByteArray): IvCipher = provider.get(AES.CBC)
.keyDecoder()
.decodeFromByteArrayBlocking(AES.Key.Format.RAW, key)
.cipher(padding = true)
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptEngine.nonWeb.kt
- Source · implementation · 4 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
3: actual fun createJavaScriptEngine(bridge: JavaScriptMessageBridge): JavaScriptEngine =
Exact file bytes / download · SHA-256 1e9355bdb3f22280fb9a0fc8b728a439cca13d23d8354a04337682fe8785d5d9.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
actual fun createJavaScriptEngine(bridge: JavaScriptMessageBridge): JavaScriptEngine =
QuickJsJavaScriptEngine(bridge)
composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/QuickJsJavaScriptEngine.kt
- Source · implementation · 142 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
47: internal expect fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher
49: private interface YokanJavaScriptBridge : ZiplineService {
50: fun sendMessage(channel: String, payload: String): String
61: internal class QuickJsJavaScriptEngine(
73: object : YokanJavaScriptBridge {
74: override fun sendMessage(channel: String, payload: String): String =
94: override fun evaluate(script: String, isCancelled: () -> Boolean): String = runBlocking(dispatcher) {
110: override fun close() {
Exact file bytes / download · SHA-256 07226072ac32e11b216136ac43cb9d3b82025f0763a458046ac8ff177aa51901.
Complete file
@file:OptIn(ExperimentalCoroutinesApi::class)
package eu.friedcutlet.yokan.services.extensions.js
import app.cash.zipline.EngineApi
import app.cash.zipline.InterruptHandler
import app.cash.zipline.QuickJs
import app.cash.zipline.Zipline
import app.cash.zipline.ZiplineService
import kotlinx.coroutines.CloseableCoroutineDispatcher
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TimeSource
private const val BridgeServiceName = "yokanJavaScriptBridge"
private const val BridgeSendMessageFunctionId = "YhSjgGyh"
private const val QuickJsMemoryLimitBytes = 128L * 1024L * 1024L
/**
* The QuickJS stack cap. JVM/Android get 8 MiB (~9,000 recursion levels); iOS needs far more for the
* same depth because zipline's native QuickJS is compiled unoptimized (~22 KiB per JS call).
*/
internal expect val QuickJsMaxStackSizeBytes: Long
// Headroom above the JS cap for the host bridge frames (HTTP, WebView, extractors) that run on top
// of the deepest JS frame, as zipline recommends (6 MiB cap on 8 MiB threads).
private val QuickJsThreadStackBytes = QuickJsMaxStackSizeBytes + 2L * 1024L * 1024L
private val QuickJsEvaluationTimeout = 30.seconds
// Creating and closing a runtime touch process-global state: QuickJS's JS_NewClassID bumps an
// unsynchronized counter during creation, and zipline's leak tracking adds/removes each runtime in
// one unsynchronized map. Evaluation only touches the engine's own runtime, so it runs in parallel.
private val QuickJsGlobalState = Mutex()
/**
* A dedicated thread with a [stackBytes] native stack for one engine. QuickJS measures its stack
* limit from the thread that created the runtime, so every native call of an engine must run on
* that same real thread, and the thread must actually own the stack the limit allows.
*/
internal expect fun quickJsDispatcher(stackBytes: Long): CloseableCoroutineDispatcher
private interface YokanJavaScriptBridge : ZiplineService {
fun sendMessage(channel: String, payload: String): String
}
/**
* QuickJS-backed JavaScript runtime shared by Android, desktop, and iOS.
*
* QuickJS is not thread-safe, so each engine creates its runtime, evaluates, and closes on its own
* [quickJsDispatcher] thread. The explicit [QuickJsMaxStackSizeBytes] cap supports the large
* generated parsers used by Aniyomi ports without leaving it unbounded.
*/
@OptIn(EngineApi::class)
internal class QuickJsJavaScriptEngine(
bridge: JavaScriptMessageBridge,
private val evaluationTimeout: Duration = QuickJsEvaluationTimeout,
) : JavaScriptEngine {
// Host bridge calls (HTTP) block this thread until they return.
private val dispatcher = quickJsDispatcher(QuickJsThreadStackBytes)
private val zipline = try {
runBlocking(dispatcher) {
val runtime = QuickJsGlobalState.withLock { Zipline.create(dispatcher) }
try {
runtime.bind<YokanJavaScriptBridge>(
BridgeServiceName,
object : YokanJavaScriptBridge {
override fun sendMessage(channel: String, payload: String): String =
bridge.sendMessage(channel, payload)
},
)
runtime.quickJs.memoryLimit = QuickJsMemoryLimitBytes
runtime.quickJs.maxStackSize = QuickJsMaxStackSizeBytes
runtime.quickJs.evaluate(BridgeBootstrap, "yokan-bridge.js")
runtime
} catch (error: Throwable) {
QuickJsGlobalState.withLock { runtime.close() }
throw error
}
}
} catch (error: Throwable) {
dispatcher.close()
throw error
}
private val quickJs: QuickJs = zipline.quickJs
private var closed = false
override fun evaluate(script: String, isCancelled: () -> Boolean): String = runBlocking(dispatcher) {
check(!closed) { "JavaScript engine is closed." }
val startedAt = TimeSource.Monotonic.markNow()
quickJs.interruptHandler = InterruptHandler {
isCancelled() || startedAt.elapsedNow() >= evaluationTimeout
}
try {
quickJs.evaluate(script, "yokan-extension.js")?.toString().orEmpty()
} finally {
quickJs.interruptHandler = null
}
}
// Fire-and-forget on the engine's own thread so disposing a runtime never blocks its caller
// (possibly Main); the thread runs it after any in-flight call, then exits.
@OptIn(DelicateCoroutinesApi::class)
override fun close() {
GlobalScope.launch(dispatcher) {
if (closed) return@launch
closed = true
try {
QuickJsGlobalState.withLock { zipline.close() }
} finally {
dispatcher.close()
}
}
}
private companion object {
val BridgeBootstrap =
"""
globalThis.__bridge = {
sendMessage: function(channel, payload) {
var call = JSON.stringify({
service: "$BridgeServiceName",
function: "$BridgeSendMessageFunctionId",
args: [String(channel), String(payload)]
});
var result = JSON.parse(globalThis.app_cash_zipline_outboundChannel.call(call));
if (Object.prototype.hasOwnProperty.call(result, "failure")) {
var failure = result.failure || {};
throw new Error(failure.message || failure.stacktraceString || "Host bridge call failed");
}
return result.success;
}
};
""".trimIndent()
}
}
composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridgeExtraTest.kt
- Source · test / fixture · 39 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
7: class CryptoBridgeExtraTest {
9: fun md5MatchesKnownVectors() {
18: fun hmacSha256MatchesKnownVector() {
28: fun aesCbcPkcs7MatchesKnownVectorAndRoundTrips() {
Exact file bytes / download · SHA-256 9487c0e39555b99c86fe0219c2f8e35aebb8c1c45feea4c362d95fd15aa9a7a6.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CryptoBridgeExtraTest {
@Test
fun md5MatchesKnownVectors() {
assertEquals("d41d8cd98f00b204e9800998ecf8427e", md5("".encodeToByteArray()).toHexString())
assertEquals("900150983cd24fb0d6963f7d28e17f72", md5("abc".encodeToByteArray()).toHexString())
assertEquals("9e107d9d372bb6826bd81d3542a419d6", md5("The quick brown fox jumps over the lazy dog".encodeToByteArray()).toHexString())
assertEquals("f96b697d7cb7938d525a2f31aaf161d0", md5("message digest".encodeToByteArray()).toHexString())
}
@OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)
@Test
fun hmacSha256MatchesKnownVector() {
// RFC 4231 test case 2: key="Jefe", data="what do ya want for nothing?"
val key = "Jefe".encodeToByteArray()
val message = "what do ya want for nothing?".encodeToByteArray()
val payload = "[\"sha-256\",\"" + kotlin.io.encoding.Base64.encode(key) + "\",\"" + kotlin.io.encoding.Base64.encode(message) + "\"]"
val result = CryptoBridge.hmac(payload)
assertTrue(result.contains("5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"), "unexpected hmac: $result")
}
@Test
fun aesCbcPkcs7MatchesKnownVectorAndRoundTrips() {
val encrypted = CryptoBridge.aes(
"""["encrypt","0123456789abcdef0123456789abcdef","00112233445566778899aabbccddeeff","c2VjcmV0LXBheWxvYWQ="]""",
)
assertTrue(encrypted.contains("xp9Jisnku4JnKnk/66AZmA=="), "unexpected AES ciphertext: $encrypted")
val decrypted = CryptoBridge.aes(
"""["decrypt","0123456789abcdef0123456789abcdef","00112233445566778899aabbccddeeff","xp9Jisnku4JnKnk/66AZmA=="]""",
)
assertTrue(decrypted.contains("secret-payload"), "unexpected AES plaintext: $decrypted")
}
}
composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridgeTest.kt
- Source · test / fixture · 51 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
8: class CryptoBridgeTest {
10: fun aesGcmMatchesNistVectors() {
28: fun aesGcmAuthenticatesAdditionalData() {
43: fun aesGcmRejectsModifiedAuthenticationTag() {
Exact file bytes / download · SHA-256 8b1c32fca720dcf21aea1ba64d229d196f0b8605d5065eef9e21f00a7925d7b7.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertNull
class CryptoBridgeTest {
@Test
fun aesGcmMatchesNistVectors() {
val key = ByteArray(16)
val iv = ByteArray(12)
assertEquals(
"58e2fccefa7e3061367f1d57a4e7455a",
aesGcmEncrypt(key, iv, ByteArray(0))?.toHexString(),
)
val encrypted = aesGcmEncrypt(key, iv, ByteArray(16))
assertEquals(
"0388dace60b6a392f328c2b971b2fe78ab6e47d42cec13bdf53a67b21257bddf",
encrypted?.toHexString(),
)
assertContentEquals(ByteArray(16), aesGcmDecrypt(key, iv, encrypted!!))
}
@Test
fun aesGcmAuthenticatesAdditionalData() {
val key = ByteArray(16)
val iv = ByteArray(12)
val additionalData = ByteArray(16)
val encrypted = aesGcmEncrypt(key, iv, ByteArray(16), additionalData)
assertEquals(
"0388dace60b6a392f328c2b971b2fe78d24e503a1bb037071c71b35d987b8657",
encrypted?.toHexString(),
)
assertContentEquals(ByteArray(16), aesGcmDecrypt(key, iv, encrypted!!, additionalData))
assertNull(aesGcmDecrypt(key, iv, encrypted, "wrong".encodeToByteArray()))
}
@Test
fun aesGcmRejectsModifiedAuthenticationTag() {
val key = ByteArray(32) { it.toByte() }
val iv = ByteArray(12) { (it * 3).toByte() }
val encrypted = aesGcmEncrypt(key, iv, "authenticated".encodeToByteArray())!!
encrypted[encrypted.lastIndex] = (encrypted.last().toInt() xor 1).toByte()
assertNull(aesGcmDecrypt(key, iv, encrypted))
}
}
composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/DesCipherTest.kt
- Source · test / fixture · 16 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
6: class DesCipherTest {
9: fun tripleDesCbcPkcs5MatchesKnownVector() {
Exact file bytes / download · SHA-256 95111d604d5a604ea1280fceb5b60adc84a1e517aa1db4f1c896c13cd5974f0a.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
class DesCipherTest {
@OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)
@Test
fun tripleDesCbcPkcs5MatchesKnownVector() {
val key = kotlin.io.encoding.Base64.decode("ASNFZ4mrze8jRWeJq83vAUVniavN7wEj")
val iv = kotlin.io.encoding.Base64.decode("ABEiM0RVZnc=")
val data = kotlin.io.encoding.Base64.decode("c2VjcmV0LXBheWxvYWQ=")
val encrypted = DesCipher.tripleDesCbcEncrypt(key, iv, data)
assertEquals("3IOJq8qqAbmlH/C4r56zuA==", kotlin.io.encoding.Base64.encode(encrypted))
}
}
composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlDomRuntimeTest.kt
- Source · test / fixture · 124 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
12: class HtmlDomRuntimeTest {
13: private fun evalWithDom(script: String): String {
24: fun parsesListingsAttributesAndText() {
47: fun supportsCombinatorsPseudoClassesAndIndexing() {
70: fun decodesEntitiesScriptDataAndBase64() {
95: fun querySelectorHelpersReturnElements() {
107: fun supportsMangayomiCollectionIterationAndAccessors() {
Exact file bytes / download · SHA-256 ebe5d1b6ff2f8ce505addcabe9c131d7eb39948681d9e5c8a16aff7d15f1ca00.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
/**
* Exercises the injected Jsoup-like HTML DOM ([HTML_DOM_JS]) inside the real
* QuickJS runtime, proving element selection, attribute/text extraction, CSS
* combinators/pseudo-classes, `abs:` URL resolution, dual property/method text
* access, and base64 helpers behave correctly on the engine extensions run on.
*/
class HtmlDomRuntimeTest {
private fun evalWithDom(script: String): String {
val engine = QuickJsJavaScriptEngine(bridge = JavaScriptMessageBridge { _, _ -> "null" })
return try {
engine.evaluate(HTML_DOM_JS)
engine.evaluate(script)
} finally {
engine.close()
}
}
@Test
fun parsesListingsAttributesAndText() {
val result = evalWithDom(
"""
var html = '<div class="listupd">' +
'<article class="bs"><a class="tip" href="/anime/naruto"><div class="tt">Naruto</div>' +
'<img data-src="/img/n.jpg"></a></article>' +
'<article class="bs"><a class="tip" href="https://x.tld/anime/bleach"><div class="tt">Bleach</div>' +
'<img data-src="/img/b.jpg"></a></article></div>';
var doc = new Document(html, "https://site.tld/browse/page");
var out = doc.select("div.listupd article a.tip").map(function (a) {
return { name: a.selectFirst("div.tt").text, link: a.attr("href"), img: a.selectFirst("img").attr("abs:data-src") };
});
JSON.stringify(out);
""".trimIndent(),
)
assertEquals(
"[{\"name\":\"Naruto\",\"link\":\"/anime/naruto\",\"img\":\"https://site.tld/img/n.jpg\"}," +
"{\"name\":\"Bleach\",\"link\":\"https://x.tld/anime/bleach\",\"img\":\"https://site.tld/img/b.jpg\"}]",
result,
)
}
@Test
fun supportsCombinatorsPseudoClassesAndIndexing() {
val result = evalWithDom(
"""
var html = '<ul class="eplister"><li><a href="/e/1"><span class="epl-num">EP 1</span></a></li>' +
'<li><a href="/e/2"><span class="epl-num">EP 2</span></a></li></ul>' +
'<div class="pg"><a class="prev" href="#">Prev</a><a class="next" href="/p/2">Next</a></div>' +
'<div class="s"><span>a</span><span>b</span><span>c</span></div>';
var doc = new Document(html);
var eps = doc.select("ul.eplister > li > a").map(function (a) { return a.attr("href") + ":" + a.selectFirst("span.epl-num").text(); });
var next = doc.selectFirst("div.pg a:not(.prev)").text();
var second = doc.select("div.s span:nth-child(2)").first().text();
var last = doc.selectFirst("div.s span:last-child").text();
var count = doc.select("ul.eplister a").size();
JSON.stringify({ eps: eps, next: next, second: second, last: last, count: count });
""".trimIndent(),
)
assertEquals(
"{\"eps\":[\"/e/1:EP 1\",\"/e/2:EP 2\"],\"next\":\"Next\",\"second\":\"b\",\"last\":\"c\",\"count\":2}",
result,
)
}
@Test
fun decodesEntitiesScriptDataAndBase64() {
val result = evalWithDom(
"""
var html = '<div id="d"><p>Hello World & more</p></div>' +
'<script>var config = {"file":"master.m3u8"};</script>' +
'<style>p > b { color: red }</STYLE ><p class="after">tail</p><script>var second = 2;</script>';
var doc = new Document(html);
var text = doc.selectFirst("#d p").text;
var scriptHasFile = String(doc.selectFirst("script").data()).indexOf("master.m3u8") !== -1;
var style = doc.selectFirst("style").data();
var after = doc.selectFirst("p.after").text();
var scripts = doc.select("script").size();
var round = atob(btoa("hello-world"));
var typeofText = typeof doc.selectFirst("#d p").text;
JSON.stringify({ text: text, scriptHasFile: scriptHasFile, style: style, after: after, scripts: scripts, round: round, typeofText: typeofText });
""".trimIndent(),
)
assertEquals(
"{\"text\":\"Hello World & more\",\"scriptHasFile\":true,\"style\":\"p > b { color: red }\",\"after\":\"tail\"," +
"\"scripts\":2,\"round\":\"hello-world\",\"typeofText\":\"function\"}",
result,
)
}
@Test
fun querySelectorHelpersReturnElements() {
val result = evalWithDom(
"""
var html = '<a href="x" data-em="e1">M1</a><a href="y" data-em="e2">M2</a>';
var all = querySelectorAll(html, "a[data-em]").map(function (a) { return a.attr("data-em"); });
var one = querySelector(html, "a[data-em]").text();
JSON.stringify({ all: all, one: one });
""".trimIndent(),
)
assertEquals("{\"all\":[\"e1\",\"e2\"],\"one\":\"M1\"}", result)
}
@Test
fun supportsMangayomiCollectionIterationAndAccessors() {
val result = evalWithDom(
"""
var doc = new Document('<div><a href="/one"><img src="/1.jpg"></a><a href="/two"><img src="/2.jpg"></a></div>');
var links = [];
for (var anchor of doc.select("a")) {
links.push({ href: anchor.getHref, src: anchor.selectFirst("img").getSrc });
}
JSON.stringify(links);
""".trimIndent(),
)
assertEquals(
"[{\"href\":\"/one\",\"src\":\"/1.jpg\"},{\"href\":\"/two\",\"src\":\"/2.jpg\"}]",
result,
)
}
}
composeApp/src/nonWebTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/QuickJsJavaScriptEngineTest.kt
- Source · test / fixture · 98 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
15: class QuickJsJavaScriptEngineTest {
17: fun evaluatesModernJavaScriptAndCallsHostBridge() {
29: class Result { constructor(value) { this.value = value; } }
44: fun interruptsRunawayJavaScript() {
59: fun deepRecursionRunsAndRunawayRecursionFailsCleanly() = runBlocking(blockingDispatcher) {
75: fun enginesEvaluateWhileAnotherWaitsOnItsHostBridge() = runBlocking {
Exact file bytes / download · SHA-256 a96646d7eef7c05c0a5aed5920c3c2b83982313d3cf03f38da073dc87018ab0d.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import eu.friedcutlet.yokan.services.blockingDispatcher
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertTrue
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
class QuickJsJavaScriptEngineTest {
@Test
fun evaluatesModernJavaScriptAndCallsHostBridge() {
val calls = mutableListOf<Pair<String, String>>()
val engine = QuickJsJavaScriptEngine(
bridge = JavaScriptMessageBridge { channel, payload ->
calls += channel to payload
"host-result"
},
)
try {
val result = engine.evaluate(
"""
class Result { constructor(value) { this.value = value; } }
const values = [1, 2, 3].map(value => value * 2);
const host = __bridge.sendMessage("test", JSON.stringify(values));
`${'$'}{new Result(values[values.length - 1]).value}:${'$'}{host}`;
""".trimIndent(),
)
assertEquals("6:host-result", result)
assertEquals(listOf("test" to "[2,4,6]"), calls)
} finally {
engine.close()
}
}
@Test
fun interruptsRunawayJavaScript() {
val engine = QuickJsJavaScriptEngine(
bridge = JavaScriptMessageBridge { _, _ -> "null" },
evaluationTimeout = 10.milliseconds,
)
try {
val failure = assertFails { engine.evaluate("while (true) {}") }
assertTrue(failure.message.orEmpty().contains("interrupt", ignoreCase = true))
} finally {
engine.close()
}
}
@Test
fun deepRecursionRunsAndRunawayRecursionFailsCleanly() = runBlocking(blockingDispatcher) {
// Called from a pool thread: the engine's own thread must own the stack its JS cap allows,
// otherwise deep recursion overruns the native stack and kills the process.
val engine = QuickJsJavaScriptEngine(bridge = JavaScriptMessageBridge { _, _ -> "null" })
try {
assertEquals("5000", engine.evaluate("function f(n) { return n === 0 ? 0 : 1 + f(n - 1); } f(5000)"))
val failure = assertFails { engine.evaluate("function g() { return 1 + g(); } g()") }
assertTrue(failure.message.orEmpty().contains("stack overflow", ignoreCase = true))
assertEquals("2", engine.evaluate("1 + 1"))
} finally {
engine.close()
}
}
@Test
fun enginesEvaluateWhileAnotherWaitsOnItsHostBridge() = runBlocking {
val entered = CompletableDeferred<Unit>()
val released = CompletableDeferred<Unit>()
val waiting = QuickJsJavaScriptEngine(
bridge = JavaScriptMessageBridge { _, _ ->
entered.complete(Unit)
// Bounded, so a regression to one engine at a time fails instead of hanging.
runBlocking { withTimeoutOrNull(5.seconds) { released.await() } }?.let { "released" } ?: "timed out"
},
)
val other = QuickJsJavaScriptEngine(bridge = JavaScriptMessageBridge { _, _ -> "null" })
try {
val slowCall = async(blockingDispatcher) { waiting.evaluate("__bridge.sendMessage('wait', '')") }
entered.await()
assertEquals("2", other.evaluate("1 + 1"))
released.complete(Unit)
assertEquals("released", slowCall.await())
} finally {
waiting.close()
other.close()
}
}
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/GzipDecompress.wasm.kt
- Source · implementation · 65 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
15: internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray =
30: private fun gzipDecompressJs(base64: String, maxOutputBytes: Int): Promise<JsAny> = js(
65: private fun jsString(value: JsAny): String = js("String(value)")
Exact file bytes / download · SHA-256 cecd8a4ccaf1d5109e4e75c7cd00590a24f0fa43369b854e434b33001fe841fe.
Complete file
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)
package eu.friedcutlet.yokan.services.extensions
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi
import kotlin.js.JsAny
import kotlin.js.Promise
import kotlin.js.js
@OptIn(ExperimentalEncodingApi::class)
internal actual suspend fun gzipDecompress(bytes: ByteArray): ByteArray =
suspendCancellableCoroutine { continuation ->
gzipDecompressJs(Base64.encode(bytes), MaxProtobufDecompressedBytes).then(
onFulfilled = { value ->
runCatching { Base64.decode(jsString(value)) }
.fold(continuation::resume, continuation::resumeWithException)
null
},
onRejected = { error ->
continuation.resumeWithException(IllegalStateException(jsString(error)))
null
},
)
}
private fun gzipDecompressJs(base64: String, maxOutputBytes: Int): Promise<JsAny> = js(
"""
(async () => {
const binary = atob(base64);
const input = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) input[i] = binary.charCodeAt(i);
const stream = new Blob([input]).stream().pipeThrough(new DecompressionStream('gzip'));
const reader = stream.getReader();
const chunks = [];
let outputLength = 0;
while (true) {
const result = await reader.read();
if (result.done) break;
outputLength += result.value.byteLength;
if (outputLength > maxOutputBytes) {
await reader.cancel();
throw new Error('decompressed protobuf exceeds the 64 MiB limit');
}
chunks.push(result.value);
}
const bytes = new Uint8Array(outputLength);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
let result = '';
for (let i = 0; i < bytes.length; i += 0x8000) {
result += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
}
return btoa(result);
})()
""",
)
private fun jsString(value: JsAny): String = js("String(value)")
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridge.wasm.kt
- Source · implementation · 12 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
8: actual fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? = null
10: actual fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? = null
12: actual fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? = null
Exact file bytes / download · SHA-256 3f12919f3c556573cbf5a92533e6ff2d32fa2b8941bf0150490d92c0cc3da658.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
// ponytail: WebCrypto (the only browser crypto, also what cryptography-kotlin wraps on wasm) is
// async-only, so these synchronous JS-bridge functions cannot use it: AES returns null and the
// digests are pure Kotlin. Upgrade path: a suspending/async crypto bridge for extensions.
// AES is only used by anime-extractor deobfuscation paths; callers treat null
// as "cipher unavailable" and fall back.
actual fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? = null
actual fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? = null
actual fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? = null
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/JavaScriptEngine.wasm.kt
- Source · implementation · 20 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: actual fun createJavaScriptEngine(bridge: JavaScriptMessageBridge): JavaScriptEngine =
15: private object UnsupportedJavaScriptEngine : JavaScriptEngine {
16: override fun evaluate(script: String, isCancelled: () -> Boolean): String =
19: override fun close() = Unit
Exact file bytes / download · SHA-256 8bf043304da5a7e76252a99e573b2a141590b5cbb66ae7f28b6a40f76369c83d.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
/**
* Extension sources need a synchronous QuickJS bridge; zipline has no wasm
* artifact, so JavaScript-based extensions are unavailable in the browser.
* Every call fails with a clear [UnsupportedOperationException] instead of
* returning empty results.
*/
// ponytail: evaluating in the page's own JS engine would not help either: the host HTTP bridge is
// synchronous and the browser cannot block on fetch. Upgrade path: promise-returning host calls
// awaited by an async (suspend) engine API.
actual fun createJavaScriptEngine(bridge: JavaScriptMessageBridge): JavaScriptEngine =
UnsupportedJavaScriptEngine
private object UnsupportedJavaScriptEngine : JavaScriptEngine {
override fun evaluate(script: String, isCancelled: () -> Boolean): String =
throw UnsupportedOperationException("JavaScript extensions are not supported in the browser.")
override fun close() = Unit
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerAdapter.wasm.kt
- Source · implementation · 44 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
12: internal actual fun createPlatformExtensionServerAdapter(profileId: eu.friedcutlet.yokan.domain.ProfileId): PlatformExtensionServerAdapter =
17: private fun unsupported(): Nothing =
20: private object WasmExtensionServerAdapter : PlatformExtensionServerAdapter {
27: override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? = null
29: override suspend fun install(
34: override suspend fun detect(path: String): InstalledExtensionServerBundle = unsupported()
37: private object UnsupportedExtensionServer : ExtensionServer {
41: override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = unsupported()
43: override suspend fun stop(): ExtensionServerStatus = ExtensionServerStatus.Stopped
Exact file bytes / download · SHA-256 10bb5ae6d39dfb9f559378709ef281948880babc89cd642f1ad8bf9f4ffdc660.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
import eu.friedcutlet.yokan.ext.ExtensionServer
import eu.friedcutlet.yokan.ext.ExtensionServerConfig
import eu.friedcutlet.yokan.ext.ExtensionServerException
import eu.friedcutlet.yokan.ext.ExtensionServerRelease
import eu.friedcutlet.yokan.ext.ExtensionServerStatus
import eu.friedcutlet.yokan.ext.InstalledExtensionServerBundle
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
internal actual fun createPlatformExtensionServerAdapter(profileId: eu.friedcutlet.yokan.domain.ProfileId): PlatformExtensionServerAdapter =
WasmExtensionServerAdapter
internal actual val defaultMihonProxyUrl: String = "http://127.0.0.1:8080"
private fun unsupported(): Nothing =
throw ExtensionServerException("unsupported", "The local extension server cannot run in the browser.")
private object WasmExtensionServerAdapter : PlatformExtensionServerAdapter {
override val mode = ExtensionServerRuntimeMode.Unsupported
override val requiresBundleDownload = false
override val installationAvailable = false
override val supportsRemoteBaseUrl = true
override val server: ExtensionServer = UnsupportedExtensionServer
override fun resolveConfig(port: Int, jvmPath: String, serverJarPath: String): ExtensionServerConfig? = null
override suspend fun install(
release: ExtensionServerRelease,
onProgress: (downloadedBytes: Long, totalBytes: Long) -> Unit,
): InstalledExtensionServerBundle = unsupported()
override suspend fun detect(path: String): InstalledExtensionServerBundle = unsupported()
}
private object UnsupportedExtensionServer : ExtensionServer {
override val status: StateFlow<ExtensionServerStatus> =
MutableStateFlow(ExtensionServerStatus.Stopped)
override suspend fun start(config: ExtensionServerConfig): ExtensionServerStatus = unsupported()
override suspend fun stop(): ExtensionServerStatus = ExtensionServerStatus.Stopped
}
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/ExtensionServerPorts.wasm.kt
- Source · implementation · 4 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.
Declaration checklist (source line numbers):
4: internal actual fun findAvailableExtensionServerPort(preferred: Int): Int = preferred
Exact file bytes / download · SHA-256 2e3b6c72f0a2ac5517fde44bd27fb0d07bc2a30b44da271356cd312e380371dc.
Complete file
package eu.friedcutlet.yokan.services.extensions.mihon
// The browser cannot bind sockets; the configured (remote) port is used as-is.
internal actual fun findAvailableExtensionServerPort(preferred: Int): Int = preferred
composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridgeWasmTest.kt
- Source · test / fixture · 32 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.
Declaration checklist (source line numbers):
9: class CryptoBridgeWasmTest {
11: fun hashesMatchStandardAbcVectors() {
28: fun aesGcmIsUnsupported() {
Exact file bytes / download · SHA-256 fbd617e71c4a72348ecf693c3ebcb339b69420e90705f4994e5c9031d20e5a1d.
Complete file
package eu.friedcutlet.yokan.services.extensions.js
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import eu.friedcutlet.yokan.util.sha256
import eu.friedcutlet.yokan.util.sha1
class CryptoBridgeWasmTest {
@Test
fun hashesMatchStandardAbcVectors() {
val input = "abc".encodeToByteArray()
assertEquals(
"a9993e364706816aba3e25717850c26c9cd0d89d",
sha1(input).toHexString(),
)
assertEquals(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
sha256(input).toHexString(),
)
}
// The browser only exposes AES through the async WebCrypto API, so the synchronous
// bridge is deliberately unavailable here (CryptoBridge.wasm.kt). Callers rely on the
// null return rather than a thrown error; the real vectors are covered in nonWebTest.
@Test
fun aesGcmIsUnsupported() {
assertNull(aesGcmEncrypt(ByteArray(16), ByteArray(12), ByteArray(0)))
assertNull(aesGcmDecrypt(ByteArray(16), ByteArray(12), ByteArray(32)))
}
}