package eu.friedcutlet.yokan.services.files import java.io.File import java.net.URI import java.nio.file.AtomicMoveNotSupportedException import java.nio.file.Files import java.nio.file.StandardCopyOption.ATOMIC_MOVE import java.nio.file.StandardCopyOption /** * Plain-filesystem [LocalFileService] shared by desktop and Android (`file://` prefixes are * accepted). [openDirectory] is the platform shell integration behind [openLocation]; callers * without one (tests, headless use) get `false`. Android wraps this for `content://` SAF paths. */ internal class JvmLocalFileService( override val downloadRoot: String, override val backupRoot: String, override val cacheRoot: String, private val openDirectory: (File) -> Boolean = { false }, ) : LocalFileService { override fun writeBytes(path: String, bytes: ByteArray) { val file = File(path.removePrefix("file://")) file.parentFile?.mkdirs() file.writeBytes(bytes) } override fun appendBytes(path: String, bytes: ByteArray) { val file = File(path.removePrefix("file://")) file.parentFile?.mkdirs() file.appendBytes(bytes) } override suspend fun writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T { val file = File(path.removePrefix("file://")) file.parentFile?.mkdirs() return file.outputStream().use { out -> block { out.write(it) } } } override suspend fun appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T { val file = File(path.removePrefix("file://")) file.parentFile?.mkdirs() return java.io.FileOutputStream(file, true).use { out -> block { out.write(it) } } } override fun promote(sourcePath: String, targetPath: String): Boolean { val source = File(sourcePath.removePrefix("file://")) val target = File(targetPath.removePrefix("file://")) if (!source.isFile) return false target.parentFile?.mkdirs() return runCatching { try { Files.move( source.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING, ) } catch (_: AtomicMoveNotSupportedException) { Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING) } target.isFile && !source.exists() }.getOrDefault(false) } override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean { val source = File(tempPath.removePrefix("file://")) val target = File(finalPath.removePrefix("file://")) if (!source.isFile || !source.isSiblingOf(target)) return false return runCatching { Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) target.isFile && !source.exists() }.getOrDefault(false) } override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean { val source = File(stagedPath.removePrefix("file://")) val target = File(finalPath.removePrefix("file://")) if (!source.isDirectory || !source.isSiblingOf(target) || target.exists()) return false return runCatching { // ATOMIC_MOVE cannot universally guarantee no-clobber against an adversarial race; // callers use unpredictable app-owned job IDs, and the preflight rejects existing targets. Files.move(source.toPath(), target.toPath(), ATOMIC_MOVE) target.isDirectory && !source.exists() }.getOrDefault(false) } private fun File.isSiblingOf(other: File): Boolean = toPath().toAbsolutePath().normalize().parent == other.toPath().toAbsolutePath().normalize().parent override fun readBytes(path: String): ByteArray { val file = path.toUriFile() if (!file.isFile) return ByteArray(0) return file.readBytes() } override fun readBytesBounded(path: String, maxBytes: Long): ByteArray { require(maxBytes >= 0) { "maxBytes must not be negative" } val file = path.toUriFile() require(file.isFile) { "File is not readable: $path" } require(maxBytes < Int.MAX_VALUE) { "Bound exceeds ByteArray capacity" } file.inputStream().buffered().use { input -> val output = java.io.ByteArrayOutputStream(minOf(file.length(), maxBytes).toInt()) val buffer = ByteArray(16 * 1024) var remaining = maxBytes + 1 while (remaining > 0) { val count = input.read(buffer, 0, minOf(buffer.size.toLong(), remaining).toInt()) if (count < 0) break output.write(buffer, 0, count) remaining -= count } val bytes = output.toByteArray() require(bytes.size.toLong() <= maxBytes) { "File exceeds $maxBytes bytes" } return bytes } } override fun canonicalPath(path: String): String? = runCatching { File(path.removePrefix("file://")).canonicalPath }.getOrNull() override fun listFiles(root: String): List { val dir = File(root.removePrefix("file://")) if (!dir.isDirectory) return emptyList() return dir.listFiles() ?.filter { it.isFile } ?.sortedByDescending { it.lastModified() } ?.map { LocalFileEntry(it.absolutePath, it.name, it.length(), it.lastModified()) } .orEmpty() } override fun exists(path: String): Boolean = File(path.removePrefix("file://")).exists() override fun deleteRecursively(path: String): Boolean { val file = File(path.removePrefix("file://")) if (!file.exists()) return true return file.deleteRecursively() } override fun directorySize(path: String): Long { val file = File(path.removePrefix("file://")) if (!file.exists()) return 0L if (file.isFile) return file.length() return file.walkTopDown().filter { it.isFile }.sumOf { it.length() } } override fun openLocation(path: String): Boolean { val file = File(path.removePrefix("file://")) if (!file.exists()) return false return runCatching { openDirectory(if (file.isFile) file.parentFile else file) }.getOrDefault(false) } override fun listDirectoryEntries(root: String): List? = File(root.removePrefix("file://")).listFiles()?.asSequence() ?.filterNot { Files.isSymbolicLink(it.toPath()) } ?.filter { it.isDirectory || it.isFile } ?.map { LocalDirectoryEntry(it.absolutePath, it.name, it.isDirectory) } ?.sortedBy { it.name.lowercase() }?.toList() override fun listLocalEntries(root: String): List? { val dir = File(root.removePrefix("file://")) if (!dir.isDirectory) return null val children = dir.listFiles() ?: return null val entries = mutableListOf() children.sortedBy { it.name.lowercase() }.forEach { child -> when { child.isFile && child.hasReadableExtension() -> entries += LocalEntry(child.absolutePath, child.nameWithoutExtension, isArchive = true) child.isDirectory && child.containsReadableFiles() -> entries += LocalEntry(child.absolutePath, child.name, isArchive = false) child.isDirectory -> entries += listLocalEntries(child.absolutePath) ?: return null } } return entries } private fun File.hasReadableExtension(): Boolean = extension.lowercase() in readableLocalFileExtensions private fun File.containsReadableFiles(): Boolean = listFiles()?.any { it.isFile && it.hasReadableExtension() } == true } internal fun String.toUriFile(): File = if (startsWith("file:")) File(URI(this)) else File(this)