package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.services.files.LocalEntry import eu.friedcutlet.yokan.services.files.LocalFileEntry import eu.friedcutlet.yokan.services.files.LocalFileService import kotlinx.coroutines.CancellationException import kotlinx.coroutines.test.runTest import kotlin.test.* class SplitPageStoreTest { @Test fun regionsCoverEveryPixelInOrderWithoutExceedingLimits() { assertEquals(listOf(TallImageRegion(0, 4096), TallImageRegion(4096, 4096), TallImageRegion(8192, 809)), tallImageRegions(800, 9001, 4096)) assertTrue(tallImageRegions(800, 1024, 4096).isEmpty()) assertTrue(tallImageRegions(4000, 7000, 4096).isEmpty()) assertTrue(tallImageRegions(Int.MAX_VALUE, Int.MAX_VALUE, 4096).isEmpty()) assertTrue(tallImageRegions(1000, 24001, 4096).isEmpty()) assertEquals(1024, tallImageRegions(400, 3000, -1).first().height) } @Test fun committedTilesResumeWithoutFetchingOrDecodingOriginal() = runTest { val files = Files().withOriginal() var decodes = 0 val store = SplitPageStore(files) { _, _, tile -> decodes++ tile(0, byteArrayOf(1, 2)) tile(1, byteArrayOf(3, 4, 5)) true } assertEquals(5L, store.process("/chapter/0001.jpg", 4096)) assertFalse(files.exists("/chapter/0001.jpg")) assertFalse(files.exists("/chapter/0001.jpg.complete")) assertEquals(listOf("0001.split.json", "0001_s0001.jpg", "0001_s0002.jpg"), files.listFiles("/chapter").map { it.name }.sorted()) assertEquals(5L, SplitPageStore(files).savedSize("/chapter", "0001")) assertEquals(1, decodes) } @Test fun failedDecodeCleansTilesAndKeepsOriginal() = runTest { val files = Files().withOriginal() val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)) error("bad codec") } assertEquals(3L, store.process("/chapter/0001.jpg", 4096)) assertEquals(setOf("/chapter/0001.jpg", "/chapter/0001.jpg.complete"), files.data.keys) assertContentEquals(byteArrayOf(9, 8, 7), files.readBytes("/chapter/0001.jpg")) } @Test fun cancelledSplitRetainsOriginalAndOrphansAreReplacedOnRetry() = runTest { val files = Files().withOriginal() val cancelled = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)) throw CancellationException("pause") } assertFailsWith { cancelled.process("/chapter/0001.jpg", 4096) } assertTrue(files.exists("/chapter/0001.jpg.complete")) val retry = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(4, 5)) tile(1, byteArrayOf(6)) true } assertEquals(3L, retry.process("/chapter/0001.jpg", 4096)) assertContentEquals(byteArrayOf(4, 5), files.readBytes("/chapter/0001_s0001.jpg")) } @Test fun promotionFailureKeepsOriginalAndNeverCommitsPartialManifest() = runTest { val files = Files().withOriginal().apply { failedPromotionSuffix = "_s0002.jpg" } val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true } assertEquals(3L, store.process("/chapter/0001.jpg", 4096)) assertFalse(files.exists("/chapter/0001.split.json")) assertEquals(2, files.data.size) } @Test fun manifestCommitFailureCanBeRetriedWithoutLosingOriginal() = runTest { val files = Files().withOriginal().apply { failedPromotionSuffix = ".split.json" } val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true } assertFailsWith { store.process("/chapter/0001.jpg", 4096) } assertNull(store.savedSize("/chapter", "0001")) assertTrue(files.exists("/chapter/0001.jpg")) files.failedPromotionSuffix = null assertEquals(2L, store.process("/chapter/0001.jpg", 4096)) } @Test fun committedManifestFinishesOriginalDeletionAfterCrash() = runTest { val files = Files().withOriginal().apply { refuseOriginalDeletion = true } val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2)); true } assertFailsWith { store.process("/chapter/0001.jpg", 4096) } assertTrue(files.exists("/chapter/0001.split.json")) files.refuseOriginalDeletion = false assertEquals(2L, SplitPageStore(files).savedSize("/chapter", "0001")) assertFalse(files.exists("/chapter/0001.jpg")) } @Test fun corruptMissingOrTruncatedTilesNeverCountAsSaved() = runTest { val files = Files().withOriginal() val store = SplitPageStore(files) { _, _, tile -> tile(0, byteArrayOf(1)); tile(1, byteArrayOf(2, 3)); true } store.process("/chapter/0001.jpg", 4096) files.writeBytes("/chapter/0001_s0002.jpg", byteArrayOf(2)) assertNull(store.savedSize("/chapter", "0001")) files.writeBytes("/chapter/0001.split.json", "{\"version\":1,\"original\":\"../other.jpg\",\"sizes\":[1,1]}".encodeToByteArray()) assertNull(store.savedSize("/chapter", "0001")) } @Test fun animationsAndOversizedEncodedImagesBypassDecoder() = runTest { val files = Files() val store = SplitPageStore(files) { _, _, _ -> error("must not decode") } files.writeBytes("/chapter/0001.gif", "GIF89a".encodeToByteArray()) assertEquals(6L, store.process("/chapter/0001.gif", 4096)) files.reportedSize = MaxSplitImageBytes + 1 assertEquals(MaxSplitImageBytes + 1, store.process("/chapter/0001.gif", 4096)) } @Test fun webpAndPngAnimationHeadersAreDetected() { val webp = ByteArray(21) "RIFF".encodeToByteArray().copyInto(webp) "WEBPVP8X".encodeToByteArray().copyInto(webp, 8) webp[20] = 2 assertTrue(webp.mayBeAnimatedImage()) webp[20] = 0 assertFalse(webp.mayBeAnimatedImage()) val apng = byteArrayOf(0x89.toByte(), 80, 78, 71, 13, 10, 26, 10) + ByteArray(4) + "acTL".encodeToByteArray() + ByteArray(4) assertTrue(apng.mayBeAnimatedImage()) } private class Files : LocalFileService { val data = linkedMapOf() var failedPromotionSuffix: String? = null var refuseOriginalDeletion = false var reportedSize: Long? = null override val downloadRoot = "/downloads" override val backupRoot = "/backups" override val cacheRoot = "/cache" fun withOriginal() = apply { writeBytes("/chapter/0001.jpg", byteArrayOf(9, 8, 7)); writeBytes("/chapter/0001.jpg.complete", ByteArray(0)) } override fun writeBytes(path: String, bytes: ByteArray) { data[path] = bytes.copyOf() } override fun readBytes(path: String) = requireNotNull(data[path]).copyOf() override fun exists(path: String) = path in data override fun promote(sourcePath: String, targetPath: String): Boolean { if (failedPromotionSuffix?.let(targetPath::endsWith) == true) return false data[targetPath] = data.remove(sourcePath) ?: return false return true } override fun deleteRecursively(path: String): Boolean { if (refuseOriginalDeletion && path.endsWith("/0001.jpg")) return false data.remove(path) return true } override fun directorySize(path: String) = reportedSize ?: data[path]?.size?.toLong() ?: 0L override fun canonicalPath(path: String) = path override fun openLocation(path: String) = false override fun listLocalEntries(root: String) = emptyList() override fun listFiles(root: String) = data.entries.filter { it.key.substringBeforeLast('/') == root } .map { LocalFileEntry(it.key, it.key.substringAfterLast('/'), it.value.size.toLong(), 0L) } } }