package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.domain.ProfileId import eu.friedcutlet.yokan.services.runJoined import eu.friedcutlet.yokan.services.scheduling.ProfileWorkResult 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 import kotlinx.coroutines.launch /** Process-local capabilities. Notification actions never bootstrap or reopen a profile. */ internal class ProfileDownloadBindings { private val lock = PlatformLock() private val bindings = mutableMapOf() fun install(id: ProfileId, downloads: DownloadService, ownerScope: CoroutineScope, hideContent: () -> Boolean = { false }): Binding { val parent = requireNotNull(ownerScope.coroutineContext[Job]) require(parent.isActive) { "Download owner is retired" } val binding = Binding(id, downloads, CoroutineScope(ownerScope.coroutineContext + SupervisorJob(parent)), hideContent) val previous = lock.withLock { bindings.put(id, binding) } previous?.retire() binding.job.invokeOnCompletion { lock.withLock { if (bindings[id] === binding) bindings.remove(id) } } return binding } fun resolve(owner: String?, token: String?): Binding? { if (owner == null || token == null) return null val id = try { ProfileId(owner) } catch (_: IllegalArgumentException) { return null } return lock.withLock { bindings[id]?.takeIf { it.token == token && it.isActive } } } class Binding internal constructor( val id: ProfileId, val downloads: DownloadService, private val scope: CoroutineScope, /** Notification privacy of the owning profile (Security → hide notification content). */ val hideContent: () -> Boolean = { false }, ) { // Distinguishes two sessions for the same profile; it is not a credential or a persistent ID. val token: String = ProfileId.random().value val actionIdentity: String get() = "yokan://downloads/${id.value}/$token" internal val job = requireNotNull(scope.coroutineContext[Job]) val isActive: Boolean get() = job.isActive fun cancelAll() { scope.launch { downloads.cancelAll() } } fun retire() { job.cancel() } suspend fun run(action: suspend (DownloadService) -> Unit): ProfileWorkResult { currentCoroutineContext().ensureActive() if (!isActive) return ProfileWorkResult.Skipped scope.runJoined { action(downloads) } return ProfileWorkResult.Completed(Unit) } } companion object { const val TokenKey = "yokan.download_session" } }