package eu.friedcutlet.yokan.services.download import eu.friedcutlet.yokan.database.DatabaseJson import eu.friedcutlet.yokan.services.files.LocalFileService import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ensureActive import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString private val imageProcessingPermit = Semaphore(1) /** A page is resumable only after all its tiles and the bounded manifest are durable. */ internal class SplitPageStore( private val files: LocalFileService, private val splitter: suspend (ByteArray, Int, suspend (Int, ByteArray) -> Unit) -> Boolean = ::splitTallImage, ) { @Serializable private data class Manifest(val version: Int = 1, val original: String, val sizes: List) suspend fun savedSize(directory: String, base: String): Long? { val path = "$directory/$base.split.json" if (!files.exists(path)) return null val manifest = try { DatabaseJson.decodeFromString(files.readBytesAsync(path, 16 * 1024).decodeToString()) } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { return null } if (manifest.version != 1 || manifest.sizes.size !in 2..MaxSplitTiles || !manifest.original.matches(Regex("${Regex.escape(base)}\\.[a-zA-Z0-9]{1,8}"))) return null if (!manifest.sizes.withIndex().all { (index, size) -> val tile = tilePath(directory, base, index) size > 0 && files.exists(tile) && files.directorySize(tile) == size }) return null // A crash after committing the manifest can leave the original behind. Finish that commit. remove("$directory/${manifest.original}") remove("$directory/${manifest.original}.complete") return manifest.sizes.sum() } suspend fun process(path: String, maximumHeight: Int): Long = imageProcessingPermit.withPermit { val directory = path.substringBeforeLast('/') val name = path.substringAfterLast('/') val base = name.substringBeforeLast('.') require(base.isNotEmpty() && base.all(Char::isDigit)) savedSize(directory, base)?.let { return@withPermit it } discardUncommitted(directory, base) val originalSize = files.directorySize(path) if (originalSize <= 0 || originalSize > MaxSplitImageBytes) return@withPermit originalSize val sizes = mutableListOf() val split = try { val bytes = files.readBytesAsync(path, MaxSplitImageBytes) if (bytes.mayBeAnimatedImage()) false else splitter(bytes, maximumHeight) { index, tile -> currentCoroutineContext().ensureActive() check(index == sizes.size && index < MaxSplitTiles && tile.isNotEmpty()) val target = tilePath(directory, base, index) files.writeBytesAsync("$target.part", tile) check(files.promoteAsync("$target.part", target)) { "Cannot save split image" } sizes += tile.size.toLong() } } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { false } if (!split || sizes.size < 2) { discardUncommitted(directory, base) return@withPermit originalSize } val manifestPath = "$directory/$base.split.json" files.writeBytesAsync("$manifestPath.part", DatabaseJson.encodeToString(Manifest(original = name, sizes = sizes)).encodeToByteArray()) check(files.promoteAsync("$manifestPath.part", manifestPath)) { "Cannot commit split image" } remove(path) remove("$path.complete") sizes.sum() } /** Removes only this page's deterministic outputs, never paths supplied by a manifest. */ private suspend fun discardUncommitted(directory: String, base: String) { val tiles = Regex("${Regex.escape(base)}_s[0-9]{4}\\.jpg(?:\\.part)?") files.listFiles(directory).filter { it.name.matches(tiles) || it.name == "$base.split.json" || it.name == "$base.split.json.part" } .forEach { remove(it.path) } } private suspend fun remove(path: String) { if (files.exists(path)) check(files.deleteRecursivelyAsync(path) && !files.exists(path)) { "Cannot remove incomplete split image" } } private fun tilePath(directory: String, base: String, index: Int) = "$directory/${base}_s${(index + 1).toString().padStart(4, '0')}.jpg" }