Yokan / rebuild
Course 1 8624561

JvmLocalArchiveService.kt

composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalArchiveService.kt

implementation429 lines
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.database.DbPageUrl4import eu.friedcutlet.yokan.util.PlatformLock5import java.io.File6import java.io.InputStream7import java.net.URI8import java.security.MessageDigest9import java.util.zip.ZipEntry10import java.util.zip.ZipFile11import java.util.zip.ZipOutputStream12import java.util.zip.CRC321314internal enum class LocalArchiveType { Epub, Zip, Tar, Rar, Unknown }1516/** Archive kind from the display name, else the provider MIME type (SAF names can be opaque). */17internal fun localArchiveType(name: String, mimeType: String?): LocalArchiveType {18    val lowerName = name.lowercase()19    return when {20        lowerName.endsWith(".epub") || mimeType.equals("application/epub+zip", ignoreCase = true) ->21            LocalArchiveType.Epub22        lowerName.endsWith(".cbz") || lowerName.endsWith(".zip") ||23            mimeType.equals("application/zip", ignoreCase = true) -> LocalArchiveType.Zip24        lowerName.endsWith(".cbt") || lowerName.endsWith(".tar") ||25            mimeType.equals("application/x-tar", ignoreCase = true) ||26            mimeType.equals("application/tar", ignoreCase = true) -> LocalArchiveType.Tar27        lowerName.endsWith(".cbr") || lowerName.endsWith(".rar") ||28            mimeType.equals("application/x-rar-compressed", ignoreCase = true) ||29            mimeType.equals("application/x-rar", ignoreCase = true) ||30            mimeType.equals("application/vnd.rar", ignoreCase = true) ||31            mimeType.equals("application/rar", ignoreCase = true) -> LocalArchiveType.Rar32        else -> LocalArchiveType.Unknown33    }34}3536/**37 * File-backed archive support shared by desktop and Android: image folders, CBZ/ZIP, CBT/TAR38 * (streamed), CBR/RAR and EPUB. Pages extract once into `cacheRoot/archives/<key>`; those39 * directories are kept least-recently-used within [extractedPagesBudgetBytes].40 *41 * Memory ceiling: archive payloads are streamed and never retained; the metadata caches hold at42 * most 32 archives / 10k page URLs and 32 books / 2k chapters, and the last [MAX_OPEN_EPUBS] EPUBs43 * stay open. Android's SAF subclass overrides [withArchiveFile] to stage `content://` documents.44 */45internal open class JvmLocalArchiveService(46    protected val cacheRoot: String,47    // ponytail: fixed 1 GiB of extracted pages; make it a storage setting if users want a bigger offline cache.48    private val extractedPagesBudgetBytes: Long = 1L shl 30,49) : LocalArchiveService {50    /** An archive readable from disk. [name]/[mimeType] pick the kind because staged copies have temp names. */51    protected class ArchiveFile(52        val file: File,53        val name: String,54        val mimeType: String?,55        val cacheKey: String,56    ) {57        val type: LocalArchiveType get() = localArchiveType(name, mimeType)58    }5960    private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")61    private val extracted = BoundedCache<String, List<DbPageUrl>>(maxEntries = 32, maxWeight = 10_000) { it.size }62    private val epubChapterCache = BoundedCache<String, List<LocalEpubChapter>>(maxEntries = 32, maxWeight = 2_000) { it.size }63    private val extractionRoot = File(cacheRoot, "archives").absoluteFile64    private val openEpubsLock = PlatformLock()65    private val openEpubs = LinkedHashMap<String, ZipFile>()6667    override fun invalidateIndexCache() = epubChapterCache.clear()6869    /** Runs [block] against the on-disk archive for [path]; null when it is not a readable file. */70    protected open fun <T> withArchiveFile(path: String, block: (ArchiveFile) -> T): T? {71        val file = path.toUriFile()72        if (!file.isFile) return null73        return block(ArchiveFile(file, file.name, null, file.cacheKey()))74    }7576    protected open fun <T> withFreshArchiveFile(path: String, block: (ArchiveFile) -> T): T? =77        withArchiveFile(path, block)7879    override fun listEpubChapters(archivePath: String): List<LocalEpubChapter> {80        if (archivePath.isBlank()) return emptyList()81        return withArchiveFile(archivePath) { archive ->82            epubChapterCache[archive.cacheKey]?.let { return@withArchiveFile it }83            if (archive.type != LocalArchiveType.Epub) return@withArchiveFile emptyList()84            val chapters = runCatching { ZipFile(archive.file).use { zip -> readEpubManifest(zip::readEntry) } }85                .getOrDefault(emptyList())86            epubChapterCache[archive.cacheKey] = chapters87            chapters88        } ?: emptyList()89    }9091    override fun readEpubChapter(archivePath: String, index: Int): String {92        val href = listEpubChapters(archivePath).getOrNull(index)?.href ?: return ""93        return readEpubResource(archivePath, href)?.decodeToString().orEmpty()94    }9596    override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? {97        if (archivePath.isBlank() || resourcePath.isBlank()) return null98        return withArchiveFile(archivePath) { archive ->99            runCatching { openEpub(archive).readEntry(resourcePath) }.getOrNull()100        }101    }102103    /**104     * The book's ZipFile, kept open (LRU by [ArchiveFile.cacheKey]) so each chapter and image read of a105     * reading session skips reopening it. Library scans list chapters with a transient ZipFile instead.106     */107    // ponytail: the last 4 books read stay open, so Windows refuses to delete/rename them until evicted,108    // and closing an evicted book fails a read still running on it (null). Add idle closing if either bites.109    private fun openEpub(archive: ArchiveFile): ZipFile = openEpubsLock.withLock {110        openEpubs.remove(archive.cacheKey)?.let { open ->111            openEpubs[archive.cacheKey] = open112            return@withLock open113        }114        ZipFile(archive.file).also { zip ->115            openEpubs[archive.cacheKey] = zip116            while (openEpubs.size > MAX_OPEN_EPUBS) openEpubs.remove(openEpubs.keys.first())?.close()117        }118    }119120    override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? {121        val source = File(directoryPath.removePrefix("file://"))122        if (!source.exists() || !source.isDirectory) return null123        val targetPath = "${source.absolutePath}.cbz"124        val target = File(targetPath)125        target.parentFile?.mkdirs()126        ZipOutputStream(target.outputStream().buffered()).use { zos ->127            val entries = source.walkTopDown()128                .filter { it.isFile && (it.extension.isImageExtension() || it.name == CHAPTER_METADATA_FILE) }129                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }130                .toList()131            entries.forEach { file ->132                val entry = ZipEntry(file.name)133                entry.time = file.lastModified()134                zos.putNextEntry(entry)135                file.inputStream().use { it.copyTo(zos) }136                zos.closeEntry()137            }138        }139        if (deleteSource) source.deleteRecursively()140        return targetPath141    }142143    override fun listPages(archivePath: String): List<DbPageUrl> {144        if (archivePath.isBlank()) return emptyList()145        extracted[archivePath]?.takeIf { it.touchExtraction() }?.let { return it }146        val directory = archivePath.toUriFile()147        val pages = if (directory.isDirectory) {148            directory.listImageFiles().map { it.toPageUrl() }149        } else if (directory.isFile && directory.extension.isImageExtension()) {150            listOf(directory.toPageUrl())151        } else {152            withArchiveFile(archivePath) { archive ->153                val extractedPages = when (archive.type) {154                    LocalArchiveType.Zip -> extractZip(archive)155                    LocalArchiveType.Tar -> extractTar(archive)156                    LocalArchiveType.Rar -> extractRar(archive)157                    LocalArchiveType.Epub, LocalArchiveType.Unknown -> emptyList()158                }159                if (extractedPages.isNotEmpty()) {160                    pruneLeastRecentlyUsed(extractionRoot, keep = File(extractionRoot, archive.cacheKey), maxBytes = extractedPagesBudgetBytes)161                }162                extractedPages163            } ?: return emptyList()164        }165        extracted[archivePath] = pages166        return pages167    }168169    override fun listPagesStrict(archivePath: String): List<DbPageUrl> {170        require(archivePath.isNotBlank()) { "Archive path is blank" }171        val directory = archivePath.toUriFile()172        if (directory.isFile && directory.extension.isImageExtension()) {173            directory.validateStrictImage()174            return listOf(directory.toPageUrl())175        }176        if (directory.isDirectory) {177            val files = directory.listFiles() ?: error("Cannot read image directory: $archivePath")178            val images = files.filter { it.isFile && it.extension.isImageExtension() }179                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }180            images.forEach { image ->181                image.validateStrictImage()182            }183            return images.map { it.toPageUrl() }184        }185        return withFreshArchiveFile(archivePath) { archive ->186            val fresh = File(extractionRoot, "strict-${System.nanoTime()}-${archive.cacheKey}")187            check(fresh.mkdirs()) { "Cannot create archive extraction directory" }188            try {189                val pages = when (archive.type) {190                    LocalArchiveType.Zip -> extractZip(archive, fresh, strict = true)191                    LocalArchiveType.Tar -> extractTar(archive, fresh, strict = true)192                    LocalArchiveType.Rar -> error("Strict RAR inventory is not supported")193                    LocalArchiveType.Epub, LocalArchiveType.Unknown -> error("Unsupported image archive: ${archive.name}")194                }195                pruneLeastRecentlyUsed(extractionRoot, keep = fresh, maxBytes = extractedPagesBudgetBytes)196                pages197            } catch (failure: Throwable) {198                fresh.deleteRecursively()199                throw failure200            }201        } ?: error("Archive is not readable: $archivePath")202    }203204    /** Marks the extraction directory behind cached [DbPageUrl]s used; false once it was pruned (re-extract). */205    private fun List<DbPageUrl>.touchExtraction(): Boolean {206        val directory = firstOrNull()?.let { page -> runCatching { File(URI(page.url)).parentFile }.getOrNull() } ?: return true207        if (directory.parentFile != extractionRoot) return true // image folders list their own files208        return directory.setLastModified(System.currentTimeMillis())209    }210211    private fun ArchiveFile.extractionDirectory(): File =212        File(extractionRoot, cacheKey).apply {213            mkdirs()214            setLastModified(System.currentTimeMillis())215        }216217    private fun extractRar(archive: ArchiveFile): List<DbPageUrl> =218        RarArchiveExtractor.extract(archive.file, archive.extractionDirectory()).map { it.toPageUrl() }219220    private fun extractZip(archive: ArchiveFile, target: File = archive.extractionDirectory(), strict: Boolean = false): List<DbPageUrl> {221        ZipFile(archive.file).use { zip ->222            val entries = zip.entries().asSequence()223                .filter { !it.isDirectory && File(it.name).extension.isImageExtension() }224                .filterNot { it.name.startsWith(".") || it.name.contains("/.") }225                .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }226                .toList()227            return entries.mapIndexed { index, entry ->228                val output = File(target, "%04d_%s".format(index, File(entry.name).name))229                if (strict || !output.exists()) {230                    val partial = File(output.path + ".part")231                    try {232                        zip.getInputStream(entry).use { input ->233                            partial.outputStream().use { output ->234                                if (strict) input.copyZipEntryStrict(entry, output) else input.copyTo(output)235                            }236                        }237                        check(partial.renameTo(output)) { "Cannot promote extracted image ${entry.name}" }238                        if (strict) output.validateStrictImage()239                    } catch (failure: Throwable) {240                        partial.delete()241                        output.delete()242                        throw failure243                    }244                }245                output.toPageUrl()246            }247        }248    }249250    private fun extractTar(archive: ArchiveFile, target: File = archive.extractionDirectory(), strict: Boolean = false): List<DbPageUrl> {251        val entries = mutableListOf<Pair<String, File>>()252        archive.file.inputStream().buffered().use { stream ->253            var index = 0254            while (true) {255                val header = readTarHeader(stream, strict)256                if (header == null) break257                val (entryName, size, type) = header258                val isImage = (type == '0' || type == 0.toChar()) &&259                    !entryName.startsWith(".") && !entryName.contains("/.") &&260                    File(entryName).extension.isImageExtension()261                val output = if (isImage) File(target, "%04d_%s".format(index++, File(entryName).name)) else null262                if (output != null && (strict || !output.exists())) {263                    try {264                        val partial = File(output.path + ".part")265                        partial.outputStream().buffered().use { stream.transferTarEntry(size, it) }266                        check(partial.renameTo(output)) { "Cannot promote extracted image $entryName" }267                        if (strict) output.validateStrictImage()268                    } catch (failure: Throwable) {269                        output.delete()270                        File(output.path + ".part").delete()271                        throw failure272                    }273                } else {274                    stream.transferTarEntry(size)275                }276                if (strict && isImage && output != null && !output.isFile) error("Truncated TAR image $entryName")277                try {278                    stream.transferTarEntry((512L - size % 512L) % 512L)279                } catch (failure: Throwable) {280                    if (strict) throw failure281                    break282                }283                if (output != null) entries += entryName to output284            }285        }286        return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) }287            .map { it.second.toPageUrl() }288    }289290    private fun File.listImageFiles(): List<File> =291        listFiles()?.filter { it.isFile && it.extension.isImageExtension() }292            ?.sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }293            .orEmpty()294295    private fun File.cacheKey(): String {296        val digest = MessageDigest.getInstance("SHA-1")297        digest.update(absolutePath.encodeToByteArray())298        digest.update(lastModified().toString().encodeToByteArray())299        return digest.digest().toHexString()300    }301302    private fun String.isImageExtension(): Boolean = lowercase() in imageExtensions303304    private fun File.toPageUrl(): DbPageUrl = DbPageUrl(url = toURI().toString(), fileName = name)305306    private companion object {307        const val MAX_OPEN_EPUBS = 4308    }309}310311private fun InputStream.copyZipEntryStrict(entry: ZipEntry, output: java.io.OutputStream) {312    require(entry.size >= 0 && entry.crc >= 0) { "ZIP image metadata is invalid: ${entry.name}" }313    val crc = CRC32()314    val buffer = ByteArray(64 * 1024)315    var copied = 0L316    while (true) {317        val count = read(buffer)318        if (count < 0) break319        output.write(buffer, 0, count)320        crc.update(buffer, 0, count)321        copied += count322    }323    check(copied == entry.size && crc.value == entry.crc) { "ZIP image is truncated or has a CRC mismatch: ${entry.name}" }324}325326/** Decode with a pixel ceiling so corrupt entries and hostile dimensions cannot pass strict inventory. */327private fun File.validateStrictImage() {328    val maxPixels = 16_000_000L329    // Android host-JVM tests have an unmocked BitmapFactory stub; prefer real ImageIO there.330    val androidOptions = if (runCatching { Class.forName("javax.imageio.ImageIO") }.isSuccess) null331        else runCatching { Class.forName("android.graphics.BitmapFactory\$Options") }.getOrNull()332    if (androidOptions != null) {333        val factory = Class.forName("android.graphics.BitmapFactory")334        val options = androidOptions.getDeclaredConstructor().newInstance()335        androidOptions.getField("inJustDecodeBounds").setBoolean(options, true)336        val decodeFile = factory.getMethod("decodeFile", String::class.java, androidOptions)337        decodeFile.invoke(null, absolutePath, options)338        val width = androidOptions.getField("outWidth").getInt(options)339        val height = androidOptions.getField("outHeight").getInt(options)340        require(width > 0 && height > 0 && width.toLong() * height <= maxPixels) { "Unreadable or oversized image: $name" }341        androidOptions.getField("inJustDecodeBounds").setBoolean(options, false)342        androidOptions.getField("inSampleSize").setInt(options, maxOf(1, kotlin.math.ceil(kotlin.math.sqrt(width.toDouble() * height / maxPixels)).toInt()))343        val bitmap = checkNotNull(decodeFile.invoke(null, absolutePath, options)) { "Undecodable image: $name" }344        bitmap.javaClass.getMethod("recycle").invoke(bitmap)345        return346    }347348    val imageIo = Class.forName("javax.imageio.ImageIO")349    val imageInput = imageIo.getMethod("createImageInputStream", Any::class.java).invoke(null, this)350        ?: error("Cannot inspect image: $name")351    try {352        val readers = imageIo.getMethod("getImageReaders", Any::class.java).invoke(null, imageInput) as Iterator<*>353        require(readers.hasNext()) { "Undecodable image: $name" }354        val reader = checkNotNull(readers.next())355        val readerApi = Class.forName("javax.imageio.ImageReader")356        try {357            readerApi.getMethod("setInput", Any::class.java).invoke(reader, imageInput)358            val intClass = Int::class.javaPrimitiveType ?: error("Primitive int class is unavailable")359            val width = readerApi.getMethod("getWidth", intClass).invoke(reader, 0) as Int360            val height = readerApi.getMethod("getHeight", intClass).invoke(reader, 0) as Int361            require(width > 0 && height > 0 && width.toLong() * height <= maxPixels) { "Unreadable or oversized image: $name" }362            val bitmap = checkNotNull(readerApi.getMethod("read", intClass).invoke(reader, 0)) { "Undecodable image: $name" }363            bitmap.javaClass.getMethod("flush").invoke(bitmap)364        } finally {365            readerApi.getMethod("dispose").invoke(reader)366        }367    } finally {368        Class.forName("javax.imageio.stream.ImageInputStream").getMethod("close").invoke(imageInput)369    }370}371372/** Exact entry first, then the first entry whose name ends with the path (EPUB hrefs are often partial). */373private fun ZipFile.readEntry(path: String): ByteArray? {374    val normalized = normalizeArchivePath(path).takeIf(String::isNotEmpty) ?: return null375    val entry = getEntry(normalized)376        ?: entries().asSequence().firstOrNull { it.name.replace('\\', '/').endsWith(normalized) }377        ?: return null378    return getInputStream(entry).use { it.readBytes() }379}380381/**382 * Deletes the least recently modified children of [root] (never [keep]) until at most [maxEntries]383 * remain within [maxBytes]. Callers bump an entry's mtime on use, which makes this an LRU.384 */385internal fun pruneLeastRecentlyUsed(root: File, keep: File, maxBytes: Long, maxEntries: Int = Int.MAX_VALUE) {386    val entries = root.listFiles().orEmpty()387        .map { entry -> Triple(entry, entry.lastModified(), entry.walkTopDown().filter(File::isFile).sumOf(File::length)) }388        .sortedBy { it.second }389    var count = entries.size390    var bytes = entries.sumOf { it.third }391    for ((entry, _, size) in entries) {392        if (count <= maxEntries && bytes <= maxBytes) break393        if (entry == keep) continue394        entry.deleteRecursively()395        count--396        bytes -= size397    }398}399400private data class TarHeader(val name: String, val size: Long, val type: Char)401402private fun readTarHeader(stream: InputStream, strict: Boolean = false): TarHeader? {403    val header = ByteArray(512)404    if (!stream.readFully(header)) {405        if (strict) throw java.io.EOFException("Truncated TAR header")406        return null407    }408    if (header.all { it == 0.toByte() }) return null409    val name = header.sliceToString(0, 100)410    if (name.isEmpty()) return null411    val size = header.sliceToString(124, 12).toLongOrNull(8) ?: 0L412    return TarHeader(name, size, header[156].toInt().toChar())413}414415private fun ByteArray.sliceToString(start: Int, length: Int): String {416    val end = (start + length).coerceAtMost(size)417    val trimmed = sliceArray(start until end).takeWhile { it != 0.toByte() }.toByteArray()418    return trimmed.decodeToString().trim()419}420421private fun InputStream.readFully(buffer: ByteArray): Boolean {422    var offset = 0423    while (offset < buffer.size) {424        val read = read(buffer, offset, buffer.size - offset)425        if (read == -1) return false426        offset += read427    }428    return true429}430

Search chapters, reference and source filenames.