package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DbItemType import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.header import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.coroutines.withContext /** Page file extensions kept from the URL; anything else is saved as `.jpg` so the reader lists it. */ private val PageFileExtensions = setOf( "png", "jpg", "jpeg", "gif", "webp", "bmp", "avif", "mp4", "mkv", "mov", "webm", "avi", "m4v", "ts", "txt", "html", "xhtml", ) /** * Fetches and stores single chapter files (pages, HLS streams, novel text) with `.part` files and * `.complete` markers. Holds no queue state: progress reaches the caller only through its callbacks. */ internal class PageTransfer( private val database: YokanDatabase, val http: HttpService, val files: LocalFileService, imageHttp: HttpService, private val imageDataSaver: ImageDataSaver?, /** Blocking file work: page writes, promotion and splitting. */ val ioDispatcher: CoroutineDispatcher, /** Suspends while the network may not be used; called before every attempt. */ private val awaitAllowedNetwork: suspend () -> Unit, ) { private val transfers = ResumableDownload(http, files) private val imageTransfers = ResumableDownload(imageHttp, files) private val splitPages = SplitPageStore(files) /** * Sizes of the pages an earlier run saved in [location] (page file plus `.complete` marker) by index. * Files of indices beyond [pageCount] are deleted, so a shorter page list leaves no stale pages behind. */ suspend fun savedPages(location: String, pageCount: Int, splitHeight: Int?): Map { val entries = files.listFiles(location) val names = entries.mapTo(HashSet()) { it.name } val saved = mutableMapOf() entries.filter { it.name.endsWith(".split.json") }.forEach { entry -> val base = entry.name.removeSuffix(".split.json") val index = base.toIntOrNull()?.minus(1) ?: return@forEach if (index in 0 until pageCount) splitPages.savedSize(location, base)?.let { saved[index] = it } } entries.forEach { entry -> val index = entry.name.takeWhile(Char::isDigit).toIntOrNull()?.minus(1) ?: return@forEach val isPageFile = entry.name.substringBeforeLast('.').all(Char::isDigit) if (index >= pageCount) { safeDelete(entry.path) } else if (index !in saved && isPageFile && "${entry.name}.complete" in names && files.exists(entry.path)) { saved[index] = if (splitHeight != null) splitPages.process(entry.path, splitHeight) else entry.sizeBytes } } return saved } /** * Saves page [index] of [request] into [location], holding one of the chapter's [permits] while it * transfers. Null once saved, else the failing HTTP status (0 without a response). */ suspend fun downloadPage( request: DownloadRequest, location: String, permits: Semaphore, page: DbPageUrl, index: Int, onBytes: (Long) -> Unit, onTransfer: (Long) -> Unit, ): Int? { val name = padIndex(index + 1) val retries = request.retries if (page.url.endsWith(".m3u8", ignoreCase = true) || page.url.contains(".m3u8?", ignoreCase = true)) { return downloadHlsPlaylist(page, location, name, retries, permits, onBytes, onTransfer) } val settings = database.settings() // E-ink devices store manga pages at panel size in grayscale; the page keeps its name, readers sniff the format. val shrink: ((ByteArray) -> ByteArray?)? = if (request.itemType == DbItemType.Manga && settings.einkMode && settings.einkOptimizeDownloads) { { bytes -> transcodeEinkPage(bytes, settings.einkPreset.width) } } else null return permits.withPermit { val path = "$location/$name${page.url.fileExtension()}" var storedBytes = 0L val sourceId = request.sourceId ?: database.chapter(request.chapterId)?.mangaId?.let(database::manga)?.sourceId val optimized = if (request.itemType == DbItemType.Manga) imageDataSaver?.resolve(page.url, page.headers.orEmpty(), sourceId, settings.features.imageDataSaver, download = true) else null var status = if (optimized != null) attemptDownload(optimized.url, optimized.headers, path, 0, { storedBytes = it }, shrink, onTransfer, imageTransfers, requireImageResponse = true) else 0 if (optimized == null || status != null) { if (optimized != null) imageDataSaver?.failed(optimized) status = attemptDownload(page.url, page.headers.orEmpty(), path, retries, { storedBytes = it }, shrink, onTransfer) } if (status == null) { if (request.itemType == DbItemType.Manga && settings.features.downloads.splitTallImages) { storedBytes = withContext(ioDispatcher) { splitPages.process(path, settings.features.downloads.splitImageHeight) } } onBytes(storedBytes) } status } } /** * Streams [url] to [targetPath] through a `.part` file, then writes its `.complete` marker. Exceptions, * empty bodies, 408, 429 and 5xx are retried up to [retries] times with backoff (Retry-After when sent); * any other status fails at once. Null once saved, else the last HTTP status (0 without a response). */ suspend fun attemptDownload( url: String, headers: Map, targetPath: String, retries: Int, onBytes: (Long) -> Unit, transform: ((ByteArray) -> ByteArray?)? = null, onTransfer: (Long) -> Unit = {}, transferService: ResumableDownload = transfers, requireImageResponse: Boolean = false, ): Int? = withContext(ioDispatcher) { val marker = "$targetPath.complete" val temporaryPath = "$targetPath.part" if (!safeDelete(marker) || files.exists(marker)) return@withContext 0 var status = 0 var retryAfter: String? = null for (attempt in 0..retries.coerceAtLeast(0)) { if (attempt > 0) delay(downloadRetryDelayMs(attempt, retryAfter)) awaitAllowedNetwork() val transfer = transferService.transfer(url, headers, temporaryPath, validateResponse = { head -> if (requireImageResponse) check(head.headers.header("Content-Type")?.startsWith("image/", true) == true) { "Optimizer did not return an image" } }, onProgress = onTransfer) var downloadedBytes = transfer.bytes val response = transfer.response status = response?.statusCode ?: 0 retryAfter = response?.headers?.header("Retry-After") if (transfer.complete) { transform?.let { shrink -> catchingNonCancellation { shrink(files.readBytesAsync(temporaryPath, MaxSplitImageBytes)) }.getOrNull()?.let { smaller -> files.writeBytesAsync(temporaryPath, smaller) downloadedBytes = smaller.size.toLong() } } } if (transfer.complete && promoteWithMarker(temporaryPath, targetPath, marker)) { safeDelete("$temporaryPath.resume") onTransfer(downloadedBytes) onBytes(downloadedBytes) return@withContext null } if (response != null && status !in 200..299 && !isRetryableDownloadStatus(status)) return@withContext status } status } /** The marker is only ever written after the page was promoted to its final name. */ suspend fun promoteWithMarker(temporaryPath: String, targetPath: String, marker: String): Boolean = catchingNonCancellation { files.promoteAsync(temporaryPath, targetPath) && run { files.writeBytesAsync(marker, ByteArray(0)) true } }.getOrDefault(false) private suspend fun safeDelete(path: String): Boolean = catchingNonCancellation { files.deleteRecursivelyAsync(path) }.getOrDefault(false) } internal fun padIndex(index: Int): String = index.toString().padStart(4, '0') private fun String.fileExtension(): String { val extension = substringBefore('?').substringBefore('#').substringAfterLast('/').substringAfterLast('.', "").lowercase() return if (extension in PageFileExtensions) ".$extension" else ".jpg" }