package eu.friedcutlet.yokan.services.files import java.io.ByteArrayOutputStream import java.io.DataOutputStream import java.io.File import java.net.URI import java.nio.file.Files import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipOutputStream import java.util.zip.CRC32 import java.util.zip.DeflaterOutputStream import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class JvmLocalArchiveServiceTest { @Test fun standaloneImagesOpenAsOnePageIncludingEncodedFileLocators() { val root = Files.createTempDirectory("yokan image % pages").toFile() try { val image = File(root, "page space.png").apply { writeBytes(png(0x22)) } val service = JvmLocalArchiveService(File(root, "cache").path) val page = service.listPages(image.toURI().toString()).single() assertEquals(image.name, page.fileName) assertContentEquals(image.readBytes(), File(URI(page.url)).readBytes()) assertEquals(listOf(page), service.listPagesStrict(image.toURI().toString())) image.writeBytes(byteArrayOf(1, 2, 3)) kotlin.test.assertFails { service.listPagesStrict(image.path) } } finally { root.deleteRecursively() } } @Test fun detectsArchiveTypesFromNamesAndSafMimeTypes() { assertEquals(LocalArchiveType.Epub, localArchiveType("book.epub", null)) assertEquals(LocalArchiveType.Zip, localArchiveType("opaque", "application/zip")) assertEquals(LocalArchiveType.Tar, localArchiveType("opaque", "application/x-tar")) assertEquals(LocalArchiveType.Rar, localArchiveType("comic.cbr", null)) assertEquals(LocalArchiveType.Rar, localArchiveType("comic.rar", null)) assertEquals(LocalArchiveType.Rar, localArchiveType("opaque", "application/x-rar-compressed")) assertEquals(LocalArchiveType.Unknown, localArchiveType("cover.jpg", "image/jpeg")) } @Test fun evictsLeastRecentlyUsedExtractedPagesBeyondTheBudget() { val root = Files.createTempDirectory("yokan-archives").toFile() try { val page = ByteArray(1_000) { it.toByte() } val comics = listOf("a", "b", "c").associateWith { name -> File(root, "$name.cbz").apply { writeBytes(cbzOf("001.jpg" to page)) }.path } // Two chapters' pages fit; the third extraction must evict one. val archives = JvmLocalArchiveService(File(root, "cache").path, extractedPagesBudgetBytes = 2_500) fun extractionOf(comic: String) = File(URI(archives.listPages(comics.getValue(comic)).single().url)).parentFile!! val a = extractionOf("a") val b = extractionOf("b") // Pin the LRU order explicitly: filesystem mtimes can tie within one test. a.setLastModified(1_000) b.setLastModified(2_000) assertEquals(a, extractionOf("a")) // cached page list; marks a as used val c = extractionOf("c") assertTrue(a.isDirectory) assertFalse(b.isDirectory) assertTrue(c.isDirectory) // b's cached page list pointed into the evicted directory, so it extracts again. val reextracted = archives.listPages(comics.getValue("b")).single() assertContentEquals(page, File(URI(reextracted.url)).readBytes()) } finally { root.deleteRecursively() } } @Test fun chapterCbzKeepsPagesAndMetadataButNotDownloadMarkers() { val root = Files.createTempDirectory("yokan-cbz").toFile() try { val chapter = File(root, "Chapter 1").apply { mkdirs() } File(chapter, "0001.jpg").writeBytes(byteArrayOf(1)) File(chapter, "0001.jpg.complete").writeBytes(ByteArray(0)) File(chapter, CHAPTER_METADATA_FILE).writeText("{}") val cbz = JvmLocalArchiveService(File(root, "cache").path).zipDirectoryToCbz(chapter.path, deleteSource = true) val names = ZipFile(checkNotNull(cbz)).use { zip -> zip.entries().asSequence().map { it.name }.toList() } assertEquals(listOf("0001.jpg", CHAPTER_METADATA_FILE), names) assertFalse(chapter.exists()) } finally { root.deleteRecursively() } } @Test fun strictInventoryUsesDecodedLocatorsAndNeverReusesReplacedArchivePages() { val root = Files.createTempDirectory("yokan strict % pages").toFile() try { val archive = File(root, "comic space.cbz") val service = JvmLocalArchiveService(File(root, "cache").path) archive.writeBytes(cbzOf("nested/01 % page.png" to png(0x11))) val oldPage = service.listPagesStrict(archive.toURI().toString()).single() assertContentEquals(png(0x11), File(URI(oldPage.url)).readBytes()) archive.writeBytes(cbzOf("nested/01 % page.png" to png(0x22))) val newPage = service.listPagesStrict(archive.toURI().toString()).single() assertContentEquals(png(0x22), File(URI(newPage.url)).readBytes()) assertFalse(oldPage.url == newPage.url) } finally { root.deleteRecursively() } } @Test fun strictInventoryRejectsUndecodableImageWithValidZipCrc() { val root = Files.createTempDirectory("yokan-corrupt-cbz").toFile() try { val archive = File(root, "broken.cbz") val bytes = ByteArrayOutputStream().also { output -> ZipOutputStream(output).use { zip -> val data = byteArrayOf(1, 2, 3, 4) val entry = ZipEntry("page.jpg").apply { method = ZipEntry.STORED size = data.size.toLong() compressedSize = data.size.toLong() crc = CRC32().apply { update(data) }.value } zip.putNextEntry(entry) zip.write(data) zip.closeEntry() } }.toByteArray() // The ZIP payload and CRC are valid; the image bytes are not a decodable JPEG. archive.writeBytes(bytes) kotlin.test.assertFails { JvmLocalArchiveService(File(root, "cache").path).listPagesStrict(archive.path) } } finally { root.deleteRecursively() } } @Test fun strictInventoryRejectsDecodableImageWithBadZipCrc() { val root = Files.createTempDirectory("yokan-bad-crc").toFile() try { val image = png(0x44) val bytes = ByteArrayOutputStream().also { output -> ZipOutputStream(output).use { zip -> val entry = ZipEntry("page.png").apply { method = ZipEntry.STORED size = image.size.toLong() compressedSize = image.size.toLong() crc = CRC32().apply { update(image) }.value } zip.putNextEntry(entry) zip.write(image) zip.closeEntry() } }.toByteArray() val centralHeader = bytes.indexOfSubsequence(byteArrayOf(0x50, 0x4b, 0x01, 0x02)) check(centralHeader >= 0) bytes[centralHeader + 16] = (bytes[centralHeader + 16].toInt() xor 1).toByte() val archive = File(root, "bad-crc.cbz").apply { writeBytes(bytes) } kotlin.test.assertFails { JvmLocalArchiveService(File(root, "cache").path).listPagesStrict(archive.path) } } finally { root.deleteRecursively() } } private fun cbzOf(vararg entries: Pair): ByteArray = ByteArrayOutputStream().also { bytes -> ZipOutputStream(bytes).use { zip -> entries.forEach { (name, content) -> zip.putNextEntry(ZipEntry(name)) zip.write(content) zip.closeEntry() } } }.toByteArray() private fun png(value: Int): ByteArray { val bytes = ByteArrayOutputStream() val output = DataOutputStream(bytes) output.write(byteArrayOf(137.toByte(), 80, 78, 71, 13, 10, 26, 10)) fun chunk(type: String, data: ByteArray) { val typeBytes = type.encodeToByteArray() output.writeInt(data.size) output.write(typeBytes) output.write(data) output.writeInt(CRC32().apply { update(typeBytes); update(data) }.value.toInt()) } val header = ByteArrayOutputStream().also { headerBytes -> DataOutputStream(headerBytes).use { headerOut -> headerOut.writeInt(1) headerOut.writeInt(1) headerOut.write(byteArrayOf(8, 6, 0, 0, 0)) } }.toByteArray() chunk("IHDR", header) val compressed = ByteArrayOutputStream().also { data -> DeflaterOutputStream(data).use { it.write(byteArrayOf(0, value.toByte(), value.toByte(), value.toByte(), -1)) } }.toByteArray() chunk("IDAT", compressed) chunk("IEND", ByteArray(0)) output.flush() return bytes.toByteArray() } private fun ByteArray.indexOfSubsequence(needle: ByteArray): Int = indices.firstOrNull { start -> start + needle.size <= size && needle.indices.all { this[start + it] == needle[it] } } ?: -1 }