ProfileImageHttpClient.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/image/ProfileImageHttpClient.kt
1package eu.friedcutlet.yokan.ui.image23import eu.friedcutlet.yokan.database.YokanDatabase4import eu.friedcutlet.yokan.services.http.cookies.CookieJar5import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine6import eu.friedcutlet.yokan.services.http.HostResolver7import eu.friedcutlet.yokan.ui.screens.reader.ReaderPageDownloadProgress8import io.ktor.client.HttpClient9import io.ktor.client.engine.HttpClientEngine10import io.ktor.client.plugins.BodyProgress11import io.ktor.client.plugins.onDownload12import io.ktor.client.request.HttpRequestPipeline13import io.ktor.http.HttpHeaders14import kotlinx.coroutines.CoroutineScope15import kotlinx.coroutines.CoroutineStart16import kotlinx.coroutines.Job17import kotlinx.coroutines.NonCancellable18import kotlinx.coroutines.async19import kotlinx.coroutines.awaitCancellation20import kotlinx.coroutines.ensureActive21import kotlinx.coroutines.currentCoroutineContext22import kotlinx.coroutines.sync.Mutex23import kotlinx.coroutines.sync.withLock24import kotlinx.coroutines.withContext2526/** One Coil transport captures one jar/database and retires with its owner, before database close. */27internal class ProfileImageHttpClient(28 private val jar: CookieJar,29 private val database: YokanDatabase,30 ownerScope: CoroutineScope,31 resolveHost: HostResolver? = null,32 engineFactory: () -> HttpClientEngine = { createPlatformHttpClientEngine(jar.profileId, resolveHost) },33) {34 private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Image HTTP requires an owner job" }35 .also { it.ensureActive() }36 private val engine = eu.friedcutlet.yokan.services.http.ProfileHttpEngine(engineFactory(), ownerJob)37 private val retirementLock = Mutex()38 private var released = false39 val client: HttpClient = HttpClient(engine) {40 followRedirects = true41 install(BodyProgress)42 }.apply {43 requestPipeline.intercept(HttpRequestPipeline.State) {44 ownerJob.ensureActive()45 currentCoroutineContext().ensureActive()46 this@ProfileImageHttpClient.client.coroutineContext[Job]?.ensureActive()47 if (!jar.isAvailable) throw kotlinx.coroutines.CancellationException("Image profile session has ended")48 val url = context.url.buildString()49 val progressUrl = context.headers[OriginalImageProgressHeader] ?: url50 context.headers.remove(OriginalImageProgressHeader)51 if (context.headers[HttpHeaders.Cookie] == null) {52 jar.cookieHeader(url)?.let { context.headers.append(HttpHeaders.Cookie, it) }53 }54 val sessionUserAgent = jar.userAgent(url)55 if (sessionUserAgent != null) {56 // A solved clearance is tied to this exact UA, including when a source supplies one.57 context.headers.remove(HttpHeaders.UserAgent)58 context.headers.append(HttpHeaders.UserAgent, sessionUserAgent)59 } else if (context.headers[HttpHeaders.UserAgent] == null) {60 context.headers.append(HttpHeaders.UserAgent, database.settings().userAgent)61 }62 context.onDownload { received, total ->63 if (ownerJob.isActive && jar.isAvailable) ReaderPageDownloadProgress.report(progressUrl, received, total)64 }65 }66 }67 private val cleanup = ownerScope.async(start = CoroutineStart.UNDISPATCHED) {68 try { awaitCancellation() }69 finally { release() }70 }7172 suspend fun closeAndJoin() = withContext(NonCancellable) {73 cleanup.cancel(); cleanup.join()74 release() // Retry a failed release; joining a canceled deferred does not rethrow its failure.75 }7677 private suspend fun release() = withContext(NonCancellable) {78 retirementLock.withLock {79 if (released) return@withLock80 val clientJob = client.coroutineContext[Job]81 clientJob?.cancel()82 engine.closeAndJoin()83 clientJob?.join()84 client.close()85 released = true86 }87 }88}89