package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.AndroidAppContext import android.os.Handler import android.os.Looper import android.webkit.WebView import android.webkit.WebViewClient import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.http.EnhancedHttpService import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.system.openSystemBrowser import kotlin.coroutines.resume import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.withContext import kotlinx.coroutines.suspendCancellableCoroutine internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService = AndroidWebViewService(http, cookieJar) /** * Headless WebView wrapper. Loads `url`, waits for `onPageFinished`, then evaluates `script` and * resolves with the WebView's returned value (Android quotes string results via `JSON.stringify`; * callers that need a structured value can wrap their script in `JSON.stringify(...)`). * * After every headless load (and on demand via [syncCookies]) we forward the * platform's `CookieManager` cookies for the URL's host into the shared * [CookieJar], so logging in via the in-app WebView (or any redirect chain * that mutates cookies during the headless flow) survives across restarts and * is automatically attached to subsequent `HttpService` requests. */ private class AndroidWebViewService( private val http: HttpService, private val cookieJar: CookieJar, ) : WebViewService { override suspend fun open(request: WebViewRequest): Boolean { if (request.url.isBlank()) return false return openSystemBrowser(request.url) } /** * Mangayomi's `m_client` policy: run a headless WebView on the challenge * URL until Cloudflare issues `cf_clearance` (or a timeout elapses), * harvest the cookies into the shared jar, then retry the request with * the fresh cookies. The retry carries the caller's skip-marker header so * [EnhancedHttpService] doesn't recurse back into this solver. */ override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? { if (request.url.isBlank()) return null val freshCookies = catchingNonCancellation { solveChallenge(request.url, request.headers) } .getOrNull() ?.takeIf { it.isNotBlank() } ?: return null val headers = request.headers.toMutableMap() headers["Cookie"] = freshCookies return http.request(HttpRequest(url = request.url, headers = headers)) } private suspend fun solveChallenge(url: String, headers: Map): String? { val context = AndroidAppContext.appContext ?: return null return withContext(Dispatchers.Main.immediate) { if (!cookieJar.canUseBrowserStorage) return@withContext null val handler = Handler(Looper.getMainLooper()) val webView = newProfileWebView(context, cookieJar.profileId) var poll: Runnable? = null try { webView.settings.apply { javaScriptEnabled = true domStorageEnabled = true useWideViewPort = true loadWithOverviewMode = false headers.entries .firstOrNull { it.key.equals("User-Agent", ignoreCase = true) } ?.value ?.takeIf { it.isNotBlank() } ?.let { userAgentString = it } } val cookieManager = profileCookieManager(cookieJar.profileId) cookieManager.setAcceptCookie(true) cookieManager.setAcceptThirdPartyCookies(webView, true) suspendCancellableCoroutine { continuation -> var finished = false var pageFinished = false fun finish(cookies: String?) { if (finished || !continuation.isActive) return finished = true harvestCookies(url) continuation.resume(cookies) } var waitedMs = 0L lateinit var polling: Runnable polling = Runnable { if (finished || !continuation.isActive || !cookieJar.canUseBrowserStorage) return@Runnable val cookies = runCatching { cookieManager.getCookie(url) }.getOrNull().orEmpty() when { "cf_clearance" in cookies && pageFinished -> finish(cookies) waitedMs >= CHALLENGE_TIMEOUT_MS -> { val names = cookies.split(';').map { it.substringBefore('=').trim() }.filter { it.isNotEmpty() } AppLogger.warn("[net] Cloudflare WebView timeout for $url title='${webView.title.orEmpty()}' cookies=$names") finish(null) } else -> { waitedMs += CHALLENGE_POLL_MS handler.postDelayed(polling, CHALLENGE_POLL_MS) } } } poll = polling webView.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView, finishedUrl: String) { if (finished || !continuation.isActive || !cookieJar.canUseBrowserStorage) return pageFinished = true harvestCookies(finishedUrl) } } val requestHeaders = headers.filterKeys { !it.equals(CLOUDFLARE_SKIP_HEADER, ignoreCase = true) } webView.loadUrl(url, requestHeaders) handler.postDelayed(polling, CHALLENGE_POLL_MS) } } finally { // Await main-thread cleanup; cancellation must not leave a queued destroy behind. withContext(NonCancellable + Dispatchers.Main.immediate) { poll?.let(handler::removeCallbacks) try { webView.stopLoading() } finally { webView.destroy() } } } } } override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String { val context = AndroidAppContext.appContext ?: return "" return withContext(Dispatchers.Main.immediate) { if (!cookieJar.canUseBrowserStorage) return@withContext "" val webView = newProfileWebView(context, cookieJar.profileId) try { configureAndroidWebView(webView, cookieJar.profileId, userAgent) suspendCancellableCoroutine { continuation -> var done = false fun finish(value: String) { if (done || !continuation.isActive) return done = true continuation.resume(value) } webView.webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView, finishedUrl: String) { if (done || !continuation.isActive || !cookieJar.canUseBrowserStorage) return harvestCookies(finishedUrl) view.evaluateJavascript(script) { value -> finish(value?.trim('"') ?: "") } } } webView.loadUrl(url) } } finally { withContext(NonCancellable + Dispatchers.Main.immediate) { try { webView.stopLoading() } finally { webView.destroy() } } } } } // ProfileStore (extra profiles' cookie stores) is main-thread only. override suspend fun syncCookies(url: String): String? = withContext(Dispatchers.Main.immediate) { harvestCookies(url) } private fun harvestCookies(url: String): String? { if (url.isBlank() || !cookieJar.canUseBrowserStorage) return null val cookieManager = profileCookieManager(cookieJar.profileId) val cookieString = runCatching { cookieManager.getCookie(url) } .getOrNull()?.takeIf { it.isNotBlank() } ?: return null if (!cookieJar.canUseBrowserStorage) return null val secure = if (url.startsWith("https://", ignoreCase = true)) "; Secure" else "" val setCookies = cookieString.split(';').mapNotNull { pair -> pair.trim().takeIf { it.substringBefore('=').isNotBlank() }?.let { "$it; Path=/$secure" } } cookieJar.setFromResponse(url, setCookies) // Persist immediately so a process death after login doesn't drop the // session (CookieManager normally batches writes). runCatching { cookieManager.flush() } return cookieString } } private const val CHALLENGE_POLL_MS = 500L private const val CHALLENGE_TIMEOUT_MS = 30_000L private const val CLOUDFLARE_SKIP_HEADER = "X-Yokan-Skip-Cloudflare"