package eu.friedcutlet.yokan.services.files import kotlinx.cinterop.ExperimentalForeignApi import platform.Foundation.NSDate import platform.Foundation.NSFileManager import platform.Foundation.NSFileModificationDate import platform.Foundation.dateWithTimeIntervalSince1970 import kotlin.random.Random import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue class IosArchivePagesTest { @Test fun zipsDirectoryAndExtractsCbzPages() { val files = createPlatformLocalFileService() val dir = "${files.cacheRoot}/cbz-src-${Random.nextLong()}" val pageA = byteArrayOf(1, 2, 3, 4) val pageB = byteArrayOf(9, 8, 7) files.writeBytes("$dir/002.png", pageB) files.writeBytes("$dir/001.jpg", pageA) files.writeBytes("$dir/notes.txt", byteArrayOf(0)) files.writeBytes("$dir/001.jpg.complete", ByteArray(0)) files.writeBytes("$dir/$CHAPTER_METADATA_FILE", "{}".encodeToByteArray()) var cbz: String? = null try { val archives = createPlatformLocalArchiveService() cbz = archives.zipDirectoryToCbz(dir, deleteSource = false) assertNotNull(cbz) assertTrue(files.exists(cbz)) assertEquals(setOf("001.jpg", "002.png", CHAPTER_METADATA_FILE), IosZipArchive.openFile(cbz)?.entryNames?.toSet()) val pages = archives.listPages(cbz) assertEquals(listOf("0000_001.jpg", "0001_002.png"), pages.map { it.fileName }) assertContentEquals(pageA, files.readBytes(pages[0].url)) assertContentEquals(pageB, files.readBytes(pages[1].url)) } finally { files.deleteRecursively(dir) cbz?.let(files::deleteRecursively) } } @Test fun extractsTarPages() { val files = createPlatformLocalFileService() val tarPath = "${files.cacheRoot}/pages-${Random.nextLong()}.cbt" val image = byteArrayOf(5, 6, 7, 8, 9) files.writeBytes(tarPath, tarWith("p1.png" to image, "skip.txt" to byteArrayOf(1))) try { val archives = createPlatformLocalArchiveService() val pages = archives.listPages(tarPath) assertEquals(listOf("0000_p1.png"), pages.map { it.fileName }) assertContentEquals(image, files.readBytes(pages.single().url)) } finally { files.deleteRecursively(tarPath) } } @Test fun strictInventoryReextractsReplacedCbzAtSamePath() { val files = createPlatformLocalFileService() val archive = "${files.cacheRoot}/strict ${Random.nextLong()} %20 #.cbz" try { val archives = createPlatformLocalArchiveService() files.writeBytes(archive, buildStoredZip(listOf("nested/page%20#one.jpg" to byteArrayOf(1)))) val first = archives.listPagesStrict(archive).single() assertTrue(first.url.contains("%2520%23"), first.url) assertContentEquals(byteArrayOf(1), files.readBytes(first.url)) files.writeBytes(archive, buildStoredZip(listOf("nested/page%20#one.jpg" to byteArrayOf(2)))) val second = archives.listPagesStrict(archive).single() assertContentEquals(byteArrayOf(2), files.readBytes(second.url)) assertFalse(first.url == second.url) } finally { files.deleteRecursively(archive) } } @Test fun strictInventoryRejectsMalformedSecondZipDirectoryRecord() { val files = createPlatformLocalFileService() val archive = "${files.cacheRoot}/malformed-${Random.nextLong()}.cbz" try { val bytes = buildStoredZip(listOf("one.jpg" to byteArrayOf(1), "two.jpg" to byteArrayOf(2))) val signature = byteArrayOf(0x50, 0x4b, 0x01, 0x02) val first = bytes.indexOfBytes(signature) val second = bytes.indexOfBytes(signature, first + signature.size) check(first >= 0 && second >= 0) bytes[second] = 0 files.writeBytes(archive, bytes) kotlin.test.assertFails { createPlatformLocalArchiveService().listPagesStrict(archive) } } finally { files.deleteRecursively(archive) } } @Test fun strictInventoryRejectsUnderreportedEocdEntryCountAndDirectoryExtent() { val files = createPlatformLocalFileService() val root = "${files.cacheRoot}/eocd-${Random.nextLong()}" val archives = createPlatformLocalArchiveService() val entries = listOf("one.jpg" to byteArrayOf(1), "two.jpg" to byteArrayOf(2)) val original = buildStoredZip(entries) val eocd = original.size - 22 val firstRecordSize = 46 + "one.jpg".encodeToByteArray().size try { // Tamper total count and central size, leaving the per-disk count unchanged. val countMismatch = original.copyOf().apply { putLe16(eocd + 10, 1) putLe32(eocd + 12, firstRecordSize) } val countMismatchPath = "$root-count.cbz" files.writeBytes(countMismatchPath, countMismatch) kotlin.test.assertFails { archives.listPagesStrict(countMismatchPath) } // Matching the per-disk count must still fail because the claimed directory no longer reaches EOCD. val extentMismatch = original.copyOf().apply { putLe16(eocd + 8, 1) putLe16(eocd + 10, 1) putLe32(eocd + 12, firstRecordSize) } val extentMismatchPath = "$root-extent.cbz" files.writeBytes(extentMismatchPath, extentMismatch) kotlin.test.assertFails { archives.listPagesStrict(extentMismatchPath) } // A well-formed ZIP comment remains accepted by strict inventory. val withComment = original.copyOf(original.size + 4).apply { putLe16(eocd + 20, 4) "note".encodeToByteArray().copyInto(this, original.size) } val commentedPath = "$root-comment.cbz" files.writeBytes(commentedPath, withComment) assertEquals(2, archives.listPagesStrict(commentedPath).size) } finally { files.deleteRecursively(root) files.deleteRecursively("$root-count.cbz") files.deleteRecursively("$root-extent.cbz") files.deleteRecursively("$root-comment.cbz") } } @Test fun strictInventoryRejectsTruncatedTarImage() { val files = createPlatformLocalFileService() val archive = "${files.cacheRoot}/truncated-${Random.nextLong()}.cbt" try { val complete = tarWith("page.png" to byteArrayOf(1, 2, 3, 4, 5)) files.writeBytes(archive, complete.copyOf(512 + 2)) kotlin.test.assertFails { createPlatformLocalArchiveService().listPagesStrict(archive) } } finally { files.deleteRecursively(archive) } } @OptIn(ExperimentalForeignApi::class) @Test fun evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget() { val files = createPlatformLocalFileService() val root = "${files.cacheRoot}/lru-${Random.nextLong()}" val page = ByteArray(1_000) { it.toByte() } val comics = listOf("a", "b", "c").associateWith { name -> "$root/$name.cbz".also { files.writeBytes(it, buildStoredZip(listOf("001.jpg" to page))) } } fun setModified(path: String, seconds: Double) { NSFileManager.defaultManager.setAttributes( mapOf(NSFileModificationDate to NSDate.dateWithTimeIntervalSince1970(seconds)), ofItemAtPath = path, error = null, ) } try { // Two chapters' pages fit; the third extraction must evict one. val archives = IosLocalArchiveService(extractedPagesBudgetBytes = 2_500) fun extractionOf(comic: String) = archives.listPages(comics.getValue(comic)).single().url.removePrefix("file://").substringBeforeLast('/') val a = extractionOf("a") val b = extractionOf("b") // Pin the LRU order explicitly: filesystem mtimes can tie within one test. setModified(a, 1_000.0) setModified(b, 2_000.0) assertEquals(a, extractionOf("a")) // cached page list; marks a as used val c = extractionOf("c") assertTrue(files.exists(a)) assertFalse(files.exists(b)) assertTrue(files.exists(c)) // b's cached page list pointed into the evicted directory, so it extracts again. assertContentEquals(page, files.readBytes(archives.listPages(comics.getValue("b")).single().url)) } finally { files.deleteRecursively(root) } } private fun tarWith(vararg entries: Pair): ByteArray { val output = mutableListOf() entries.forEach { (name, data) -> val header = ByteArray(512) name.encodeToByteArray().copyInto(header) val sizeOctal = data.size.toString(8).padStart(11, '0') sizeOctal.encodeToByteArray().copyInto(header, 124) header[156] = '0'.code.toByte() for (index in 148..155) header[index] = ' '.code.toByte() val checksum = header.sumOf { it.toInt() and 0xff }.toString(8).padStart(6, '0').encodeToByteArray() checksum.copyInto(header, 148) header[154] = 0 header[155] = ' '.code.toByte() output += header.toList() output += data.toList() val padding = (512 - (data.size % 512)) % 512 repeat(padding) { output += 0 } } repeat(1024) { output += 0 } return output.toByteArray() } private fun ByteArray.indexOfBytes(needle: ByteArray, start: Int = 0): Int = (start until size).firstOrNull { index -> index + needle.size <= size && needle.indices.all { this[index + it] == needle[it] } } ?: -1 private fun ByteArray.putLe16(offset: Int, value: Int) { this[offset] = value.toByte() this[offset + 1] = (value ushr 8).toByte() } private fun ByteArray.putLe32(offset: Int, value: Int) { for (index in 0..3) this[offset + index] = (value ushr (index * 8)).toByte() } }