package eu.friedcutlet.yokan.services.webview import android.content.Context import android.webkit.CookieManager import android.webkit.WebView import androidx.webkit.ProfileStore import androidx.webkit.WebViewCompat import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.http.cookies.platformBrowserIsolation import eu.friedcutlet.yokan.services.logging.AppLogger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext // Extra profiles only reach these when CookieJar.canUseBrowserStorage holds, i.e. WebViewFeature.MULTI_PROFILE. // ProfileStore must be used on the main thread. /** The cookie store backing [id]'s WebViews: Default keeps the app-wide store, extras get their WebView profile's. */ internal fun profileCookieManager(id: ProfileId): CookieManager = if (id == ProfileId.Default) CookieManager.getInstance() else ProfileStore.getInstance().getOrCreateProfile(id.value).cookieManager /** A WebView bound to [id]'s WebView profile; the profile must be set before the view is used. */ internal fun newProfileWebView(context: Context, id: ProfileId): WebView = WebView(context).also { if (id != ProfileId.Default) WebViewCompat.setProfile(it, id.value) } /** Drops a deleted extra profile's WebView profile. Failures (still in use) are logged: profile deletion must still finish. */ internal suspend fun deleteProfileWebViewStorage(id: ProfileId) { if (!platformBrowserIsolation) return withContext(Dispatchers.Main) { // deleteProfile returns false when the profile was never created. runCatching { ProfileStore.getInstance().deleteProfile(id.value) } .onFailure { AppLogger.warn("[profiles] Could not delete WebView profile ${id.value}: ${it.message}") } } }