package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DatabaseJson import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.HttpStreamResponse import eu.friedcutlet.yokan.services.http.header import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString @Serializable private data class PartialDownload(val url: String, val etag: String, val total: Long) internal data class DownloadTransfer(val response: HttpStreamResponse?, val bytes: Long, val complete: Boolean) /** Retains only partial representations validated by a strong ETag and a known total length. */ internal class ResumableDownload(private val http: HttpService, private val files: LocalFileService) { suspend fun transfer( url: String, headers: Map, path: String, validateResponse: (HttpStreamResponse) -> Unit = {}, onProgress: (Long) -> Unit, ): DownloadTransfer { val manifest = "$path.resume" var saved = catchingNonCancellation { DatabaseJson.decodeFromString(files.readBytesAsync(manifest, 64 * 1024).decodeToString()) }.getOrNull()?.takeIf { it.url == url && it.total > 0 && it.etag.startsWith('"') } var offset = if (saved != null && files.exists(path)) files.directorySize(path) else 0L if (saved == null || offset <= 0 || offset >= saved.total) { saved = null offset = 0 check(files.deleteRecursivelyAsync(path)) { "Cannot reset partial download" } files.deleteRecursivelyAsync(manifest) } // One immediate full retry when a server ignores Range or the representation has changed. repeat(2) { val partial = saved val start = offset var received = 0L var response: HttpStreamResponse? = null var validated = false var restart = false val result = catchingNonCancellation { val stream: suspend (suspend (ByteArray) -> Unit) -> HttpStreamResponse = { write -> val requestHeaders = headers.filterKeys { !it.equals("Range", true) && !it.equals("If-Range", true) && !it.equals("Accept-Encoding", true) } + mapOf("Accept-Encoding" to "identity") + if (partial != null) { mapOf("Range" to "bytes=$start-", "If-Range" to partial.etag) } else emptyMap() http.stream(HttpRequest(url = url, headers = requestHeaders, onStreamResponse = { head -> response = head if (head.statusCode in 200..299) validateResponse(head) if (head.statusCode in 200..299) { val range = head.headers.header("Content-Range") val expectedRange = partial?.let { "bytes $start-${it.total - 1}/${it.total}" } val encoding = head.headers.header("Content-Encoding") if ((partial != null && (head.statusCode != 206 || range != expectedRange || head.headers.header("ETag")?.let { it != partial.etag } == true)) || (partial == null && head.statusCode == 206) || (encoding != null && !encoding.equals("identity", true)) ) { restart = true error("Response does not match the saved partial representation") } validated = true val etag = head.headers.header("ETag")?.takeIf { it.startsWith('"') && it.endsWith('"') } val total = partial?.total ?: head.headers.header("Content-Length")?.toLongOrNull() if (etag != null && total != null && total > 0) { files.writeBytesAsync(manifest, DatabaseJson.encodeToString(PartialDownload(url, etag, total)).encodeToByteArray()) } } else if (partial != null && head.statusCode == 416) { restart = true error("Saved range is no longer available") } })) { chunk -> check(partial == null || validated) { "Transport must validate range headers before appending" } write(chunk) received += chunk.size onProgress(start + received) } } if (partial == null) files.writeChunks(path, stream) else files.appendChunks(path, stream) } if (restart) { check(files.deleteRecursivelyAsync(path)) { "Cannot reset partial download" } files.deleteRecursivelyAsync(manifest) saved = null offset = 0 onProgress(0) } else { val final = result.getOrNull() ?: response val expected = partial?.let { it.total - start } ?: final?.headers?.header("Content-Length")?.toLongOrNull() val complete = result.isSuccess && final?.statusCode in 200..299 && received > 0 && (expected == null || expected == received) && (partial == null || validated) && (final?.statusCode != 206 || validated) if (!complete && final?.statusCode in 200..299 && expected != null && received > expected) { files.deleteRecursivelyAsync(path) files.deleteRecursivelyAsync(manifest) } return DownloadTransfer(final, start + received, complete) } } return DownloadTransfer(null, 0, false) } }