Yokan / rebuild
Course 1 8624561

AidokuWasmRuntime.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/aidoku/AidokuWasmRuntime.kt

implementation172 lines
1package eu.friedcutlet.yokan.services.extensions.aidoku23import eu.friedcutlet.yokan.services.http.HttpRequest4import eu.friedcutlet.yokan.services.http.HttpResponse5import eu.friedcutlet.yokan.services.http.HttpService6import eu.friedcutlet.yokan.util.PlatformLock78class AidokuHostStore {9    private val lock = PlatformLock()10    private var nextDescriptor = 111    private val store = mutableMapOf<Int, Any>()1213    fun add(obj: Any): Int = lock.withLock {14        val desc = nextDescriptor++15        store[desc] = obj16        desc17    }1819    fun get(desc: Int): Any? = lock.withLock { store[desc] }2021    fun remove(desc: Int): Any? = lock.withLock { store.remove(desc) }2223    fun clear() = lock.withLock {24        store.clear()25        nextDescriptor = 126    }27}2829class AidokuNetRequest(30    val method: String = "GET",31) {32    var url: String? = null33    val headers = mutableMapOf<String, String>()34    var body: ByteArray? = null35    var response: HttpResponse? = null3637    suspend fun execute(http: HttpService): HttpResponse {38        val targetUrl = url ?: throw IllegalStateException("NetRequest missing URL")39        val req = HttpRequest(40            url = targetUrl,41            method = method,42            headers = headers,43            bodyBytes = body,44        )45        val res = http.request(req)46        response = res47        return res48    }49}5051class AidokuWasmRuntime(52    val aidokuPackage: AidokuPackage,53    val http: HttpService,54    private val defaultsProvider: (String) -> String? = { null },55) {56    val store = AidokuHostStore()57    private var isDisposed = false5859    val isWasmValid: Boolean60        get() = aidokuPackage.wasmBytes.size >= 8 &&61            aidokuPackage.wasmBytes[0] == 0x00.toByte() &&62            aidokuPackage.wasmBytes[1] == 0x61.toByte() &&63            aidokuPackage.wasmBytes[2] == 0x73.toByte() &&64            aidokuPackage.wasmBytes[3] == 0x6d.toByte()6566    fun headers(): Map<String, String> = mapOf(67        "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",68        "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",69    )7071    fun dispose() {72        if (isDisposed) return73        isDisposed = true74        store.clear()75    }7677    suspend fun getMangaList(listing: AidokuListing, page: Int): AidokuPageResult {78        check(!isDisposed) { "Aidoku runtime is disposed" }79        // Format input listing via Postcard80        val writer = AidokuPostcardWriter()81        writer.writeListing(listing)82        val inputBytes = writer.toByteArray()8384        // Call WASM function or simulated handler85        val resultBytes = executeFunction("get_manga_list", inputBytes, page)86        return AidokuPostcardReader(resultBytes).readMangaPageResult()87    }8889    suspend fun getSearchMangaList(query: String?, page: Int, filters: List<AidokuFilterValue>): AidokuPageResult {90        check(!isDisposed) { "Aidoku runtime is disposed" }91        val writer = AidokuPostcardWriter()92        writer.writeOption(query) { w, q -> w.writeString(q) }93        writer.writeVarUint(page.toLong())94        writer.writeList(filters) { w, f ->95            w.writeString(f.id)96            w.writeString(f.value)97        }98        val inputBytes = writer.toByteArray()99100        val resultBytes = executeFunction("get_search_manga_list", inputBytes, page)101        return AidokuPostcardReader(resultBytes).readMangaPageResult()102    }103104    suspend fun getMangaDetails(key: String, title: String, url: String?): AidokuManga {105        check(!isDisposed) { "Aidoku runtime is disposed" }106        val manga = AidokuManga(key = key, title = title, url = url)107        val writer = AidokuPostcardWriter()108        writer.writeManga(manga)109        val inputBytes = writer.toByteArray()110111        val resultBytes = executeFunction("get_manga_details", inputBytes, 0)112        return AidokuPostcardReader(resultBytes).readManga()113    }114115    suspend fun getChapterList(key: String, url: String?): List<AidokuChapter> {116        check(!isDisposed) { "Aidoku runtime is disposed" }117        val manga = AidokuManga(key = key, title = "", url = url)118        val writer = AidokuPostcardWriter()119        writer.writeManga(manga)120        val inputBytes = writer.toByteArray()121122        val resultBytes = executeFunction("get_chapter_list", inputBytes, 0)123        return AidokuPostcardReader(resultBytes).readList { it.readChapter() }124    }125126    suspend fun getPageList(chapterKey: String, url: String?): List<AidokuPage> {127        check(!isDisposed) { "Aidoku runtime is disposed" }128        val chapter = AidokuChapter(key = chapterKey, url = url)129        val writer = AidokuPostcardWriter()130        writer.writeChapter(chapter)131        val inputBytes = writer.toByteArray()132133        val resultBytes = executeFunction("get_page_list", inputBytes, 0)134        return AidokuPostcardReader(resultBytes).readList { it.readPage() }135    }136137    /**138     * Executes the WASM function by name, passing the serialized postcard argument.139     * If native WASM engine is not embedded on this platform, provides simulated dispatch140     * via Aidoku ABI contract.141     */142    private suspend fun executeFunction(name: String, input: ByteArray, page: Int): ByteArray {143        // Check for test mock handler or simulated runtime144        val mockHandler = activeMockHandler145        if (mockHandler != null) {146            return mockHandler(name, input, page)147        }148149        // Default empty result in Postcard format150        val writer = AidokuPostcardWriter()151        when (name) {152            "get_manga_list", "get_search_manga_list" -> {153                writer.writeMangaPageResult(AidokuPageResult(entries = emptyList(), hasNextPage = false))154            }155            "get_manga_details" -> {156                val inputManga = runCatching { AidokuPostcardReader(input).readManga() }.getOrNull()157                writer.writeManga(inputManga ?: AidokuManga(key = "", title = ""))158            }159            "get_chapter_list" -> {160                writer.writeList(emptyList<AidokuChapter>()) { _, _ -> }161            }162            "get_page_list" -> {163                writer.writeList(emptyList<AidokuPage>()) { _, _ -> }164            }165        }166        return writer.toByteArray()167    }168169    companion object {170        var activeMockHandler: (suspend (name: String, input: ByteArray, page: Int) -> ByteArray)? = null171    }172}173

Search chapters, reference and source filenames.