Yokan / rebuild
Course 1 8624561

PageTransfer.kt

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

implementation177 lines
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbPageUrl5import eu.friedcutlet.yokan.database.YokanDatabase6import eu.friedcutlet.yokan.services.catchingNonCancellation7import eu.friedcutlet.yokan.services.files.LocalFileService8import eu.friedcutlet.yokan.services.http.HttpService9import eu.friedcutlet.yokan.services.http.header10import kotlinx.coroutines.CoroutineDispatcher11import kotlinx.coroutines.delay12import kotlinx.coroutines.sync.Semaphore13import kotlinx.coroutines.sync.withPermit14import kotlinx.coroutines.withContext1516/** Page file extensions kept from the URL; anything else is saved as `.jpg` so the reader lists it. */17private val PageFileExtensions = setOf(18    "png", "jpg", "jpeg", "gif", "webp", "bmp", "avif",19    "mp4", "mkv", "mov", "webm", "avi", "m4v", "ts",20    "txt", "html", "xhtml",21)2223/**24 * Fetches and stores single chapter files (pages, HLS streams, novel text) with `.part` files and25 * `.complete` markers. Holds no queue state: progress reaches the caller only through its callbacks.26 */27internal class PageTransfer(28    private val database: YokanDatabase,29    val http: HttpService,30    val files: LocalFileService,31    imageHttp: HttpService,32    private val imageDataSaver: ImageDataSaver?,33    /** Blocking file work: page writes, promotion and splitting. */34    val ioDispatcher: CoroutineDispatcher,35    /** Suspends while the network may not be used; called before every attempt. */36    private val awaitAllowedNetwork: suspend () -> Unit,37) {38    private val transfers = ResumableDownload(http, files)39    private val imageTransfers = ResumableDownload(imageHttp, files)40    private val splitPages = SplitPageStore(files)4142    /**43     * Sizes of the pages an earlier run saved in [location] (page file plus `.complete` marker) by index.44     * Files of indices beyond [pageCount] are deleted, so a shorter page list leaves no stale pages behind.45     */46    suspend fun savedPages(location: String, pageCount: Int, splitHeight: Int?): Map<Int, Long> {47        val entries = files.listFiles(location)48        val names = entries.mapTo(HashSet()) { it.name }49        val saved = mutableMapOf<Int, Long>()50        entries.filter { it.name.endsWith(".split.json") }.forEach { entry ->51            val base = entry.name.removeSuffix(".split.json")52            val index = base.toIntOrNull()?.minus(1) ?: return@forEach53            if (index in 0 until pageCount) splitPages.savedSize(location, base)?.let { saved[index] = it }54        }55        entries.forEach { entry ->56            val index = entry.name.takeWhile(Char::isDigit).toIntOrNull()?.minus(1) ?: return@forEach57            val isPageFile = entry.name.substringBeforeLast('.').all(Char::isDigit)58            if (index >= pageCount) {59                safeDelete(entry.path)60            } else if (index !in saved && isPageFile && "${entry.name}.complete" in names && files.exists(entry.path)) {61                saved[index] = if (splitHeight != null) splitPages.process(entry.path, splitHeight) else entry.sizeBytes62            }63        }64        return saved65    }6667    /**68     * Saves page [index] of [request] into [location], holding one of the chapter's [permits] while it69     * transfers. Null once saved, else the failing HTTP status (0 without a response).70     */71    suspend fun downloadPage(72        request: DownloadRequest,73        location: String,74        permits: Semaphore,75        page: DbPageUrl,76        index: Int,77        onBytes: (Long) -> Unit,78        onTransfer: (Long) -> Unit,79    ): Int? {80        val name = padIndex(index + 1)81        val retries = request.retries82        if (page.url.endsWith(".m3u8", ignoreCase = true) || page.url.contains(".m3u8?", ignoreCase = true)) {83            return downloadHlsPlaylist(page, location, name, retries, permits, onBytes, onTransfer)84        }85        val settings = database.settings()86        // E-ink devices store manga pages at panel size in grayscale; the page keeps its name, readers sniff the format.87        val shrink: ((ByteArray) -> ByteArray?)? = if (request.itemType == DbItemType.Manga && settings.einkMode && settings.einkOptimizeDownloads) {88            { bytes -> transcodeEinkPage(bytes, settings.einkPreset.width) }89        } else null90        return permits.withPermit {91            val path = "$location/$name${page.url.fileExtension()}"92            var storedBytes = 0L93            val sourceId = request.sourceId ?: database.chapter(request.chapterId)?.mangaId?.let(database::manga)?.sourceId94            val optimized = if (request.itemType == DbItemType.Manga) imageDataSaver?.resolve(page.url, page.headers.orEmpty(), sourceId, settings.features.imageDataSaver, download = true) else null95            var status = if (optimized != null) attemptDownload(optimized.url, optimized.headers, path, 0, { storedBytes = it }, shrink, onTransfer, imageTransfers, requireImageResponse = true) else 096            if (optimized == null || status != null) {97                if (optimized != null) imageDataSaver?.failed(optimized)98                status = attemptDownload(page.url, page.headers.orEmpty(), path, retries, { storedBytes = it }, shrink, onTransfer)99            }100            if (status == null) {101                if (request.itemType == DbItemType.Manga && settings.features.downloads.splitTallImages) {102                    storedBytes = withContext(ioDispatcher) { splitPages.process(path, settings.features.downloads.splitImageHeight) }103                }104                onBytes(storedBytes)105            }106            status107        }108    }109110    /**111     * Streams [url] to [targetPath] through a `.part` file, then writes its `.complete` marker. Exceptions,112     * empty bodies, 408, 429 and 5xx are retried up to [retries] times with backoff (Retry-After when sent);113     * any other status fails at once. Null once saved, else the last HTTP status (0 without a response).114     */115    suspend fun attemptDownload(116        url: String,117        headers: Map<String, String>,118        targetPath: String,119        retries: Int,120        onBytes: (Long) -> Unit,121        transform: ((ByteArray) -> ByteArray?)? = null,122        onTransfer: (Long) -> Unit = {},123        transferService: ResumableDownload = transfers,124        requireImageResponse: Boolean = false,125    ): Int? = withContext(ioDispatcher) {126        val marker = "$targetPath.complete"127        val temporaryPath = "$targetPath.part"128        if (!safeDelete(marker) || files.exists(marker)) return@withContext 0129        var status = 0130        var retryAfter: String? = null131        for (attempt in 0..retries.coerceAtLeast(0)) {132            if (attempt > 0) delay(downloadRetryDelayMs(attempt, retryAfter))133            awaitAllowedNetwork()134            val transfer = transferService.transfer(url, headers, temporaryPath, validateResponse = { head ->135                if (requireImageResponse) check(head.headers.header("Content-Type")?.startsWith("image/", true) == true) { "Optimizer did not return an image" }136            }, onProgress = onTransfer)137            var downloadedBytes = transfer.bytes138            val response = transfer.response139            status = response?.statusCode ?: 0140            retryAfter = response?.headers?.header("Retry-After")141            if (transfer.complete) {142                transform?.let { shrink ->143                    catchingNonCancellation { shrink(files.readBytesAsync(temporaryPath, MaxSplitImageBytes)) }.getOrNull()?.let { smaller ->144                        files.writeBytesAsync(temporaryPath, smaller)145                        downloadedBytes = smaller.size.toLong()146                    }147                }148            }149            if (transfer.complete && promoteWithMarker(temporaryPath, targetPath, marker)) {150                safeDelete("$temporaryPath.resume")151                onTransfer(downloadedBytes)152                onBytes(downloadedBytes)153                return@withContext null154            }155            if (response != null && status !in 200..299 && !isRetryableDownloadStatus(status)) return@withContext status156        }157        status158    }159160    /** The marker is only ever written after the page was promoted to its final name. */161    suspend fun promoteWithMarker(temporaryPath: String, targetPath: String, marker: String): Boolean =162        catchingNonCancellation {163            files.promoteAsync(temporaryPath, targetPath) && run {164                files.writeBytesAsync(marker, ByteArray(0))165                true166            }167        }.getOrDefault(false)168169    private suspend fun safeDelete(path: String): Boolean = catchingNonCancellation { files.deleteRecursivelyAsync(path) }.getOrDefault(false)170}171172internal fun padIndex(index: Int): String = index.toString().padStart(4, '0')173174private fun String.fileExtension(): String {175    val extension = substringBefore('?').substringBefore('#').substringAfterLast('/').substringAfterLast('.', "").lowercase()176    return if (extension in PageFileExtensions) ".$extension" else ".jpg"177}178

Search chapters, reference and source filenames.