SplitPageStore.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/download/SplitPageStore.kt
1package eu.friedcutlet.yokan.services.download23import eu.friedcutlet.yokan.database.DatabaseJson4import eu.friedcutlet.yokan.services.files.LocalFileService5import kotlinx.coroutines.CancellationException6import kotlinx.coroutines.ensureActive7import kotlinx.coroutines.currentCoroutineContext8import kotlinx.coroutines.sync.Semaphore9import kotlinx.coroutines.sync.withPermit10import kotlinx.serialization.Serializable11import kotlinx.serialization.encodeToString1213private val imageProcessingPermit = Semaphore(1)1415/** A page is resumable only after all its tiles and the bounded manifest are durable. */16internal class SplitPageStore(17 private val files: LocalFileService,18 private val splitter: suspend (ByteArray, Int, suspend (Int, ByteArray) -> Unit) -> Boolean = ::splitTallImage,19) {20 @Serializable21 private data class Manifest(val version: Int = 1, val original: String, val sizes: List<Long>)2223 suspend fun savedSize(directory: String, base: String): Long? {24 val path = "$directory/$base.split.json"25 if (!files.exists(path)) return null26 val manifest = try {27 DatabaseJson.decodeFromString<Manifest>(files.readBytesAsync(path, 16 * 1024).decodeToString())28 } catch (cancel: CancellationException) { throw cancel }29 catch (_: Exception) { return null }30 if (manifest.version != 1 || manifest.sizes.size !in 2..MaxSplitTiles ||31 !manifest.original.matches(Regex("${Regex.escape(base)}\\.[a-zA-Z0-9]{1,8}"))) return null32 if (!manifest.sizes.withIndex().all { (index, size) ->33 val tile = tilePath(directory, base, index)34 size > 0 && files.exists(tile) && files.directorySize(tile) == size35 }) return null36 // A crash after committing the manifest can leave the original behind. Finish that commit.37 remove("$directory/${manifest.original}")38 remove("$directory/${manifest.original}.complete")39 return manifest.sizes.sum()40 }4142 suspend fun process(path: String, maximumHeight: Int): Long = imageProcessingPermit.withPermit {43 val directory = path.substringBeforeLast('/')44 val name = path.substringAfterLast('/')45 val base = name.substringBeforeLast('.')46 require(base.isNotEmpty() && base.all(Char::isDigit))47 savedSize(directory, base)?.let { return@withPermit it }48 discardUncommitted(directory, base)49 val originalSize = files.directorySize(path)50 if (originalSize <= 0 || originalSize > MaxSplitImageBytes) return@withPermit originalSize51 val sizes = mutableListOf<Long>()52 val split = try {53 val bytes = files.readBytesAsync(path, MaxSplitImageBytes)54 if (bytes.mayBeAnimatedImage()) false else splitter(bytes, maximumHeight) { index, tile ->55 currentCoroutineContext().ensureActive()56 check(index == sizes.size && index < MaxSplitTiles && tile.isNotEmpty())57 val target = tilePath(directory, base, index)58 files.writeBytesAsync("$target.part", tile)59 check(files.promoteAsync("$target.part", target)) { "Cannot save split image" }60 sizes += tile.size.toLong()61 }62 } catch (cancel: CancellationException) { throw cancel }63 catch (_: Exception) { false }64 if (!split || sizes.size < 2) {65 discardUncommitted(directory, base)66 return@withPermit originalSize67 }68 val manifestPath = "$directory/$base.split.json"69 files.writeBytesAsync("$manifestPath.part", DatabaseJson.encodeToString(Manifest(original = name, sizes = sizes)).encodeToByteArray())70 check(files.promoteAsync("$manifestPath.part", manifestPath)) { "Cannot commit split image" }71 remove(path)72 remove("$path.complete")73 sizes.sum()74 }7576 /** Removes only this page's deterministic outputs, never paths supplied by a manifest. */77 private suspend fun discardUncommitted(directory: String, base: String) {78 val tiles = Regex("${Regex.escape(base)}_s[0-9]{4}\\.jpg(?:\\.part)?")79 files.listFiles(directory).filter { it.name.matches(tiles) || it.name == "$base.split.json" || it.name == "$base.split.json.part" }80 .forEach { remove(it.path) }81 }8283 private suspend fun remove(path: String) {84 if (files.exists(path)) check(files.deleteRecursivelyAsync(path) && !files.exists(path)) { "Cannot remove incomplete split image" }85 }8687 private fun tilePath(directory: String, base: String, index: Int) = "$directory/${base}_s${(index + 1).toString().padStart(4, '0')}.jpg"88}89