AndroidWebViewProfiles.kt
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/webview/AndroidWebViewProfiles.kt
1package eu.friedcutlet.yokan.services.webview23import android.content.Context4import android.webkit.CookieManager5import android.webkit.WebView6import androidx.webkit.ProfileStore7import androidx.webkit.WebViewCompat8import eu.friedcutlet.yokan.domain.ProfileId9import eu.friedcutlet.yokan.services.http.cookies.platformBrowserIsolation10import eu.friedcutlet.yokan.services.logging.AppLogger11import kotlinx.coroutines.Dispatchers12import kotlinx.coroutines.withContext1314// Extra profiles only reach these when CookieJar.canUseBrowserStorage holds, i.e. WebViewFeature.MULTI_PROFILE.15// ProfileStore must be used on the main thread.1617/** The cookie store backing [id]'s WebViews: Default keeps the app-wide store, extras get their WebView profile's. */18internal fun profileCookieManager(id: ProfileId): CookieManager =19 if (id == ProfileId.Default) CookieManager.getInstance()20 else ProfileStore.getInstance().getOrCreateProfile(id.value).cookieManager2122/** A WebView bound to [id]'s WebView profile; the profile must be set before the view is used. */23internal fun newProfileWebView(context: Context, id: ProfileId): WebView =24 WebView(context).also { if (id != ProfileId.Default) WebViewCompat.setProfile(it, id.value) }2526/** Drops a deleted extra profile's WebView profile. Failures (still in use) are logged: profile deletion must still finish. */27internal suspend fun deleteProfileWebViewStorage(id: ProfileId) {28 if (!platformBrowserIsolation) return29 withContext(Dispatchers.Main) {30 // deleteProfile returns false when the profile was never created.31 runCatching { ProfileStore.getInstance().deleteProfile(id.value) }32 .onFailure { AppLogger.warn("[profiles] Could not delete WebView profile ${id.value}: ${it.message}") }33 }34}35