InAppWebViewViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/webview/InAppWebViewViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.webview23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.services.catchingNonCancellation7import eu.friedcutlet.yokan.services.http.isCloudflareChallenge8import eu.friedcutlet.yokan.services.http.cookies.CookieJar9import eu.friedcutlet.yokan.services.notifications.InAppNotifications10import eu.friedcutlet.yokan.services.notifications.InAppMessage11import eu.friedcutlet.yokan.services.webview.WebViewRequest12import eu.friedcutlet.yokan.services.webview.WebViewService13import kotlinx.coroutines.Job14import kotlinx.coroutines.flow.MutableStateFlow15import kotlinx.coroutines.flow.StateFlow16import kotlinx.coroutines.flow.asStateFlow17import kotlinx.coroutines.flow.distinctUntilChanged18import kotlinx.coroutines.flow.map19import kotlinx.coroutines.flow.update20import kotlinx.coroutines.launch2122internal enum class BrowserVerificationStatus { Ready, Waiting, Verified, Failed }2324internal data class InAppWebViewState(25 /** Page-load / Cloudflare progress; the bar shows only strictly between 0 and 1. */26 val progress: Float = 0f,27 /** Settings user agent, used when the route does not pin one. */28 val defaultUserAgent: String,29 val verificationUrl: String? = null,30 val verificationStatus: BrowserVerificationStatus = BrowserVerificationStatus.Ready,31)3233internal class InAppWebViewViewModel(34 private val webView: WebViewService,35 /** Handed to the platform WebView so it seeds and harvests the shared jar. */36 val cookieJar: CookieJar,37 settings: SettingsStore,38) : ViewModel() {39 private val _state = MutableStateFlow(InAppWebViewState(defaultUserAgent = settings.db.value.userAgent))40 val state: StateFlow<InAppWebViewState> = _state.asStateFlow()41 private var verificationJob: Job? = null42 private var verificationRequest: Any? = null4344 init {45 viewModelScope.launch {46 settings.db.map { it.userAgent }.distinctUntilChanged().collect { userAgent ->47 _state.update { it.copy(defaultUserAgent = userAgent) }48 }49 }50 }5152 fun setProgress(value: Float) {53 _state.update { it.copy(progress = value.coerceIn(0f, 1f)) }54 }5556 fun requireBrowserVerification(url: String) {57 if (!cookieJar.canUseBrowserStorage) return58 if (_state.value.verificationUrl == url) return59 verificationRequest = null60 verificationJob?.cancel()61 verificationJob = null62 _state.update { it.copy(63 verificationUrl = url, verificationStatus = BrowserVerificationStatus.Ready, progress = 1f,64 ) }65 }6667 private fun isCurrentVerification(request: Any): Boolean =68 verificationRequest === request && cookieJar.canUseBrowserStorage6970 fun solveCloudflare(url: String, userAgent: String?) {71 if (!cookieJar.canUseBrowserStorage || verificationJob?.isActive == true) return72 val request = Any()73 verificationRequest = request74 _state.update { it.copy(75 verificationUrl = url, verificationStatus = BrowserVerificationStatus.Waiting, progress = 0.05f,76 ) }77 verificationJob = viewModelScope.launch {78 try {79 val result = catchingNonCancellation {80 webView.resolveCloudflare(81 WebViewRequest(82 url = url,83 title = "Cloudflare",84 headers = userAgent85 ?.takeIf { it.isNotBlank() }86 ?.let { mapOf("User-Agent" to it) }87 .orEmpty(),88 ),89 )90 }91 // A redirected page or retired profile must never consume a previous session's result.92 if (!isCurrentVerification(request)) return@launch93 result.onSuccess { response ->94 val verified = response != null && response.statusCode in 200..299 && !response.isCloudflareChallenge()95 _state.update { it.copy(verificationStatus = if (verified) BrowserVerificationStatus.Verified else BrowserVerificationStatus.Failed, progress = 1f) }96 postBrowserMessage(97 title = if (verified) "Cloudflare check complete" else "Cloudflare check incomplete",98 message = response?.let { "HTTP ${it.statusCode}" }99 ?: "No response returned.",100 )101 }.onFailure { error ->102 _state.update { it.copy(verificationStatus = BrowserVerificationStatus.Failed, progress = 1f) }103 postBrowserMessage(104 title = "Cloudflare check failed",105 message = error.message.orEmpty().ifBlank { error::class.simpleName.orEmpty() },106 )107 }108 } finally {109 if (isCurrentVerification(request)) {110 _state.update {111 if (it.verificationStatus == BrowserVerificationStatus.Waiting) {112 it.copy(verificationStatus = BrowserVerificationStatus.Failed, progress = 1f)113 } else it114 }115 verificationRequest = null116 }117 }118 }119 }120121 /**122 * Fired after every navigation so cookies set by the loaded page (especially after a tracker /123 * source login) land in the shared CookieJar — the next HTTP request through `services.http`124 * for that host picks them up automatically.125 */126 fun syncCookies(url: String) {127 viewModelScope.launch { catchingNonCancellation { webView.syncCookies(url) } }128 }129130 /** Returns true when the cookies were saved (the import dialog closes). */131 fun importCookies(url: String, raw: String): Boolean {132 if (!cookieJar.isAvailable) return false133 val host = hostFromUrl(url)134 val cookie = normaliseCookieInput(raw)135 if (host == null || cookie == null) {136 postBrowserMessage(137 title = "Cookies not imported",138 message = "Paste a Cookie header with at least one name=value pair.",139 )140 return false141 }142 cookieJar.put(host, cookie)143 postBrowserMessage(144 title = "Cookies imported",145 message = "Saved cookies for $host.",146 )147 return true148 }149150 fun clearCookies(url: String) {151 if (!cookieJar.isAvailable) return152 hostFromUrl(url)?.let { host ->153 cookieJar.clear(host)154 postBrowserMessage(155 title = "Cookies cleared",156 message = "Removed cookies for $host.",157 )158 }159 }160161 private fun postBrowserMessage(title: String, message: String) {162 if (cookieJar.isAvailable) {163 InAppNotifications.post(InAppMessage(title, message, profileId = cookieJar.profileId))164 }165 }166}167