package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.database.DbPageUrl import eu.friedcutlet.yokan.util.PlatformLock import java.io.File import java.io.InputStream import java.net.URI import java.security.MessageDigest import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipOutputStream import java.util.zip.CRC32 internal enum class LocalArchiveType { Epub, Zip, Tar, Rar, Unknown } /** Archive kind from the display name, else the provider MIME type (SAF names can be opaque). */ internal fun localArchiveType(name: String, mimeType: String?): LocalArchiveType { val lowerName = name.lowercase() return when { lowerName.endsWith(".epub") || mimeType.equals("application/epub+zip", ignoreCase = true) -> LocalArchiveType.Epub lowerName.endsWith(".cbz") || lowerName.endsWith(".zip") || mimeType.equals("application/zip", ignoreCase = true) -> LocalArchiveType.Zip lowerName.endsWith(".cbt") || lowerName.endsWith(".tar") || mimeType.equals("application/x-tar", ignoreCase = true) || mimeType.equals("application/tar", ignoreCase = true) -> LocalArchiveType.Tar lowerName.endsWith(".cbr") || lowerName.endsWith(".rar") || mimeType.equals("application/x-rar-compressed", ignoreCase = true) || mimeType.equals("application/x-rar", ignoreCase = true) || mimeType.equals("application/vnd.rar", ignoreCase = true) || mimeType.equals("application/rar", ignoreCase = true) -> LocalArchiveType.Rar else -> LocalArchiveType.Unknown } } /** * File-backed archive support shared by desktop and Android: image folders, CBZ/ZIP, CBT/TAR * (streamed), CBR/RAR and EPUB. Pages extract once into `cacheRoot/archives/`; those * directories are kept least-recently-used within [extractedPagesBudgetBytes]. * * Memory ceiling: archive payloads are streamed and never retained; the metadata caches hold at * most 32 archives / 10k page URLs and 32 books / 2k chapters, and the last [MAX_OPEN_EPUBS] EPUBs * stay open. Android's SAF subclass overrides [withArchiveFile] to stage `content://` documents. */ internal open class JvmLocalArchiveService( protected val cacheRoot: String, // ponytail: fixed 1 GiB of extracted pages; make it a storage setting if users want a bigger offline cache. private val extractedPagesBudgetBytes: Long = 1L shl 30, ) : LocalArchiveService { /** An archive readable from disk. [name]/[mimeType] pick the kind because staged copies have temp names. */ protected class ArchiveFile( val file: File, val name: String, val mimeType: String?, val cacheKey: String, ) { val type: LocalArchiveType get() = localArchiveType(name, mimeType) } private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif") private val extracted = BoundedCache>(maxEntries = 32, maxWeight = 10_000) { it.size } private val epubChapterCache = BoundedCache>(maxEntries = 32, maxWeight = 2_000) { it.size } private val extractionRoot = File(cacheRoot, "archives").absoluteFile private val openEpubsLock = PlatformLock() private val openEpubs = LinkedHashMap() override fun invalidateIndexCache() = epubChapterCache.clear() /** Runs [block] against the on-disk archive for [path]; null when it is not a readable file. */ protected open fun withArchiveFile(path: String, block: (ArchiveFile) -> T): T? { val file = path.toUriFile() if (!file.isFile) return null return block(ArchiveFile(file, file.name, null, file.cacheKey())) } protected open fun withFreshArchiveFile(path: String, block: (ArchiveFile) -> T): T? = withArchiveFile(path, block) override fun listEpubChapters(archivePath: String): List { if (archivePath.isBlank()) return emptyList() return withArchiveFile(archivePath) { archive -> epubChapterCache[archive.cacheKey]?.let { return@withArchiveFile it } if (archive.type != LocalArchiveType.Epub) return@withArchiveFile emptyList() val chapters = runCatching { ZipFile(archive.file).use { zip -> readEpubManifest(zip::readEntry) } } .getOrDefault(emptyList()) epubChapterCache[archive.cacheKey] = chapters chapters } ?: emptyList() } override fun readEpubChapter(archivePath: String, index: Int): String { val href = listEpubChapters(archivePath).getOrNull(index)?.href ?: return "" return readEpubResource(archivePath, href)?.decodeToString().orEmpty() } override fun readEpubResource(archivePath: String, resourcePath: String): ByteArray? { if (archivePath.isBlank() || resourcePath.isBlank()) return null return withArchiveFile(archivePath) { archive -> runCatching { openEpub(archive).readEntry(resourcePath) }.getOrNull() } } /** * The book's ZipFile, kept open (LRU by [ArchiveFile.cacheKey]) so each chapter and image read of a * reading session skips reopening it. Library scans list chapters with a transient ZipFile instead. */ // ponytail: the last 4 books read stay open, so Windows refuses to delete/rename them until evicted, // and closing an evicted book fails a read still running on it (null). Add idle closing if either bites. private fun openEpub(archive: ArchiveFile): ZipFile = openEpubsLock.withLock { openEpubs.remove(archive.cacheKey)?.let { open -> openEpubs[archive.cacheKey] = open return@withLock open } ZipFile(archive.file).also { zip -> openEpubs[archive.cacheKey] = zip while (openEpubs.size > MAX_OPEN_EPUBS) openEpubs.remove(openEpubs.keys.first())?.close() } } override fun zipDirectoryToCbz(directoryPath: String, deleteSource: Boolean): String? { val source = File(directoryPath.removePrefix("file://")) if (!source.exists() || !source.isDirectory) return null val targetPath = "${source.absolutePath}.cbz" val target = File(targetPath) target.parentFile?.mkdirs() ZipOutputStream(target.outputStream().buffered()).use { zos -> val entries = source.walkTopDown() .filter { it.isFile && (it.extension.isImageExtension() || it.name == CHAPTER_METADATA_FILE) } .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } .toList() entries.forEach { file -> val entry = ZipEntry(file.name) entry.time = file.lastModified() zos.putNextEntry(entry) file.inputStream().use { it.copyTo(zos) } zos.closeEntry() } } if (deleteSource) source.deleteRecursively() return targetPath } override fun listPages(archivePath: String): List { if (archivePath.isBlank()) return emptyList() extracted[archivePath]?.takeIf { it.touchExtraction() }?.let { return it } val directory = archivePath.toUriFile() val pages = if (directory.isDirectory) { directory.listImageFiles().map { it.toPageUrl() } } else if (directory.isFile && directory.extension.isImageExtension()) { listOf(directory.toPageUrl()) } else { withArchiveFile(archivePath) { archive -> val extractedPages = when (archive.type) { LocalArchiveType.Zip -> extractZip(archive) LocalArchiveType.Tar -> extractTar(archive) LocalArchiveType.Rar -> extractRar(archive) LocalArchiveType.Epub, LocalArchiveType.Unknown -> emptyList() } if (extractedPages.isNotEmpty()) { pruneLeastRecentlyUsed(extractionRoot, keep = File(extractionRoot, archive.cacheKey), maxBytes = extractedPagesBudgetBytes) } extractedPages } ?: return emptyList() } extracted[archivePath] = pages return pages } override fun listPagesStrict(archivePath: String): List { require(archivePath.isNotBlank()) { "Archive path is blank" } val directory = archivePath.toUriFile() if (directory.isFile && directory.extension.isImageExtension()) { directory.validateStrictImage() return listOf(directory.toPageUrl()) } if (directory.isDirectory) { val files = directory.listFiles() ?: error("Cannot read image directory: $archivePath") val images = files.filter { it.isFile && it.extension.isImageExtension() } .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } images.forEach { image -> image.validateStrictImage() } return images.map { it.toPageUrl() } } return withFreshArchiveFile(archivePath) { archive -> val fresh = File(extractionRoot, "strict-${System.nanoTime()}-${archive.cacheKey}") check(fresh.mkdirs()) { "Cannot create archive extraction directory" } try { val pages = when (archive.type) { LocalArchiveType.Zip -> extractZip(archive, fresh, strict = true) LocalArchiveType.Tar -> extractTar(archive, fresh, strict = true) LocalArchiveType.Rar -> error("Strict RAR inventory is not supported") LocalArchiveType.Epub, LocalArchiveType.Unknown -> error("Unsupported image archive: ${archive.name}") } pruneLeastRecentlyUsed(extractionRoot, keep = fresh, maxBytes = extractedPagesBudgetBytes) pages } catch (failure: Throwable) { fresh.deleteRecursively() throw failure } } ?: error("Archive is not readable: $archivePath") } /** Marks the extraction directory behind cached [DbPageUrl]s used; false once it was pruned (re-extract). */ private fun List.touchExtraction(): Boolean { val directory = firstOrNull()?.let { page -> runCatching { File(URI(page.url)).parentFile }.getOrNull() } ?: return true if (directory.parentFile != extractionRoot) return true // image folders list their own files return directory.setLastModified(System.currentTimeMillis()) } private fun ArchiveFile.extractionDirectory(): File = File(extractionRoot, cacheKey).apply { mkdirs() setLastModified(System.currentTimeMillis()) } private fun extractRar(archive: ArchiveFile): List = RarArchiveExtractor.extract(archive.file, archive.extractionDirectory()).map { it.toPageUrl() } private fun extractZip(archive: ArchiveFile, target: File = archive.extractionDirectory(), strict: Boolean = false): List { ZipFile(archive.file).use { zip -> val entries = zip.entries().asSequence() .filter { !it.isDirectory && File(it.name).extension.isImageExtension() } .filterNot { it.name.startsWith(".") || it.name.contains("/.") } .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } .toList() return entries.mapIndexed { index, entry -> val output = File(target, "%04d_%s".format(index, File(entry.name).name)) if (strict || !output.exists()) { val partial = File(output.path + ".part") try { zip.getInputStream(entry).use { input -> partial.outputStream().use { output -> if (strict) input.copyZipEntryStrict(entry, output) else input.copyTo(output) } } check(partial.renameTo(output)) { "Cannot promote extracted image ${entry.name}" } if (strict) output.validateStrictImage() } catch (failure: Throwable) { partial.delete() output.delete() throw failure } } output.toPageUrl() } } } private fun extractTar(archive: ArchiveFile, target: File = archive.extractionDirectory(), strict: Boolean = false): List { val entries = mutableListOf>() archive.file.inputStream().buffered().use { stream -> var index = 0 while (true) { val header = readTarHeader(stream, strict) if (header == null) break val (entryName, size, type) = header val isImage = (type == '0' || type == 0.toChar()) && !entryName.startsWith(".") && !entryName.contains("/.") && File(entryName).extension.isImageExtension() val output = if (isImage) File(target, "%04d_%s".format(index++, File(entryName).name)) else null if (output != null && (strict || !output.exists())) { try { val partial = File(output.path + ".part") partial.outputStream().buffered().use { stream.transferTarEntry(size, it) } check(partial.renameTo(output)) { "Cannot promote extracted image $entryName" } if (strict) output.validateStrictImage() } catch (failure: Throwable) { output.delete() File(output.path + ".part").delete() throw failure } } else { stream.transferTarEntry(size) } if (strict && isImage && output != null && !output.isFile) error("Truncated TAR image $entryName") try { stream.transferTarEntry((512L - size % 512L) % 512L) } catch (failure: Throwable) { if (strict) throw failure break } if (output != null) entries += entryName to output } } return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) } .map { it.second.toPageUrl() } } private fun File.listImageFiles(): List = listFiles()?.filter { it.isFile && it.extension.isImageExtension() } ?.sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } .orEmpty() private fun File.cacheKey(): String { val digest = MessageDigest.getInstance("SHA-1") digest.update(absolutePath.encodeToByteArray()) digest.update(lastModified().toString().encodeToByteArray()) return digest.digest().toHexString() } private fun String.isImageExtension(): Boolean = lowercase() in imageExtensions private fun File.toPageUrl(): DbPageUrl = DbPageUrl(url = toURI().toString(), fileName = name) private companion object { const val MAX_OPEN_EPUBS = 4 } } private fun InputStream.copyZipEntryStrict(entry: ZipEntry, output: java.io.OutputStream) { require(entry.size >= 0 && entry.crc >= 0) { "ZIP image metadata is invalid: ${entry.name}" } val crc = CRC32() val buffer = ByteArray(64 * 1024) var copied = 0L while (true) { val count = read(buffer) if (count < 0) break output.write(buffer, 0, count) crc.update(buffer, 0, count) copied += count } check(copied == entry.size && crc.value == entry.crc) { "ZIP image is truncated or has a CRC mismatch: ${entry.name}" } } /** Decode with a pixel ceiling so corrupt entries and hostile dimensions cannot pass strict inventory. */ private fun File.validateStrictImage() { val maxPixels = 16_000_000L // Android host-JVM tests have an unmocked BitmapFactory stub; prefer real ImageIO there. val androidOptions = if (runCatching { Class.forName("javax.imageio.ImageIO") }.isSuccess) null else runCatching { Class.forName("android.graphics.BitmapFactory\$Options") }.getOrNull() if (androidOptions != null) { val factory = Class.forName("android.graphics.BitmapFactory") val options = androidOptions.getDeclaredConstructor().newInstance() androidOptions.getField("inJustDecodeBounds").setBoolean(options, true) val decodeFile = factory.getMethod("decodeFile", String::class.java, androidOptions) decodeFile.invoke(null, absolutePath, options) val width = androidOptions.getField("outWidth").getInt(options) val height = androidOptions.getField("outHeight").getInt(options) require(width > 0 && height > 0 && width.toLong() * height <= maxPixels) { "Unreadable or oversized image: $name" } androidOptions.getField("inJustDecodeBounds").setBoolean(options, false) androidOptions.getField("inSampleSize").setInt(options, maxOf(1, kotlin.math.ceil(kotlin.math.sqrt(width.toDouble() * height / maxPixels)).toInt())) val bitmap = checkNotNull(decodeFile.invoke(null, absolutePath, options)) { "Undecodable image: $name" } bitmap.javaClass.getMethod("recycle").invoke(bitmap) return } val imageIo = Class.forName("javax.imageio.ImageIO") val imageInput = imageIo.getMethod("createImageInputStream", Any::class.java).invoke(null, this) ?: error("Cannot inspect image: $name") try { val readers = imageIo.getMethod("getImageReaders", Any::class.java).invoke(null, imageInput) as Iterator<*> require(readers.hasNext()) { "Undecodable image: $name" } val reader = checkNotNull(readers.next()) val readerApi = Class.forName("javax.imageio.ImageReader") try { readerApi.getMethod("setInput", Any::class.java).invoke(reader, imageInput) val intClass = Int::class.javaPrimitiveType ?: error("Primitive int class is unavailable") val width = readerApi.getMethod("getWidth", intClass).invoke(reader, 0) as Int val height = readerApi.getMethod("getHeight", intClass).invoke(reader, 0) as Int require(width > 0 && height > 0 && width.toLong() * height <= maxPixels) { "Unreadable or oversized image: $name" } val bitmap = checkNotNull(readerApi.getMethod("read", intClass).invoke(reader, 0)) { "Undecodable image: $name" } bitmap.javaClass.getMethod("flush").invoke(bitmap) } finally { readerApi.getMethod("dispose").invoke(reader) } } finally { Class.forName("javax.imageio.stream.ImageInputStream").getMethod("close").invoke(imageInput) } } /** Exact entry first, then the first entry whose name ends with the path (EPUB hrefs are often partial). */ private fun ZipFile.readEntry(path: String): ByteArray? { val normalized = normalizeArchivePath(path).takeIf(String::isNotEmpty) ?: return null val entry = getEntry(normalized) ?: entries().asSequence().firstOrNull { it.name.replace('\\', '/').endsWith(normalized) } ?: return null return getInputStream(entry).use { it.readBytes() } } /** * Deletes the least recently modified children of [root] (never [keep]) until at most [maxEntries] * remain within [maxBytes]. Callers bump an entry's mtime on use, which makes this an LRU. */ internal fun pruneLeastRecentlyUsed(root: File, keep: File, maxBytes: Long, maxEntries: Int = Int.MAX_VALUE) { val entries = root.listFiles().orEmpty() .map { entry -> Triple(entry, entry.lastModified(), entry.walkTopDown().filter(File::isFile).sumOf(File::length)) } .sortedBy { it.second } var count = entries.size var bytes = entries.sumOf { it.third } for ((entry, _, size) in entries) { if (count <= maxEntries && bytes <= maxBytes) break if (entry == keep) continue entry.deleteRecursively() count-- bytes -= size } } private data class TarHeader(val name: String, val size: Long, val type: Char) private fun readTarHeader(stream: InputStream, strict: Boolean = false): TarHeader? { val header = ByteArray(512) if (!stream.readFully(header)) { if (strict) throw java.io.EOFException("Truncated TAR header") return null } if (header.all { it == 0.toByte() }) return null val name = header.sliceToString(0, 100) if (name.isEmpty()) return null val size = header.sliceToString(124, 12).toLongOrNull(8) ?: 0L return TarHeader(name, size, header[156].toInt().toChar()) } private fun ByteArray.sliceToString(start: Int, length: Int): String { val end = (start + length).coerceAtMost(size) val trimmed = sliceArray(start until end).takeWhile { it != 0.toByte() }.toByteArray() return trimmed.decodeToString().trim() } private fun InputStream.readFully(buffer: ByteArray): Boolean { var offset = 0 while (offset < buffer.size) { val read = read(buffer, offset, buffer.size - offset) if (read == -1) return false offset += read } return true }