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 = 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 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): 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 = 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, ) }