package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.services.logging.AppLogger 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.notifications.InAppNotifications import eu.friedcutlet.yokan.services.system.openSystemBrowser import java.util.concurrent.atomic.AtomicBoolean import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runInterruptible internal actual fun createSharedPlatformWebViewService(http: HttpService, cookieJar: CookieJar, files: LocalFileService): WebViewService = DesktopWebViewService(cookieJar, files) private class DesktopWebViewService( private val cookieJar: CookieJar, private val files: LocalFileService, ) : WebViewService { override suspend fun open(request: WebViewRequest): Boolean { if (request.url.isBlank()) return false return openSystemBrowser(request.url) } override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? { if (request.url.isBlank()) return null // solve() blocks for up to minutes; keep it off the caller's thread and let // cancellation interrupt it so its finally block kills the browser process. val result = runInterruptible(Dispatchers.IO) { DesktopBrowserChallengeSession.solve(request.url, cookieJar, files.cacheRoot) } ?: return null cookieJar.rememberUserAgent(request.url, result.userAgent) return result.response } override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String { if (url.isBlank() || script.isBlank()) return "" if (scriptWarningShown.compareAndSet(false, true)) { val message = "Desktop WebView scripting is unavailable in this runtime. " + "Use the Cloudflare resolver or import cookies if the source needs a browser session." AppLogger.warn(message) InAppNotifications.post( title = "WebView script unavailable", message = message, ) } return "" } override suspend fun syncCookies(url: String): String? = cookieJar.cookieHeader(url) } private val scriptWarningShown = AtomicBoolean(false)