package eu.friedcutlet.yokan.ui.screens.webview import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.isCloudflareChallenge import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.notifications.InAppNotifications import eu.friedcutlet.yokan.services.notifications.InAppMessage import eu.friedcutlet.yokan.services.webview.WebViewRequest import eu.friedcutlet.yokan.services.webview.WebViewService import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch internal enum class BrowserVerificationStatus { Ready, Waiting, Verified, Failed } internal data class InAppWebViewState( /** Page-load / Cloudflare progress; the bar shows only strictly between 0 and 1. */ val progress: Float = 0f, /** Settings user agent, used when the route does not pin one. */ val defaultUserAgent: String, val verificationUrl: String? = null, val verificationStatus: BrowserVerificationStatus = BrowserVerificationStatus.Ready, ) internal class InAppWebViewViewModel( private val webView: WebViewService, /** Handed to the platform WebView so it seeds and harvests the shared jar. */ val cookieJar: CookieJar, settings: SettingsStore, ) : ViewModel() { private val _state = MutableStateFlow(InAppWebViewState(defaultUserAgent = settings.db.value.userAgent)) val state: StateFlow = _state.asStateFlow() private var verificationJob: Job? = null private var verificationRequest: Any? = null init { viewModelScope.launch { settings.db.map { it.userAgent }.distinctUntilChanged().collect { userAgent -> _state.update { it.copy(defaultUserAgent = userAgent) } } } } fun setProgress(value: Float) { _state.update { it.copy(progress = value.coerceIn(0f, 1f)) } } fun requireBrowserVerification(url: String) { if (!cookieJar.canUseBrowserStorage) return if (_state.value.verificationUrl == url) return verificationRequest = null verificationJob?.cancel() verificationJob = null _state.update { it.copy( verificationUrl = url, verificationStatus = BrowserVerificationStatus.Ready, progress = 1f, ) } } private fun isCurrentVerification(request: Any): Boolean = verificationRequest === request && cookieJar.canUseBrowserStorage fun solveCloudflare(url: String, userAgent: String?) { if (!cookieJar.canUseBrowserStorage || verificationJob?.isActive == true) return val request = Any() verificationRequest = request _state.update { it.copy( verificationUrl = url, verificationStatus = BrowserVerificationStatus.Waiting, progress = 0.05f, ) } verificationJob = viewModelScope.launch { try { val result = catchingNonCancellation { webView.resolveCloudflare( WebViewRequest( url = url, title = "Cloudflare", headers = userAgent ?.takeIf { it.isNotBlank() } ?.let { mapOf("User-Agent" to it) } .orEmpty(), ), ) } // A redirected page or retired profile must never consume a previous session's result. if (!isCurrentVerification(request)) return@launch result.onSuccess { response -> val verified = response != null && response.statusCode in 200..299 && !response.isCloudflareChallenge() _state.update { it.copy(verificationStatus = if (verified) BrowserVerificationStatus.Verified else BrowserVerificationStatus.Failed, progress = 1f) } postBrowserMessage( title = if (verified) "Cloudflare check complete" else "Cloudflare check incomplete", message = response?.let { "HTTP ${it.statusCode}" } ?: "No response returned.", ) }.onFailure { error -> _state.update { it.copy(verificationStatus = BrowserVerificationStatus.Failed, progress = 1f) } postBrowserMessage( title = "Cloudflare check failed", message = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() }, ) } } finally { if (isCurrentVerification(request)) { _state.update { if (it.verificationStatus == BrowserVerificationStatus.Waiting) { it.copy(verificationStatus = BrowserVerificationStatus.Failed, progress = 1f) } else it } verificationRequest = null } } } } /** * Fired after every navigation so cookies set by the loaded page (especially after a tracker / * source login) land in the shared CookieJar — the next HTTP request through `services.http` * for that host picks them up automatically. */ fun syncCookies(url: String) { viewModelScope.launch { catchingNonCancellation { webView.syncCookies(url) } } } /** Returns true when the cookies were saved (the import dialog closes). */ fun importCookies(url: String, raw: String): Boolean { if (!cookieJar.isAvailable) return false val host = hostFromUrl(url) val cookie = normaliseCookieInput(raw) if (host == null || cookie == null) { postBrowserMessage( title = "Cookies not imported", message = "Paste a Cookie header with at least one name=value pair.", ) return false } cookieJar.put(host, cookie) postBrowserMessage( title = "Cookies imported", message = "Saved cookies for $host.", ) return true } fun clearCookies(url: String) { if (!cookieJar.isAvailable) return hostFromUrl(url)?.let { host -> cookieJar.clear(host) postBrowserMessage( title = "Cookies cleared", message = "Removed cookies for $host.", ) } } private fun postBrowserMessage(title: String, message: String) { if (cookieJar.isAvailable) { InAppNotifications.post(InAppMessage(title, message, profileId = cookieJar.profileId)) } } }