ProfileWebViewService.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/webview/ProfileWebViewService.kt
1package eu.friedcutlet.yokan.services.webview23import eu.friedcutlet.yokan.services.http.HttpResponse4import eu.friedcutlet.yokan.services.http.cookies.CookieJar5import eu.friedcutlet.yokan.services.runJoined6import eu.friedcutlet.yokan.util.PlatformLock7import kotlinx.coroutines.CoroutineScope8import kotlinx.coroutines.Job9import kotlinx.coroutines.SupervisorJob10import kotlinx.coroutines.currentCoroutineContext11import kotlinx.coroutines.ensureActive1213/** Factory stays unopened for unsupported or retired owners. Production supplies its session scope. */14internal class ProfileWebViewService(15 private val cookieJar: CookieJar,16 ownerScope: CoroutineScope?,17 factory: () -> WebViewService,18) : WebViewService {19 private val lock = PlatformLock()20 private val ownerJob = ownerScope?.let { requireNotNull(it.coroutineContext[Job]) { "Profile browser requires an owner job" } }21 private val scope = ownerScope?.let { CoroutineScope(it.coroutineContext + SupervisorJob(ownerJob)) }22 private val service = lazy(factory)2324 private fun isAllowed() = cookieJar.canUseBrowserStorage && (ownerJob == null || ownerJob.isActive)2526 private suspend fun <T> runAllowed(fallback: T, action: suspend (WebViewService) -> T): T {27 currentCoroutineContext().ensureActive()28 if (!isAllowed()) return fallback29 suspend fun invoke(): T {30 currentCoroutineContext().ensureActive()31 val delegate = lock.withLock { if (isAllowed()) service.value else null } ?: return fallback32 return action(delegate)33 }34 val owner = scope ?: return invoke()35 return owner.runJoined { invoke() }36 }3738 override suspend fun open(request: WebViewRequest): Boolean = runAllowed(false) { it.open(request) }39 override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? = runAllowed(null) { it.resolveCloudflare(request) }40 override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String =41 runAllowed("") { it.evaluateScript(url, script, userAgent) }42 override suspend fun syncCookies(url: String): String? = runAllowed(null) { it.syncCookies(url) }43}44