IosArchivePagesTest.kt
composeApp/src/iosTest/kotlin/eu/friedcutlet/yokan/services/files/IosArchivePagesTest.kt
1package eu.friedcutlet.yokan.services.files23import kotlinx.cinterop.ExperimentalForeignApi4import platform.Foundation.NSDate5import platform.Foundation.NSFileManager6import platform.Foundation.NSFileModificationDate7import platform.Foundation.dateWithTimeIntervalSince19708import kotlin.random.Random9import kotlin.test.Test10import kotlin.test.assertContentEquals11import kotlin.test.assertEquals12import kotlin.test.assertFalse13import kotlin.test.assertNotNull14import kotlin.test.assertTrue1516class IosArchivePagesTest {17 @Test18 fun zipsDirectoryAndExtractsCbzPages() {19 val files = createPlatformLocalFileService()20 val dir = "${files.cacheRoot}/cbz-src-${Random.nextLong()}"21 val pageA = byteArrayOf(1, 2, 3, 4)22 val pageB = byteArrayOf(9, 8, 7)23 files.writeBytes("$dir/002.png", pageB)24 files.writeBytes("$dir/001.jpg", pageA)25 files.writeBytes("$dir/notes.txt", byteArrayOf(0))26 files.writeBytes("$dir/001.jpg.complete", ByteArray(0))27 files.writeBytes("$dir/$CHAPTER_METADATA_FILE", "{}".encodeToByteArray())28 var cbz: String? = null2930 try {31 val archives = createPlatformLocalArchiveService()32 cbz = archives.zipDirectoryToCbz(dir, deleteSource = false)33 assertNotNull(cbz)34 assertTrue(files.exists(cbz))35 assertEquals(setOf("001.jpg", "002.png", CHAPTER_METADATA_FILE), IosZipArchive.openFile(cbz)?.entryNames?.toSet())3637 val pages = archives.listPages(cbz)38 assertEquals(listOf("0000_001.jpg", "0001_002.png"), pages.map { it.fileName })39 assertContentEquals(pageA, files.readBytes(pages[0].url))40 assertContentEquals(pageB, files.readBytes(pages[1].url))41 } finally {42 files.deleteRecursively(dir)43 cbz?.let(files::deleteRecursively)44 }45 }4647 @Test48 fun extractsTarPages() {49 val files = createPlatformLocalFileService()50 val tarPath = "${files.cacheRoot}/pages-${Random.nextLong()}.cbt"51 val image = byteArrayOf(5, 6, 7, 8, 9)52 files.writeBytes(tarPath, tarWith("p1.png" to image, "skip.txt" to byteArrayOf(1)))5354 try {55 val archives = createPlatformLocalArchiveService()56 val pages = archives.listPages(tarPath)57 assertEquals(listOf("0000_p1.png"), pages.map { it.fileName })58 assertContentEquals(image, files.readBytes(pages.single().url))59 } finally {60 files.deleteRecursively(tarPath)61 }62 }6364 @Test65 fun strictInventoryReextractsReplacedCbzAtSamePath() {66 val files = createPlatformLocalFileService()67 val archive = "${files.cacheRoot}/strict ${Random.nextLong()} %20 #.cbz"68 try {69 val archives = createPlatformLocalArchiveService()70 files.writeBytes(archive, buildStoredZip(listOf("nested/page%20#one.jpg" to byteArrayOf(1))))71 val first = archives.listPagesStrict(archive).single()72 assertTrue(first.url.contains("%2520%23"), first.url)73 assertContentEquals(byteArrayOf(1), files.readBytes(first.url))74 files.writeBytes(archive, buildStoredZip(listOf("nested/page%20#one.jpg" to byteArrayOf(2))))75 val second = archives.listPagesStrict(archive).single()76 assertContentEquals(byteArrayOf(2), files.readBytes(second.url))77 assertFalse(first.url == second.url)78 } finally {79 files.deleteRecursively(archive)80 }81 }8283 @Test84 fun strictInventoryRejectsMalformedSecondZipDirectoryRecord() {85 val files = createPlatformLocalFileService()86 val archive = "${files.cacheRoot}/malformed-${Random.nextLong()}.cbz"87 try {88 val bytes = buildStoredZip(listOf("one.jpg" to byteArrayOf(1), "two.jpg" to byteArrayOf(2)))89 val signature = byteArrayOf(0x50, 0x4b, 0x01, 0x02)90 val first = bytes.indexOfBytes(signature)91 val second = bytes.indexOfBytes(signature, first + signature.size)92 check(first >= 0 && second >= 0)93 bytes[second] = 094 files.writeBytes(archive, bytes)95 kotlin.test.assertFails { createPlatformLocalArchiveService().listPagesStrict(archive) }96 } finally {97 files.deleteRecursively(archive)98 }99 }100101 @Test102 fun strictInventoryRejectsUnderreportedEocdEntryCountAndDirectoryExtent() {103 val files = createPlatformLocalFileService()104 val root = "${files.cacheRoot}/eocd-${Random.nextLong()}"105 val archives = createPlatformLocalArchiveService()106 val entries = listOf("one.jpg" to byteArrayOf(1), "two.jpg" to byteArrayOf(2))107 val original = buildStoredZip(entries)108 val eocd = original.size - 22109 val firstRecordSize = 46 + "one.jpg".encodeToByteArray().size110111 try {112 // Tamper total count and central size, leaving the per-disk count unchanged.113 val countMismatch = original.copyOf().apply {114 putLe16(eocd + 10, 1)115 putLe32(eocd + 12, firstRecordSize)116 }117 val countMismatchPath = "$root-count.cbz"118 files.writeBytes(countMismatchPath, countMismatch)119 kotlin.test.assertFails { archives.listPagesStrict(countMismatchPath) }120121 // Matching the per-disk count must still fail because the claimed directory no longer reaches EOCD.122 val extentMismatch = original.copyOf().apply {123 putLe16(eocd + 8, 1)124 putLe16(eocd + 10, 1)125 putLe32(eocd + 12, firstRecordSize)126 }127 val extentMismatchPath = "$root-extent.cbz"128 files.writeBytes(extentMismatchPath, extentMismatch)129 kotlin.test.assertFails { archives.listPagesStrict(extentMismatchPath) }130131 // A well-formed ZIP comment remains accepted by strict inventory.132 val withComment = original.copyOf(original.size + 4).apply {133 putLe16(eocd + 20, 4)134 "note".encodeToByteArray().copyInto(this, original.size)135 }136 val commentedPath = "$root-comment.cbz"137 files.writeBytes(commentedPath, withComment)138 assertEquals(2, archives.listPagesStrict(commentedPath).size)139 } finally {140 files.deleteRecursively(root)141 files.deleteRecursively("$root-count.cbz")142 files.deleteRecursively("$root-extent.cbz")143 files.deleteRecursively("$root-comment.cbz")144 }145 }146147 @Test148 fun strictInventoryRejectsTruncatedTarImage() {149 val files = createPlatformLocalFileService()150 val archive = "${files.cacheRoot}/truncated-${Random.nextLong()}.cbt"151 try {152 val complete = tarWith("page.png" to byteArrayOf(1, 2, 3, 4, 5))153 files.writeBytes(archive, complete.copyOf(512 + 2))154 kotlin.test.assertFails { createPlatformLocalArchiveService().listPagesStrict(archive) }155 } finally {156 files.deleteRecursively(archive)157 }158 }159160 @OptIn(ExperimentalForeignApi::class)161 @Test162 fun evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget() {163 val files = createPlatformLocalFileService()164 val root = "${files.cacheRoot}/lru-${Random.nextLong()}"165 val page = ByteArray(1_000) { it.toByte() }166 val comics = listOf("a", "b", "c").associateWith { name ->167 "$root/$name.cbz".also { files.writeBytes(it, buildStoredZip(listOf("001.jpg" to page))) }168 }169 fun setModified(path: String, seconds: Double) {170 NSFileManager.defaultManager.setAttributes(171 mapOf<Any?, Any?>(NSFileModificationDate to NSDate.dateWithTimeIntervalSince1970(seconds)),172 ofItemAtPath = path,173 error = null,174 )175 }176177 try {178 // Two chapters' pages fit; the third extraction must evict one.179 val archives = IosLocalArchiveService(extractedPagesBudgetBytes = 2_500)180 fun extractionOf(comic: String) =181 archives.listPages(comics.getValue(comic)).single().url.removePrefix("file://").substringBeforeLast('/')182183 val a = extractionOf("a")184 val b = extractionOf("b")185 // Pin the LRU order explicitly: filesystem mtimes can tie within one test.186 setModified(a, 1_000.0)187 setModified(b, 2_000.0)188 assertEquals(a, extractionOf("a")) // cached page list; marks a as used189 val c = extractionOf("c")190191 assertTrue(files.exists(a))192 assertFalse(files.exists(b))193 assertTrue(files.exists(c))194 // b's cached page list pointed into the evicted directory, so it extracts again.195 assertContentEquals(page, files.readBytes(archives.listPages(comics.getValue("b")).single().url))196 } finally {197 files.deleteRecursively(root)198 }199 }200201 private fun tarWith(vararg entries: Pair<String, ByteArray>): ByteArray {202 val output = mutableListOf<Byte>()203 entries.forEach { (name, data) ->204 val header = ByteArray(512)205 name.encodeToByteArray().copyInto(header)206 val sizeOctal = data.size.toString(8).padStart(11, '0')207 sizeOctal.encodeToByteArray().copyInto(header, 124)208 header[156] = '0'.code.toByte()209 for (index in 148..155) header[index] = ' '.code.toByte()210 val checksum = header.sumOf { it.toInt() and 0xff }.toString(8).padStart(6, '0').encodeToByteArray()211 checksum.copyInto(header, 148)212 header[154] = 0213 header[155] = ' '.code.toByte()214 output += header.toList()215 output += data.toList()216 val padding = (512 - (data.size % 512)) % 512217 repeat(padding) { output += 0 }218 }219 repeat(1024) { output += 0 }220 return output.toByteArray()221 }222223 private fun ByteArray.indexOfBytes(needle: ByteArray, start: Int = 0): Int =224 (start until size).firstOrNull { index ->225 index + needle.size <= size && needle.indices.all { this[index + it] == needle[it] }226 } ?: -1227228 private fun ByteArray.putLe16(offset: Int, value: Int) {229 this[offset] = value.toByte()230 this[offset + 1] = (value ushr 8).toByte()231 }232233 private fun ByteArray.putLe32(offset: Int, value: Int) {234 for (index in 0..3) this[offset + index] = (value ushr (index * 8)).toByte()235 }236}237