package eu.friedcutlet.yokan.ui.image import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.http.cookies.CookieJar import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine import eu.friedcutlet.yokan.services.http.HostResolver import eu.friedcutlet.yokan.ui.screens.reader.ReaderPageDownloadProgress import io.ktor.client.HttpClient import io.ktor.client.engine.HttpClientEngine import io.ktor.client.plugins.BodyProgress import io.ktor.client.plugins.onDownload import io.ktor.client.request.HttpRequestPipeline import io.ktor.http.HttpHeaders import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.ensureActive import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext /** One Coil transport captures one jar/database and retires with its owner, before database close. */ internal class ProfileImageHttpClient( private val jar: CookieJar, private val database: YokanDatabase, ownerScope: CoroutineScope, resolveHost: HostResolver? = null, engineFactory: () -> HttpClientEngine = { createPlatformHttpClientEngine(jar.profileId, resolveHost) }, ) { private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Image HTTP requires an owner job" } .also { it.ensureActive() } private val engine = eu.friedcutlet.yokan.services.http.ProfileHttpEngine(engineFactory(), ownerJob) private val retirementLock = Mutex() private var released = false val client: HttpClient = HttpClient(engine) { followRedirects = true install(BodyProgress) }.apply { requestPipeline.intercept(HttpRequestPipeline.State) { ownerJob.ensureActive() currentCoroutineContext().ensureActive() this@ProfileImageHttpClient.client.coroutineContext[Job]?.ensureActive() if (!jar.isAvailable) throw kotlinx.coroutines.CancellationException("Image profile session has ended") val url = context.url.buildString() val progressUrl = context.headers[OriginalImageProgressHeader] ?: url context.headers.remove(OriginalImageProgressHeader) if (context.headers[HttpHeaders.Cookie] == null) { jar.cookieHeader(url)?.let { context.headers.append(HttpHeaders.Cookie, it) } } val sessionUserAgent = jar.userAgent(url) if (sessionUserAgent != null) { // A solved clearance is tied to this exact UA, including when a source supplies one. context.headers.remove(HttpHeaders.UserAgent) context.headers.append(HttpHeaders.UserAgent, sessionUserAgent) } else if (context.headers[HttpHeaders.UserAgent] == null) { context.headers.append(HttpHeaders.UserAgent, database.settings().userAgent) } context.onDownload { received, total -> if (ownerJob.isActive && jar.isAvailable) ReaderPageDownloadProgress.report(progressUrl, received, total) } } } private val cleanup = ownerScope.async(start = CoroutineStart.UNDISPATCHED) { try { awaitCancellation() } finally { release() } } suspend fun closeAndJoin() = withContext(NonCancellable) { cleanup.cancel(); cleanup.join() release() // Retry a failed release; joining a canceled deferred does not rethrow its failure. } private suspend fun release() = withContext(NonCancellable) { retirementLock.withLock { if (released) return@withLock val clientJob = client.coroutineContext[Job] clientJob?.cancel() engine.closeAndJoin() clientJob?.join() client.close() released = true } } }