WebViewService.ios.kt
composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/webview/WebViewService.ios.kt
1package eu.friedcutlet.yokan.services.webview23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.services.http.EnhancedHttpService5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpResponse7import eu.friedcutlet.yokan.services.files.LocalFileService8import eu.friedcutlet.yokan.services.http.HttpService9import eu.friedcutlet.yokan.services.http.cookies.CookieJar10import eu.friedcutlet.yokan.services.http.isCloudflareChallengePageTitle11import eu.friedcutlet.yokan.services.system.openSystemBrowser12import kotlinx.cinterop.ExperimentalForeignApi13import kotlinx.coroutines.Dispatchers14import kotlinx.coroutines.NonCancellable15import kotlinx.coroutines.delay16import kotlinx.coroutines.withContext17import platform.CoreGraphics.CGRectMake18import platform.Foundation.NSURL19import platform.Foundation.NSURLRequest20import platform.WebKit.WKWebView21import platform.WebKit.WKWebViewConfiguration2223internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService =24 IosWebViewService(http, cookieJar)2526/**27 * iOS [WebViewService] backed by a headless [WKWebView] and the profile's28 * `WKWebsiteDataStore` ([profileDataStore]). Challenge and in-app browsing cookies are harvested29 * into [CookieJar], then attached to the retry performed by [HttpService].30 */31private class IosWebViewService(32 private val http: HttpService,33 private val cookieJar: CookieJar,34) : WebViewService {3536 override suspend fun open(request: WebViewRequest): Boolean {37 if (request.url.isBlank()) return false38 return openSystemBrowser(request.url)39 }4041 /**42 * Mangayomi's `m_client` policy on iOS: drive a headless `WKWebView` on43 * the challenge URL until `cf_clearance` lands in the shared44 * `WKWebsiteDataStore` (or a timeout elapses), harvest cookies into the45 * jar, then retry over HTTP. The retry keeps the caller's skip-marker46 * header so [EnhancedHttpService] doesn't recurse back into the solver.47 */48 override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? {49 if (request.url.isBlank()) return null50 val userAgent = request.headers.entries51 .firstOrNull { it.key.equals("User-Agent", ignoreCase = true) }52 ?.value53 catchingNonCancellation { solveChallenge(request.url, userAgent) }54 syncCookies(request.url)55 val headers = request.headers.toMutableMap()56 cookieJar.cookieHeader(request.url)?.let { headers["Cookie"] = it }57 return http.request(HttpRequest(url = request.url, headers = headers))58 }5960 @OptIn(ExperimentalForeignApi::class)61 private suspend fun solveChallenge(url: String, userAgent: String?): Boolean {62 val nsUrl = NSURL.URLWithString(url) ?: return false63 val host = nsUrl.host?.lowercase() ?: return false64 val webView = withContext(Dispatchers.Main) {65 val configuration = WKWebViewConfiguration().apply { websiteDataStore = profileDataStore(cookieJar.profileId) }66 WKWebView(frame = CGRectMake(0.0, 0.0, 1024.0, 768.0), configuration = configuration).also { view ->67 if (!userAgent.isNullOrBlank()) view.customUserAgent = userAgent68 view.loadRequest(NSURLRequest.requestWithURL(nsUrl))69 }70 }71 try {72 var waited = 0L73 while (waited < CHALLENGE_TIMEOUT_MS) {74 delay(CHALLENGE_POLL_MS)75 waited += CHALLENGE_POLL_MS76 val cleared = fetchCookies().orEmpty().any { cookie ->77 cookie.name == "cf_clearance" && cookie.matchesHost(host)78 }79 val title = withContext(Dispatchers.Main) { webView.title.orEmpty() }80 if (cleared && title.isNotBlank() && !isCloudflareChallengePageTitle(title)) return true81 }82 return false83 } finally {84 // NonCancellable: a cancelled caller must still stop the page load.85 withContext(NonCancellable + Dispatchers.Main) { webView.stopLoading() }86 }87 }8889 override suspend fun syncCookies(url: String): String? {90 if (url.isBlank()) return null91 val host = NSURL.URLWithString(url)?.host?.lowercase() ?: return null92 val matching = fetchCookies().orEmpty().filter { cookie -> cookie.matchesHost(host) }93 if (matching.isEmpty()) return null94 cookieJar.setFromResponse(url, matching.map { it.toSetCookieHeader() })95 return cookieJar.cookieHeader(url)96 }9798 private suspend fun fetchCookies() = withContext(Dispatchers.Main) { profileDataStore(cookieJar.profileId) }.allCookies()99}100101private const val CHALLENGE_POLL_MS = 500L102private const val CHALLENGE_TIMEOUT_MS = 45_000L103