RarArchiveExtractor.kt
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/RarArchiveExtractor.kt
1package eu.friedcutlet.yokan.services.files23import java.io.File4import java.io.RandomAccessFile5import java.util.zip.ZipFile67/**8 * Robust RAR archive (RAR4 & RAR5) extractor for CBR and RAR comic archives.9 *10 * Capabilities:11 * - Detects and extracts CBR archives that are actually renamed ZIP files.12 * - Parses RAR4 (Rar!\x1a\x07\x00) store/uncompressed image entries directly in pure Kotlin.13 * - Parses RAR5 (Rar!\x1a\x07\x01\x00) store/uncompressed image entries with vint headers.14 * - CLI fallback (unrar / 7z) for proprietary compressed RAR streams when available.15 */16object RarArchiveExtractor {17 private val imageExtensions = setOf("png", "jpg", "jpeg", "gif", "webp", "bmp", "avif")1819 fun isImageFile(name: String): Boolean =20 File(name).extension.lowercase() in imageExtensions2122 fun isZipFile(file: File): Boolean {23 if (!file.exists() || file.length() < 4) return false24 return runCatching {25 file.inputStream().use { input ->26 val b0 = input.read()27 val b1 = input.read()28 val b2 = input.read()29 val b3 = input.read()30 b0 == 0x50 && b1 == 0x4B && ((b2 == 0x03 && b3 == 0x04) || (b2 == 0x05 && b3 == 0x06))31 }32 }.getOrDefault(false)33 }3435 fun isRar4(magic: ByteArray): Boolean =36 magic.size >= 7 &&37 magic[0] == 0x52.toByte() &&38 magic[1] == 0x61.toByte() &&39 magic[2] == 0x72.toByte() &&40 magic[3] == 0x21.toByte() &&41 magic[4] == 0x1A.toByte() &&42 magic[5] == 0x07.toByte() &&43 magic[6] == 0x00.toByte()4445 fun isRar5(magic: ByteArray): Boolean =46 magic.size >= 8 &&47 magic[0] == 0x52.toByte() &&48 magic[1] == 0x61.toByte() &&49 magic[2] == 0x72.toByte() &&50 magic[3] == 0x21.toByte() &&51 magic[4] == 0x1A.toByte() &&52 magic[5] == 0x07.toByte() &&53 magic[6] == 0x01.toByte() &&54 magic[7] == 0x00.toByte()5556 /**57 * Extracts images from a RAR or CBR archive to [targetDir].58 * Returns list of extracted image files sorted by filename.59 */60 fun extract(archiveFile: File, targetDir: File): List<File> {61 targetDir.mkdirs()62 if (!archiveFile.exists() || archiveFile.length() < 7) return emptyList()6364 if (isZipFile(archiveFile)) {65 return extractDisguisedZip(archiveFile, targetDir)66 }6768 val magic = ByteArray(8)69 runCatching {70 archiveFile.inputStream().use { it.read(magic) }71 }7273 val entries = when {74 isRar4(magic) -> runCatching { extractRar4(archiveFile, targetDir) }.getOrDefault(emptyList())75 isRar5(magic) -> runCatching { extractRar5(archiveFile, targetDir) }.getOrDefault(emptyList())76 else -> emptyList()77 }7879 if (entries.isNotEmpty()) {80 return entries.sortedWith { left, right -> naturalPageNameComparator.compare(left.first, right.first) }81 .map { it.second }82 }8384 val cliExtracted = extractViaCli(archiveFile, targetDir)85 if (cliExtracted.isNotEmpty()) {86 return cliExtracted.sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }87 }8889 return emptyList()90 }9192 private fun extractDisguisedZip(archive: File, targetDir: File): List<File> = runCatching {93 val result = mutableListOf<File>()94 ZipFile(archive).use { zip ->95 val entries = zip.entries().toList()96 .filter { !it.isDirectory && isImageFile(it.name) }97 .filterNot { it.name.startsWith(".") || it.name.contains("/.") }98 .sortedWith { left, right -> naturalPageNameComparator.compare(left.name, right.name) }99 entries.forEachIndexed { index, entry ->100 val safeName = "%04d_%s".format(index, File(entry.name).name)101 val output = File(targetDir, safeName)102 if (!output.exists()) {103 zip.getInputStream(entry).use { input ->104 output.outputStream().use { input.copyTo(it) }105 }106 }107 result += output108 }109 }110 result111 }.getOrDefault(emptyList())112113 private fun extractRar4(archiveFile: File, targetDir: File): List<Pair<String, File>> {114 val extractedFiles = mutableListOf<Pair<String, File>>()115 RandomAccessFile(archiveFile, "r").use { file ->116 file.seek(7) // Skip magic bytes117 var index = 0118 while (file.filePointer + 7 <= file.length()) {119 val headerStart = file.filePointer120 file.readShortLE() // headCrc121 val headType = file.read()122 if (headType == -1) break123 val headFlags = file.readShortLE()124 val headSize = file.readShortLE()125 if (headSize < 7) break126127 var addSize = 0L128 if ((headFlags and 0x8000) != 0) {129 addSize = file.readIntLE()130 }131132 if (headType == 0x74) { // FILE_HEAD133 val packSizeLow = file.readIntLE()134 val unpSizeLow = file.readIntLE()135 file.read() // hostOs136 file.readIntLE() // fileCrc137 file.readIntLE() // fileTime138 file.read() // unpVer139 val method = file.read() // 0x30 = store140 val nameSize = file.readShortLE()141 file.readIntLE() // attr142143 val packSize = if ((headFlags and 0x0100) != 0) {144 val highPack = file.readIntLE()145 file.readIntLE() // highUnp146 (highPack shl 32) or packSizeLow147 } else {148 packSizeLow149 }150151 val nameBytes = ByteArray(nameSize.coerceAtLeast(0))152 if (nameBytes.isNotEmpty()) file.readFully(nameBytes)153 val rawName = nameBytes.decodeToString()154155 val headerEnd = headerStart + headSize156 if (file.filePointer < headerEnd) {157 file.seek(headerEnd)158 }159160 if (method == 0x30 && isImageFile(rawName) && packSize > 0) {161 val safeName = "%04d_%s".format(index++, File(rawName).name)162 val output = File(targetDir, safeName)163 if (!output.exists()) {164 val buffer = ByteArray(packSize.toInt())165 file.readFully(buffer)166 output.writeBytes(buffer)167 } else {168 file.skipBytes(packSize.toInt())169 }170 extractedFiles += rawName to output171 } else {172 if (packSize > 0) file.skipBytes(packSize.toInt())173 }174 } else if (headType == 0x7B) { // ENDARC_HEAD175 break176 } else {177 val headerEnd = headerStart + headSize178 if (file.filePointer < headerEnd) file.seek(headerEnd)179 if (addSize > 0) file.skipBytes(addSize.toInt())180 }181 }182 }183 return extractedFiles184 }185186 private fun extractRar5(archiveFile: File, targetDir: File): List<Pair<String, File>> {187 val extractedFiles = mutableListOf<Pair<String, File>>()188 RandomAccessFile(archiveFile, "r").use { file ->189 file.seek(8) // Skip 8-byte RAR5 magic190 var index = 0191 while (file.filePointer < file.length()) {192 file.readIntLE() // header CRC32193 val headerSize = readVint(file)194 if (headerSize <= 0L) break195 val headerDataStart = file.filePointer196 val headerType = readVint(file)197 val headerFlags = readVint(file)198199 if ((headerFlags and 0x0001L) != 0L) {200 readVint(file) // extraSize201 }202 val dataSize = if ((headerFlags and 0x0002L) != 0L) readVint(file) else 0L203204 if (headerType == 2L) { // FILE header205 val fileFlags = readVint(file)206 readVint(file) // unpackedSize207 readVint(file) // attributes208 if ((fileFlags and 0x0002L) != 0L) file.readIntLE() // mtime209 if ((fileFlags and 0x0004L) != 0L) file.readIntLE() // data CRC32210211 val compInfo = readVint(file)212 val method = (compInfo.toInt() shr 3) and 0x07213 readVint(file) // hostOs214 val nameLength = readVint(file).toInt()215 val nameBytes = ByteArray(nameLength.coerceAtLeast(0))216 if (nameBytes.isNotEmpty()) file.readFully(nameBytes)217 val rawName = nameBytes.decodeToString()218219 val headerDataEnd = headerDataStart + headerSize220 if (file.filePointer < headerDataEnd) file.seek(headerDataEnd)221222 val isDir = (fileFlags and 0x0001L) != 0L223 if (!isDir && method == 0 && isImageFile(rawName) && dataSize > 0) {224 val safeName = "%04d_%s".format(index++, File(rawName).name)225 val output = File(targetDir, safeName)226 if (!output.exists()) {227 val buffer = ByteArray(dataSize.toInt())228 file.readFully(buffer)229 output.writeBytes(buffer)230 } else {231 file.skipBytes(dataSize.toInt())232 }233 extractedFiles += rawName to output234 } else {235 if (dataSize > 0) file.skipBytes(dataSize.toInt())236 }237 } else if (headerType == 5L) { // ENDARC238 break239 } else {240 val headerDataEnd = headerDataStart + headerSize241 if (file.filePointer < headerDataEnd) file.seek(headerDataEnd)242 if (dataSize > 0) file.skipBytes(dataSize.toInt())243 }244 }245 }246 return extractedFiles247 }248249 private fun extractViaCli(archive: File, targetDir: File): List<File> {250 val commands = listOf(251 listOf("unrar", "e", "-y", "-o+", archive.absolutePath, targetDir.absolutePath),252 listOf("7z", "e", "-y", "-o${targetDir.absolutePath}", archive.absolutePath),253 listOf("7za", "e", "-y", "-o${targetDir.absolutePath}", archive.absolutePath),254 listOf("unar", "-o", targetDir.absolutePath, "-f", archive.absolutePath),255 )256 for (cmd in commands) {257 val success = runCatching {258 val proc = ProcessBuilder(cmd)259 .redirectErrorStream(true)260 .start()261 val exited = proc.waitFor()262 exited == 0263 }.getOrDefault(false)264265 if (success) {266 val files = targetDir.walkTopDown()267 .filter { it.isFile && isImageFile(it.name) }268 .toList()269 if (files.isNotEmpty()) return files270 }271 }272 return emptyList()273 }274275 private fun readVint(file: RandomAccessFile): Long {276 var result = 0L277 var shift = 0278 for (i in 0 until 10) {279 val b = file.read()280 if (b == -1) break281 result = result or ((b.toLong() and 0x7f) shl shift)282 if ((b and 0x80) == 0) break283 shift += 7284 }285 return result286 }287288 private fun RandomAccessFile.readShortLE(): Int {289 val b0 = read()290 val b1 = read()291 if (b0 == -1 || b1 == -1) return -1292 return (b0 and 0xff) or ((b1 and 0xff) shl 8)293 }294295 private fun RandomAccessFile.readIntLE(): Long {296 val b0 = read()297 val b1 = read()298 val b2 = read()299 val b3 = read()300 if (b0 == -1 || b1 == -1 || b2 == -1 || b3 == -1) return -1L301 return ((b0.toLong() and 0xff)) or302 ((b1.toLong() and 0xff) shl 8) or303 ((b2.toLong() and 0xff) shl 16) or304 ((b3.toLong() and 0xff) shl 24)305 }306}307