package eu.friedcutlet.yokan.services.files import java.io.File import java.io.RandomAccessFile import java.util.zip.ZipFile /** * Robust RAR archive (RAR4 & RAR5) extractor for CBR and RAR comic archives. * * Capabilities: * - Detects and extracts CBR archives that are actually renamed ZIP files. * - Parses RAR4 (Rar!\x1a\x07\x00) store/uncompressed image entries directly in pure Kotlin. * - Parses RAR5 (Rar!\x1a\x07\x01\x00) store/uncompressed image entries with vint headers. * - CLI fallback (unrar / 7z) for proprietary compressed RAR streams when available. */ object RarArchiveExtractor { private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif") fun isImageFile(name: String): Boolean = File(name).extension.lowercase() in imageExtensions fun isZipFile(file: File): Boolean { if (!file.exists() || file.length() < 4) return false return runCatching { file.inputStream().use { input -> val b0 = input.read() val b1 = input.read() val b2 = input.read() val b3 = input.read() b0 == 0x50 && b1 == 0x4B && ((b2 == 0x03 && b3 == 0x04) || (b2 == 0x05 && b3 == 0x06)) } }.getOrDefault(false) } fun isRar4(magic: ByteArray): Boolean = magic.size >= 7 && magic[0] == 0x52.toByte() && magic[1] == 0x61.toByte() && magic[2] == 0x72.toByte() && magic[3] == 0x21.toByte() && magic[4] == 0x1A.toByte() && magic[5] == 0x07.toByte() && magic[6] == 0x00.toByte() fun isRar5(magic: ByteArray): Boolean = magic.size >= 8 && magic[0] == 0x52.toByte() && magic[1] == 0x61.toByte() && magic[2] == 0x72.toByte() && magic[3] == 0x21.toByte() && magic[4] == 0x1A.toByte() && magic[5] == 0x07.toByte() && magic[6] == 0x01.toByte() && magic[7] == 0x00.toByte() /** * Extracts images from a RAR or CBR archive to [targetDir]. * Returns list of extracted image files sorted by filename. */ fun extract(archiveFile: File, targetDir: File): List { targetDir.mkdirs() if (!archiveFile.exists() || archiveFile.length() < 7) return emptyList() if (isZipFile(archiveFile)) { return extractDisguisedZip(archiveFile, targetDir) } val magic = ByteArray(8) runCatching { archiveFile.inputStream().use { it.read(magic) } } val entries = when { isRar4(magic) -> runCatching { extractRar4(archiveFile, targetDir) }.getOrDefault(emptyList()) isRar5(magic) -> runCatching { extractRar5(archiveFile, targetDir) }.getOrDefault(emptyList()) else -> emptyList() } if (entries.isNotEmpty()) { return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) } .map { it.second } } val cliExtracted = extractViaCli(archiveFile, targetDir) if (cliExtracted.isNotEmpty()) { return cliExtracted.sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } } return emptyList() } private fun extractDisguisedZip(archive: File, targetDir: File): List = runCatching { val result = mutableListOf() ZipFile(archive).use { zip -> val entries = zip.entries().toList() .filter { !it.isDirectory && isImageFile(it.name) } .filterNot { it.name.startsWith(".") || it.name.contains("/.") } .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) } entries.forEachIndexed { index, entry -> val safeName = "%04d_%s".format(index, File(entry.name).name) val output = File(targetDir, safeName) if (!output.exists()) { zip.getInputStream(entry).use { input -> output.outputStream().use { input.copyTo(it) } } } result += output } } result }.getOrDefault(emptyList()) private fun extractRar4(archiveFile: File, targetDir: File): List> { val extractedFiles = mutableListOf>() RandomAccessFile(archiveFile, "r").use { file -> file.seek(7) // Skip magic bytes var index = 0 while (file.filePointer + 7 <= file.length()) { val headerStart = file.filePointer file.readShortLE() // headCrc val headType = file.read() if (headType == -1) break val headFlags = file.readShortLE() val headSize = file.readShortLE() if (headSize < 7) break var addSize = 0L if ((headFlags and 0x8000) != 0) { addSize = file.readIntLE() } if (headType == 0x74) { // FILE_HEAD val packSizeLow = file.readIntLE() val unpSizeLow = file.readIntLE() file.read() // hostOs file.readIntLE() // fileCrc file.readIntLE() // fileTime file.read() // unpVer val method = file.read() // 0x30 = store val nameSize = file.readShortLE() file.readIntLE() // attr val packSize = if ((headFlags and 0x0100) != 0) { val highPack = file.readIntLE() file.readIntLE() // highUnp (highPack shl 32) or packSizeLow } else { packSizeLow } val nameBytes = ByteArray(nameSize.coerceAtLeast(0)) if (nameBytes.isNotEmpty()) file.readFully(nameBytes) val rawName = nameBytes.decodeToString() val headerEnd = headerStart + headSize if (file.filePointer < headerEnd) { file.seek(headerEnd) } if (method == 0x30 && isImageFile(rawName) && packSize > 0) { val safeName = "%04d_%s".format(index++, File(rawName).name) val output = File(targetDir, safeName) if (!output.exists()) { val buffer = ByteArray(packSize.toInt()) file.readFully(buffer) output.writeBytes(buffer) } else { file.skipBytes(packSize.toInt()) } extractedFiles += rawName to output } else { if (packSize > 0) file.skipBytes(packSize.toInt()) } } else if (headType == 0x7B) { // ENDARC_HEAD break } else { val headerEnd = headerStart + headSize if (file.filePointer < headerEnd) file.seek(headerEnd) if (addSize > 0) file.skipBytes(addSize.toInt()) } } } return extractedFiles } private fun extractRar5(archiveFile: File, targetDir: File): List> { val extractedFiles = mutableListOf>() RandomAccessFile(archiveFile, "r").use { file -> file.seek(8) // Skip 8-byte RAR5 magic var index = 0 while (file.filePointer < file.length()) { file.readIntLE() // header CRC32 val headerSize = readVint(file) if (headerSize <= 0L) break val headerDataStart = file.filePointer val headerType = readVint(file) val headerFlags = readVint(file) if ((headerFlags and 0x0001L) != 0L) { readVint(file) // extraSize } val dataSize = if ((headerFlags and 0x0002L) != 0L) readVint(file) else 0L if (headerType == 2L) { // FILE header val fileFlags = readVint(file) readVint(file) // unpackedSize readVint(file) // attributes if ((fileFlags and 0x0002L) != 0L) file.readIntLE() // mtime if ((fileFlags and 0x0004L) != 0L) file.readIntLE() // data CRC32 val compInfo = readVint(file) val method = (compInfo.toInt() shr 3) and 0x07 readVint(file) // hostOs val nameLength = readVint(file).toInt() val nameBytes = ByteArray(nameLength.coerceAtLeast(0)) if (nameBytes.isNotEmpty()) file.readFully(nameBytes) val rawName = nameBytes.decodeToString() val headerDataEnd = headerDataStart + headerSize if (file.filePointer < headerDataEnd) file.seek(headerDataEnd) val isDir = (fileFlags and 0x0001L) != 0L if (!isDir && method == 0 && isImageFile(rawName) && dataSize > 0) { val safeName = "%04d_%s".format(index++, File(rawName).name) val output = File(targetDir, safeName) if (!output.exists()) { val buffer = ByteArray(dataSize.toInt()) file.readFully(buffer) output.writeBytes(buffer) } else { file.skipBytes(dataSize.toInt()) } extractedFiles += rawName to output } else { if (dataSize > 0) file.skipBytes(dataSize.toInt()) } } else if (headerType == 5L) { // ENDARC break } else { val headerDataEnd = headerDataStart + headerSize if (file.filePointer < headerDataEnd) file.seek(headerDataEnd) if (dataSize > 0) file.skipBytes(dataSize.toInt()) } } } return extractedFiles } private fun extractViaCli(archive: File, targetDir: File): List { val commands = listOf( listOf("unrar", "e", "-y", "-o+", archive.absolutePath, targetDir.absolutePath), listOf("7z", "e", "-y", "-o${targetDir.absolutePath}", archive.absolutePath), listOf("7za", "e", "-y", "-o${targetDir.absolutePath}", archive.absolutePath), listOf("unar", "-o", targetDir.absolutePath, "-f", archive.absolutePath), ) for (cmd in commands) { val success = runCatching { val proc = ProcessBuilder(cmd) .redirectErrorStream(true) .start() val exited = proc.waitFor() exited == 0 }.getOrDefault(false) if (success) { val files = targetDir.walkTopDown() .filter { it.isFile && isImageFile(it.name) } .toList() if (files.isNotEmpty()) return files } } return emptyList() } private fun readVint(file: RandomAccessFile): Long { var result = 0L var shift = 0 for (i in 0 until 10) { val b = file.read() if (b == -1) break result = result or ((b.toLong() and 0x7f) shl shift) if ((b and 0x80) == 0) break shift += 7 } return result } private fun RandomAccessFile.readShortLE(): Int { val b0 = read() val b1 = read() if (b0 == -1 || b1 == -1) return -1 return (b0 and 0xff) or ((b1 and 0xff) shl 8) } private fun RandomAccessFile.readIntLE(): Long { val b0 = read() val b1 = read() val b2 = read() val b3 = read() if (b0 == -1 || b1 == -1 || b2 == -1 || b3 == -1) return -1L return ((b0.toLong() and 0xff)) or ((b1.toLong() and 0xff) shl 8) or ((b2.toLong() and 0xff) shl 16) or ((b3.toLong() and 0xff) shl 24) } }