Yokan / rebuild
Course 1 8624561

ResumableDownload.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/ResumableDownload.kt

implementation108 lines
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DatabaseJson4import eu.friedcutlet.yokan.services.catchingNonCancellation5import eu.friedcutlet.yokan.services.files.LocalFileService6import eu.friedcutlet.yokan.services.http.HttpRequest7import eu.friedcutlet.yokan.services.http.HttpService8import eu.friedcutlet.yokan.services.http.HttpStreamResponse9import eu.friedcutlet.yokan.services.http.header10import kotlinx.serialization.Serializable11import kotlinx.serialization.encodeToString1213@Serializable14private data class PartialDownload(val url: String, val etag: String, val total: Long)1516internal data class DownloadTransfer(val response: HttpStreamResponse?, val bytes: Long, val complete: Boolean)1718/** Retains only partial representations validated by a strong ETag and a known total length. */19internal class ResumableDownload(private val http: HttpService, private val files: LocalFileService) {20    suspend fun transfer(21        url: String,22        headers: Map<String, String>,23        path: String,24        validateResponse: (HttpStreamResponse) -> Unit = {},25        onProgress: (Long) -> Unit,26    ): DownloadTransfer {27        val manifest = "$path.resume"28        var saved = catchingNonCancellation {29            DatabaseJson.decodeFromString<PartialDownload>(files.readBytesAsync(manifest, 64 * 1024).decodeToString())30        }.getOrNull()?.takeIf { it.url == url && it.total > 0 && it.etag.startsWith('"') }31        var offset = if (saved != null && files.exists(path)) files.directorySize(path) else 0L32        if (saved == null || offset <= 0 || offset >= saved.total) {33            saved = null34            offset = 035            check(files.deleteRecursivelyAsync(path)) { "Cannot reset partial download" }36            files.deleteRecursivelyAsync(manifest)37        }38        // One immediate full retry when a server ignores Range or the representation has changed.39        repeat(2) {40            val partial = saved41            val start = offset42            var received = 0L43            var response: HttpStreamResponse? = null44            var validated = false45            var restart = false46            val result = catchingNonCancellation {47                val stream: suspend (suspend (ByteArray) -> Unit) -> HttpStreamResponse = { write ->48                    val requestHeaders = headers.filterKeys {49                        !it.equals("Range", true) && !it.equals("If-Range", true) && !it.equals("Accept-Encoding", true)50                    } + mapOf("Accept-Encoding" to "identity") + if (partial != null) {51                        mapOf("Range" to "bytes=$start-", "If-Range" to partial.etag)52                    } else emptyMap()53                    http.stream(HttpRequest(url = url, headers = requestHeaders, onStreamResponse = { head ->54                        response = head55                        if (head.statusCode in 200..299) validateResponse(head)56                        if (head.statusCode in 200..299) {57                            val range = head.headers.header("Content-Range")58                            val expectedRange = partial?.let { "bytes $start-${it.total - 1}/${it.total}" }59                            val encoding = head.headers.header("Content-Encoding")60                            if ((partial != null && (head.statusCode != 206 || range != expectedRange ||61                                    head.headers.header("ETag")?.let { it != partial.etag } == true)) ||62                                (partial == null && head.statusCode == 206) ||63                                (encoding != null && !encoding.equals("identity", true))64                            ) {65                                restart = true66                                error("Response does not match the saved partial representation")67                            }68                            validated = true69                            val etag = head.headers.header("ETag")?.takeIf { it.startsWith('"') && it.endsWith('"') }70                            val total = partial?.total ?: head.headers.header("Content-Length")?.toLongOrNull()71                            if (etag != null && total != null && total > 0) {72                                files.writeBytesAsync(manifest, DatabaseJson.encodeToString(PartialDownload(url, etag, total)).encodeToByteArray())73                            }74                        } else if (partial != null && head.statusCode == 416) {75                            restart = true76                            error("Saved range is no longer available")77                        }78                    })) { chunk ->79                        check(partial == null || validated) { "Transport must validate range headers before appending" }80                        write(chunk)81                        received += chunk.size82                        onProgress(start + received)83                    }84                }85                if (partial == null) files.writeChunks(path, stream) else files.appendChunks(path, stream)86            }87            if (restart) {88                check(files.deleteRecursivelyAsync(path)) { "Cannot reset partial download" }89                files.deleteRecursivelyAsync(manifest)90                saved = null91                offset = 092                onProgress(0)93            } else {94                val final = result.getOrNull() ?: response95                val expected = partial?.let { it.total - start } ?: final?.headers?.header("Content-Length")?.toLongOrNull()96                val complete = result.isSuccess && final?.statusCode in 200..299 && received > 0 &&97                    (expected == null || expected == received) && (partial == null || validated) &&98                    (final?.statusCode != 206 || validated)99                if (!complete && final?.statusCode in 200..299 && expected != null && received > expected) {100                    files.deleteRecursivelyAsync(path)101                    files.deleteRecursivelyAsync(manifest)102                }103                return DownloadTransfer(final, start + received, complete)104            }105        }106        return DownloadTransfer(null, 0, false)107    }108}109

Search chapters, reference and source filenames.