Yokan / rebuild
Course 1 8624561

WebViewService.android.kt

composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.android.kt

implementation192 lines
1package eu.friedcutlet.yokan.services.webview23import eu.friedcutlet.yokan.AndroidAppContext4import android.os.Handler5import android.os.Looper6import android.webkit.WebView7import android.webkit.WebViewClient8import eu.friedcutlet.yokan.services.catchingNonCancellation9import eu.friedcutlet.yokan.services.logging.AppLogger10import eu.friedcutlet.yokan.services.http.EnhancedHttpService11import eu.friedcutlet.yokan.services.http.HttpRequest12import eu.friedcutlet.yokan.services.http.HttpResponse13import eu.friedcutlet.yokan.services.files.LocalFileService14import eu.friedcutlet.yokan.services.http.HttpService15import eu.friedcutlet.yokan.services.http.cookies.CookieJar16import eu.friedcutlet.yokan.services.system.openSystemBrowser17import kotlin.coroutines.resume18import kotlinx.coroutines.Dispatchers19import kotlinx.coroutines.NonCancellable20import kotlinx.coroutines.withContext21import kotlinx.coroutines.suspendCancellableCoroutine2223internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService =24    AndroidWebViewService(http, cookieJar)2526/**27 * Headless WebView wrapper. Loads `url`, waits for `onPageFinished`, then evaluates `script` and28 * resolves with the WebView's returned value (Android quotes string results via `JSON.stringify`;29 * callers that need a structured value can wrap their script in `JSON.stringify(...)`).30 *31 * After every headless load (and on demand via [syncCookies]) we forward the32 * platform's `CookieManager` cookies for the URL's host into the shared33 * [CookieJar], so logging in via the in-app WebView (or any redirect chain34 * that mutates cookies during the headless flow) survives across restarts and35 * is automatically attached to subsequent `HttpService` requests.36 */37private class AndroidWebViewService(38    private val http: HttpService,39    private val cookieJar: CookieJar,40) : WebViewService {41    override suspend fun open(request: WebViewRequest): Boolean {42        if (request.url.isBlank()) return false43        return openSystemBrowser(request.url)44    }4546    /**47     * Mangayomi's `m_client` policy: run a headless WebView on the challenge48     * URL until Cloudflare issues `cf_clearance` (or a timeout elapses),49     * harvest the cookies into the shared jar, then retry the request with50     * the fresh cookies. The retry carries the caller's skip-marker header so51     * [EnhancedHttpService] doesn't recurse back into this solver.52     */53    override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? {54        if (request.url.isBlank()) return null55        val freshCookies = catchingNonCancellation { solveChallenge(request.url, request.headers) }56            .getOrNull()57            ?.takeIf { it.isNotBlank() }58            ?: return null59        val headers = request.headers.toMutableMap()60        headers["Cookie"] = freshCookies61        return http.request(HttpRequest(url = request.url, headers = headers))62    }6364    private suspend fun solveChallenge(url: String, headers: Map<String, String>): String? {65        val context = AndroidAppContext.appContext ?: return null66        return withContext(Dispatchers.Main.immediate) {67            if (!cookieJar.canUseBrowserStorage) return@withContext null68            val handler = Handler(Looper.getMainLooper())69            val webView = newProfileWebView(context, cookieJar.profileId)70            var poll: Runnable? = null71            try {72                webView.settings.apply {73                    javaScriptEnabled = true74                    domStorageEnabled = true75                    useWideViewPort = true76                    loadWithOverviewMode = false77                    headers.entries78                        .firstOrNull { it.key.equals("User-Agent", ignoreCase = true) }79                        ?.value80                        ?.takeIf { it.isNotBlank() }81                        ?.let { userAgentString = it }82                }83                val cookieManager = profileCookieManager(cookieJar.profileId)84                cookieManager.setAcceptCookie(true)85                cookieManager.setAcceptThirdPartyCookies(webView, true)86                suspendCancellableCoroutine { continuation ->87                    var finished = false88                    var pageFinished = false89                    fun finish(cookies: String?) {90                        if (finished || !continuation.isActive) return91                        finished = true92                        harvestCookies(url)93                        continuation.resume(cookies)94                    }95                    var waitedMs = 0L96                    lateinit var polling: Runnable97                    polling = Runnable {98                        if (finished || !continuation.isActive || !cookieJar.canUseBrowserStorage) return@Runnable99                        val cookies = runCatching { cookieManager.getCookie(url) }.getOrNull().orEmpty()100                        when {101                            "cf_clearance" in cookies && pageFinished -> finish(cookies)102                            waitedMs >= CHALLENGE_TIMEOUT_MS -> {103                                val names = cookies.split(';').map { it.substringBefore('=').trim() }.filter { it.isNotEmpty() }104                                AppLogger.warn("[net] Cloudflare WebView timeout for $url title='${webView.title.orEmpty()}' cookies=$names")105                                finish(null)106                            }107                            else -> {108                                waitedMs += CHALLENGE_POLL_MS109                                handler.postDelayed(polling, CHALLENGE_POLL_MS)110                            }111                        }112                    }113                    poll = polling114                    webView.webViewClient = object : WebViewClient() {115                        override fun onPageFinished(view: WebView, finishedUrl: String) {116                            if (finished || !continuation.isActive || !cookieJar.canUseBrowserStorage) return117                            pageFinished = true118                            harvestCookies(finishedUrl)119                        }120                    }121                    val requestHeaders = headers.filterKeys { !it.equals(CLOUDFLARE_SKIP_HEADER, ignoreCase = true) }122                    webView.loadUrl(url, requestHeaders)123                    handler.postDelayed(polling, CHALLENGE_POLL_MS)124                }125            } finally {126                // Await main-thread cleanup; cancellation must not leave a queued destroy behind.127                withContext(NonCancellable + Dispatchers.Main.immediate) {128                    poll?.let(handler::removeCallbacks)129                    try { webView.stopLoading() } finally { webView.destroy() }130                }131            }132        }133    }134135    override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String {136        val context = AndroidAppContext.appContext ?: return ""137        return withContext(Dispatchers.Main.immediate) {138            if (!cookieJar.canUseBrowserStorage) return@withContext ""139            val webView = newProfileWebView(context, cookieJar.profileId)140            try {141                configureAndroidWebView(webView, cookieJar.profileId, userAgent)142                suspendCancellableCoroutine { continuation ->143                    var done = false144                    fun finish(value: String) {145                        if (done || !continuation.isActive) return146                        done = true147                        continuation.resume(value)148                    }149                    webView.webViewClient = object : WebViewClient() {150                        override fun onPageFinished(view: WebView, finishedUrl: String) {151                            if (done || !continuation.isActive || !cookieJar.canUseBrowserStorage) return152                            harvestCookies(finishedUrl)153                            view.evaluateJavascript(script) { value -> finish(value?.trim('"') ?: "") }154                        }155                    }156                    webView.loadUrl(url)157                }158            } finally {159                withContext(NonCancellable + Dispatchers.Main.immediate) {160                    try { webView.stopLoading() } finally { webView.destroy() }161                }162            }163        }164    }165166    // ProfileStore (extra profiles' cookie stores) is main-thread only.167    override suspend fun syncCookies(url: String): String? = withContext(Dispatchers.Main.immediate) { harvestCookies(url) }168169    private fun harvestCookies(url: String): String? {170        if (url.isBlank() || !cookieJar.canUseBrowserStorage) return null171        val cookieManager = profileCookieManager(cookieJar.profileId)172        val cookieString = runCatching { cookieManager.getCookie(url) }173            .getOrNull()?.takeIf { it.isNotBlank() }174            ?: return null175        if (!cookieJar.canUseBrowserStorage) return null176        val secure = if (url.startsWith("https://", ignoreCase = true)) "; Secure" else ""177        val setCookies = cookieString.split(';').mapNotNull { pair ->178            pair.trim().takeIf { it.substringBefore('=').isNotBlank() }?.let { "$it; Path=/$secure" }179        }180        cookieJar.setFromResponse(url, setCookies)181        // Persist immediately so a process death after login doesn't drop the182        // session (CookieManager normally batches writes).183        runCatching { cookieManager.flush() }184        return cookieString185    }186187}188189private const val CHALLENGE_POLL_MS = 500L190private const val CHALLENGE_TIMEOUT_MS = 30_000L191192private const val CLOUDFLARE_SKIP_HEADER = "X-Yokan-Skip-Cloudflare"193

Search chapters, reference and source filenames.