JvmLocalFileService.kt
composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/files/JvmLocalFileService.kt
1package eu.friedcutlet.yokan.services.files23import java.io.File4import java.net.URI5import java.nio.file.AtomicMoveNotSupportedException6import java.nio.file.Files7import java.nio.file.StandardCopyOption.ATOMIC_MOVE8import java.nio.file.StandardCopyOption910/**11 * Plain-filesystem [LocalFileService] shared by desktop and Android (`file://` prefixes are12 * accepted). [openDirectory] is the platform shell integration behind [openLocation]; callers13 * without one (tests, headless use) get `false`. Android wraps this for `content://` SAF paths.14 */15internal class JvmLocalFileService(16 override val downloadRoot: String,17 override val backupRoot: String,18 override val cacheRoot: String,19 private val openDirectory: (File) -> Boolean = { false },20) : LocalFileService {21 override fun writeBytes(path: String, bytes: ByteArray) {22 val file = File(path.removePrefix("file://"))23 file.parentFile?.mkdirs()24 file.writeBytes(bytes)25 }2627 override fun appendBytes(path: String, bytes: ByteArray) {28 val file = File(path.removePrefix("file://"))29 file.parentFile?.mkdirs()30 file.appendBytes(bytes)31 }3233 override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {34 val file = File(path.removePrefix("file://"))35 file.parentFile?.mkdirs()36 return file.outputStream().use { out -> block { out.write(it) } }37 }3839 override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T {40 val file = File(path.removePrefix("file://"))41 file.parentFile?.mkdirs()42 return java.io.FileOutputStream(file, true).use { out -> block { out.write(it) } }43 }4445 override fun promote(sourcePath: String, targetPath: String): Boolean {46 val source = File(sourcePath.removePrefix("file://"))47 val target = File(targetPath.removePrefix("file://"))48 if (!source.isFile) return false49 target.parentFile?.mkdirs()50 return runCatching {51 try {52 Files.move(53 source.toPath(),54 target.toPath(),55 StandardCopyOption.ATOMIC_MOVE,56 StandardCopyOption.REPLACE_EXISTING,57 )58 } catch (_: AtomicMoveNotSupportedException) {59 Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)60 }61 target.isFile && !source.exists()62 }.getOrDefault(false)63 }6465 override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean {66 val source = File(tempPath.removePrefix("file://"))67 val target = File(finalPath.removePrefix("file://"))68 if (!source.isFile || !source.isSiblingOf(target)) return false69 return runCatching {70 Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)71 target.isFile && !source.exists()72 }.getOrDefault(false)73 }7475 override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean {76 val source = File(stagedPath.removePrefix("file://"))77 val target = File(finalPath.removePrefix("file://"))78 if (!source.isDirectory || !source.isSiblingOf(target) || target.exists()) return false79 return runCatching {80 // ATOMIC_MOVE cannot universally guarantee no-clobber against an adversarial race;81 // callers use unpredictable app-owned job IDs, and the preflight rejects existing targets.82 Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE)83 target.isDirectory && !source.exists()84 }.getOrDefault(false)85 }8687 private fun File.isSiblingOf(other: File): Boolean =88 toPath().toAbsolutePath().normalize().parent == other.toPath().toAbsolutePath().normalize().parent8990 override fun readBytes(path: String): ByteArray {91 val file = path.toUriFile()92 if (!file.isFile) return ByteArray(0)93 return file.readBytes()94 }9596 override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {97 require(maxBytes >= 0) { "maxBytes must not be negative" }98 val file = path.toUriFile()99 require(file.isFile) { "File is not readable: $path" }100 require(maxBytes < Int.MAX_VALUE) { "Bound exceeds ByteArray capacity" }101 file.inputStream().buffered().use { input ->102 val output = java.io.ByteArrayOutputStream(minOf(file.length(), maxBytes).toInt())103 val buffer = ByteArray(16 * 1024)104 var remaining = maxBytes + 1105 while (remaining > 0) {106 val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt())107 if (count < 0) break108 output.write(buffer, 0, count)109 remaining -= count110 }111 val bytes = output.toByteArray()112 require(bytes.size.toLong() <= maxBytes) { "File exceeds $maxBytes bytes" }113 return bytes114 }115 }116117 override fun canonicalPath(path: String): String? =118 runCatching { File(path.removePrefix("file://")).canonicalPath }.getOrNull()119120 override fun listFiles(root: String): List<LocalFileEntry> {121 val dir = File(root.removePrefix("file://"))122 if (!dir.isDirectory) return emptyList()123 return dir.listFiles()124 ?.filter { it.isFile }125 ?.sortedByDescending { it.lastModified() }126 ?.map { LocalFileEntry(it.absolutePath, it.name, it.length(), it.lastModified()) }127 .orEmpty()128 }129130 override fun exists(path: String): Boolean =131 File(path.removePrefix("file://")).exists()132133 override fun deleteRecursively(path: String): Boolean {134 val file = File(path.removePrefix("file://"))135 if (!file.exists()) return true136 return file.deleteRecursively()137 }138139 override fun directorySize(path: String): Long {140 val file = File(path.removePrefix("file://"))141 if (!file.exists()) return 0L142 if (file.isFile) return file.length()143 return file.walkTopDown().filter { it.isFile }.sumOf { it.length() }144 }145146 override fun openLocation(path: String): Boolean {147 val file = File(path.removePrefix("file://"))148 if (!file.exists()) return false149 return runCatching { openDirectory(if (file.isFile) file.parentFile else file) }.getOrDefault(false)150 }151152 override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? =153 File(root.removePrefix("file://")).listFiles()?.asSequence()154 ?.filterNot { Files.isSymbolicLink(it.toPath()) }155 ?.filter { it.isDirectory || it.isFile }156 ?.map { LocalDirectoryEntry(it.absolutePath, it.name, it.isDirectory) }157 ?.sortedBy { it.name.lowercase() }?.toList()158159 override fun listLocalEntries(root: String): List<LocalEntry>? {160 val dir = File(root.removePrefix("file://"))161 if (!dir.isDirectory) return null162 val children = dir.listFiles() ?: return null163 val entries = mutableListOf<LocalEntry>()164 children.sortedBy { it.name.lowercase() }.forEach { child ->165 when {166 child.isFile && child.hasReadableExtension() ->167 entries += LocalEntry(child.absolutePath, child.nameWithoutExtension, isArchive = true)168 child.isDirectory && child.containsReadableFiles() ->169 entries += LocalEntry(child.absolutePath, child.name, isArchive = false)170 child.isDirectory -> entries += listLocalEntries(child.absolutePath) ?: return null171 }172 }173 return entries174 }175176 private fun File.hasReadableExtension(): Boolean = extension.lowercase() in readableLocalFileExtensions177178 private fun File.containsReadableFiles(): Boolean =179 listFiles()?.any { it.isFile && it.hasReadableExtension() } == true180}181182internal fun String.toUriFile(): File =183 if (startsWith("file:")) File(URI(this)) else File(this)184