package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.services.catchingNonCancellation 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.http.isCloudflareChallengePageTitle import eu.friedcutlet.yokan.services.system.openSystemBrowser import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import platform.CoreGraphics.CGRectMake import platform.Foundation.NSURL import platform.Foundation.NSURLRequest import platform.WebKit.WKWebView import platform.WebKit.WKWebViewConfiguration internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService = IosWebViewService(http, cookieJar) /** * iOS [WebViewService] backed by a headless [WKWebView] and the profile's * `WKWebsiteDataStore` ([profileDataStore]). Challenge and in-app browsing cookies are harvested * into [CookieJar], then attached to the retry performed by [HttpService]. */ private class IosWebViewService( 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 on iOS: drive a headless `WKWebView` on * the challenge URL until `cf_clearance` lands in the shared * `WKWebsiteDataStore` (or a timeout elapses), harvest cookies into the * jar, then retry over HTTP. The retry keeps the caller's skip-marker * header so [EnhancedHttpService] doesn't recurse back into the solver. */ override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? { if (request.url.isBlank()) return null val userAgent = request.headers.entries .firstOrNull { it.key.equals("User-Agent", ignoreCase = true) } ?.value catchingNonCancellation { solveChallenge(request.url, userAgent) } syncCookies(request.url) val headers = request.headers.toMutableMap() cookieJar.cookieHeader(request.url)?.let { headers["Cookie"] = it } return http.request(HttpRequest(url = request.url, headers = headers)) } @OptIn(ExperimentalForeignApi::class) private suspend fun solveChallenge(url: String, userAgent: String?): Boolean { val nsUrl = NSURL.URLWithString(url) ?: return false val host = nsUrl.host?.lowercase() ?: return false val webView = withContext(Dispatchers.Main) { val configuration = WKWebViewConfiguration().apply { websiteDataStore = profileDataStore(cookieJar.profileId) } WKWebView(frame = CGRectMake(0.0, 0.0, 1024.0, 768.0), configuration = configuration).also { view -> if (!userAgent.isNullOrBlank()) view.customUserAgent = userAgent view.loadRequest(NSURLRequest.requestWithURL(nsUrl)) } } try { var waited = 0L while (waited < CHALLENGE_TIMEOUT_MS) { delay(CHALLENGE_POLL_MS) waited += CHALLENGE_POLL_MS val cleared = fetchCookies().orEmpty().any { cookie -> cookie.name == "cf_clearance" && cookie.matchesHost(host) } val title = withContext(Dispatchers.Main) { webView.title.orEmpty() } if (cleared && title.isNotBlank() && !isCloudflareChallengePageTitle(title)) return true } return false } finally { // NonCancellable: a cancelled caller must still stop the page load. withContext(NonCancellable + Dispatchers.Main) { webView.stopLoading() } } } override suspend fun syncCookies(url: String): String? { if (url.isBlank()) return null val host = NSURL.URLWithString(url)?.host?.lowercase() ?: return null val matching = fetchCookies().orEmpty().filter { cookie -> cookie.matchesHost(host) } if (matching.isEmpty()) return null cookieJar.setFromResponse(url, matching.map { it.toSetCookieHeader() }) return cookieJar.cookieHeader(url) } private suspend fun fetchCookies() = withContext(Dispatchers.Main) { profileDataStore(cookieJar.profileId) }.allCookies() } private const val CHALLENGE_POLL_MS = 500L private const val CHALLENGE_TIMEOUT_MS = 45_000L