package eu.friedcutlet.yokan.services.webview import eu.friedcutlet.yokan.services.http.HttpResponse import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive /** Factory stays unopened for unsupported or retired owners. Production supplies its session scope. */ internal class ProfileWebViewService( private val cookieJar: CookieJar, ownerScope: CoroutineScope?, factory: () -> WebViewService, ) : WebViewService { private val lock = PlatformLock() private val ownerJob = ownerScope?.let { requireNotNull(it.coroutineContext[Job]) { "Profile browser requires an owner job" } } private val scope = ownerScope?.let { CoroutineScope(it.coroutineContext + SupervisorJob(ownerJob)) } private val service = lazy(factory) private fun isAllowed() = cookieJar.canUseBrowserStorage && (ownerJob == null || ownerJob.isActive) private suspend fun runAllowed(fallback: T, action: suspend (WebViewService) -> T): T { currentCoroutineContext().ensureActive() if (!isAllowed()) return fallback suspend fun invoke(): T { currentCoroutineContext().ensureActive() val delegate = lock.withLock { if (isAllowed()) service.value else null } ?: return fallback return action(delegate) } val owner = scope ?: return invoke() return owner.runJoined { invoke() } } override suspend fun open(request: WebViewRequest): Boolean = runAllowed(false) { it.open(request) } override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse? = runAllowed(null) { it.resolveCloudflare(request) } override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String = runAllowed("") { it.evaluateScript(url, script, userAgent) } override suspend fun syncCookies(url: String): String? = runAllowed(null) { it.syncCookies(url) } }