AndroidSafLocalFileService.kt
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalFileService.kt
1package eu.friedcutlet.yokan.services.files23import android.content.ContentResolver4import android.content.Intent5import android.database.Cursor6import android.net.Uri7import android.provider.DocumentsContract8import eu.friedcutlet.yokan.AndroidAppContext910/**11 * [JvmLocalFileService] plus SAF `content://` paths. Persisted tree grants are read-only local12 * folders: they can be listed, read and opened, never written or deleted. A separately picked13 * `content://` document (not under a tree) keeps write support.14 */15internal class AndroidSafLocalFileService(16 private val files: JvmLocalFileService,17) : LocalFileService by files {18 override fun writeBytes(path: String, bytes: ByteArray) {19 if (!path.startsWith("content://")) return files.writeBytes(path, bytes)20 if (treeUri(path) != null) return21 val context = AndroidAppContext.appContext ?: return22 context.contentResolver.openOutputStream(Uri.parse(path), "wt")?.use { it.write(bytes) }23 }2425 override fun appendBytes(path: String, bytes: ByteArray) {26 if (!path.startsWith("content://")) return files.appendBytes(path, bytes)27 if (treeUri(path) != null) return28 val context = AndroidAppContext.appContext ?: return29 context.contentResolver.openOutputStream(Uri.parse(path), "wa")?.use { it.write(bytes) }30 }3132 override suspend fun <T> writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T =33 if (path.startsWith("content://")) super.writeChunks(path, block) else files.writeChunks(path, block)3435 override suspend fun <T> appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T =36 if (path.startsWith("content://")) super.appendChunks(path, block) else files.appendChunks(path, block)3738 override fun promote(sourcePath: String, targetPath: String): Boolean =39 if (sourcePath.startsWith("content://") || targetPath.startsWith("content://")) {40 // Provider documents cannot be moved atomically; copy through the resolver instead.41 super.promote(sourcePath, targetPath)42 } else {43 files.promote(sourcePath, targetPath)44 }4546 override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean =47 if (tempPath.startsWith("content://") || finalPath.startsWith("content://")) false48 else files.atomicReplaceFile(tempPath, finalPath)4950 override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean =51 if (stagedPath.startsWith("content://") || finalPath.startsWith("content://")) false52 else files.publishDirectoryIfAbsent(stagedPath, finalPath)5354 override fun canonicalPath(path: String): String? =55 if (path.startsWith("content://")) null else files.canonicalPath(path)5657 override fun readBytes(path: String): ByteArray {58 if (!path.startsWith("content://")) return files.readBytes(path)59 val context = AndroidAppContext.appContext ?: return ByteArray(0)60 return runCatching {61 val uri = Uri.parse(path)62 if (treeUri(path) != null && !hasPersistedReadGrant(context.contentResolver, uri)) return@runCatching null63 val documentUri = safDocumentUri(context.contentResolver, uri) ?: uri64 context.contentResolver.openInputStream(documentUri)?.use { it.readBytes() }65 }.getOrNull() ?: ByteArray(0)66 }6768 override fun mimeType(path: String): String? {69 if (!path.startsWith("content://")) return files.mimeType(path)70 val context = AndroidAppContext.appContext ?: return null71 return runCatching { context.contentResolver.getType(Uri.parse(path)) }.getOrNull()72 }7374 override fun readBytesBounded(path: String, maxBytes: Long): ByteArray {75 require(maxBytes >= 0) { "maxBytes must not be negative" }76 if (!path.startsWith("content://")) return files.readBytesBounded(path, maxBytes)77 require(maxBytes < Int.MAX_VALUE) { "Bound exceeds ByteArray capacity" }78 val context = AndroidAppContext.appContext ?: error("Content resolver is unavailable")79 val uri = Uri.parse(path)80 if (treeUri(path) != null) require(hasPersistedReadGrant(context.contentResolver, uri)) { "No SAF read grant" }81 val documentUri = safDocumentUri(context.contentResolver, uri) ?: uri82 val input = context.contentResolver.openInputStream(documentUri) ?: error("Cannot open $path")83 input.use {84 val output = java.io.ByteArrayOutputStream()85 val buffer = ByteArray(16 * 1024)86 var total = 0L87 while (total <= maxBytes) {88 val count = it.read(buffer, 0, minOf(buffer.size.toLong(), maxBytes + 1 - total).toInt())89 if (count < 0) break90 output.write(buffer, 0, count)91 total += count92 }93 require(total <= maxBytes) { "File exceeds $maxBytes bytes" }94 return output.toByteArray()95 }96 }9798 override fun listFiles(root: String): List<LocalFileEntry> {99 val context = AndroidAppContext.appContext100 if (context != null && root.startsWith("content://") && treeUri(root) != null) {101 return listSafFiles(context.contentResolver, Uri.parse(root)).orEmpty()102 }103 return files.listFiles(root)104 }105106 override fun exists(path: String): Boolean {107 if (!path.startsWith("content://")) return files.exists(path)108 val context = AndroidAppContext.appContext ?: return false109 val uri = Uri.parse(path)110 return if (treeUri(path) != null) {111 hasPersistedReadGrant(context.contentResolver, uri) &&112 querySafDocument(context.contentResolver, uri) != null113 } else {114 runCatching {115 context.contentResolver.openInputStream(uri)?.use { true } ?: false116 }.getOrDefault(false)117 }118 }119120 override fun deleteRecursively(path: String): Boolean =121 if (path.startsWith("content://")) false else files.deleteRecursively(path)122123 override fun directorySize(path: String): Long {124 val context = AndroidAppContext.appContext125 if (context != null && path.startsWith("content://") && treeUri(path) != null) {126 return directorySizeSaf(context.contentResolver, Uri.parse(path))127 }128 return files.directorySize(path)129 }130131 override fun openLocation(path: String): Boolean {132 if (!path.startsWith("content://")) return files.openLocation(path)133 val context = AndroidAppContext.appContext ?: return false134 val uri = Uri.parse(path)135 if (treeUri(path) == null || !hasPersistedReadGrant(context.contentResolver, uri)) return false136 return runCatching {137 context.startActivity(Intent(Intent.ACTION_VIEW).apply {138 data = uri139 addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)140 })141 true142 }.getOrDefault(false)143 }144145 override fun listDirectoryEntries(root: String): List<LocalDirectoryEntry>? {146 if (!root.startsWith("content://")) return files.listDirectoryEntries(root)147 val resolver = AndroidAppContext.appContext?.contentResolver ?: return null148 val uri = Uri.parse(root)149 if (treeUri(root) == null || !hasPersistedReadGrant(resolver, uri)) return null150 val document = querySafDocument(resolver, uri)?.takeIf { it.isDirectory } ?: return null151 return querySafChildren(resolver, document.uri)?.map { LocalDirectoryEntry(it.uri.toString(), it.name, it.isDirectory) }152 ?.sortedBy { it.name.lowercase() }153 }154155 override fun listLocalEntries(root: String): List<LocalEntry>? {156 val context = AndroidAppContext.appContext157 if (context != null && root.startsWith("content://") && treeUri(root) != null) {158 return listSafLocalEntries(context.contentResolver, Uri.parse(root))159 }160 return files.listLocalEntries(root)161 }162163 private data class SafDocument(164 val uri: Uri,165 val name: String,166 val mimeType: String,167 val size: Long,168 val lastModified: Long,169 ) {170 val isDirectory: Boolean get() = mimeType == DocumentsContract.Document.MIME_TYPE_DIR171 val isReadableFile: Boolean172 get() = !isDirectory && name.substringAfterLast('.', "").lowercase() in readableLocalFileExtensions173 }174175 private fun listSafLocalEntries(resolver: ContentResolver, root: Uri): List<LocalEntry>? {176 if (!hasPersistedReadGrant(resolver, root)) return null177 val rootDocument = querySafDocument(resolver, root) ?: return null178 if (!rootDocument.isDirectory) return null179 return collectSafLocalEntries(resolver, rootDocument.uri, mutableSetOf())180 }181182 private fun collectSafLocalEntries(183 resolver: ContentResolver,184 directory: Uri,185 visited: MutableSet<String>,186 ): List<LocalEntry>? {187 val documentId = runCatching { DocumentsContract.getDocumentId(directory) }.getOrNull() ?: return null188 if (!visited.add(documentId)) return null189 val children = querySafChildren(resolver, directory) ?: return null190 val entries = mutableListOf<LocalEntry>()191 for (child in children.sortedBy { it.name.lowercase() }) {192 if (child.isDirectory) {193 val containsReadableFile = querySafChildren(resolver, child.uri)?.any { it.isReadableFile } ?: return null194 if (containsReadableFile) {195 entries += LocalEntry(child.uri.toString(), child.name, isArchive = false)196 } else {197 entries += collectSafLocalEntries(resolver, child.uri, visited) ?: return null198 }199 } else if (child.isReadableFile) {200 entries += LocalEntry(child.uri.toString(), child.name.substringBeforeLast('.'), isArchive = true)201 }202 }203 return entries204 }205206 private fun listSafFiles(resolver: ContentResolver, root: Uri): List<LocalFileEntry>? {207 if (!hasPersistedReadGrant(resolver, root)) return null208 val rootDocument = querySafDocument(resolver, root) ?: return null209 if (!rootDocument.isDirectory) return null210 return querySafChildren(resolver, rootDocument.uri)?.filterNot { it.isDirectory }211 ?.sortedByDescending { it.lastModified }212 ?.map { LocalFileEntry(it.uri.toString(), it.name, it.size, it.lastModified) }213 }214215 private fun directorySizeSaf(resolver: ContentResolver, root: Uri): Long {216 if (!hasPersistedReadGrant(resolver, root)) return 0L217 val document = querySafDocument(resolver, root) ?: return 0L218 if (!document.isDirectory) return document.size219 return directorySizeSafChildren(resolver, document.uri, mutableSetOf())220 }221222 private fun directorySizeSafChildren(223 resolver: ContentResolver,224 directory: Uri,225 visited: MutableSet<String>,226 ): Long {227 val id = runCatching { DocumentsContract.getDocumentId(directory) }.getOrNull() ?: return 0L228 if (!visited.add(id)) return 0L229 return querySafChildren(resolver, directory)?.sumOf { child ->230 if (child.isDirectory) directorySizeSafChildren(resolver, child.uri, visited) else child.size.coerceAtLeast(0L)231 } ?: 0L232 }233234 private fun querySafDocument(resolver: ContentResolver, path: Uri): SafDocument? = runCatching {235 val uri = safDocumentUri(resolver, path) ?: return@runCatching null236 resolver.query(uri, documentProjection, null, null, null)?.use { cursor ->237 if (!cursor.moveToFirst()) return@use null238 readSafDocument(uri, cursor)239 }240 }.getOrNull()241242 private fun querySafChildren(resolver: ContentResolver, directory: Uri): List<SafDocument>? = runCatching {243 val tree = treeUri(directory.toString()) ?: return@runCatching null244 val directoryId = DocumentsContract.getDocumentId(safDocumentUri(resolver, directory) ?: return@runCatching null)245 val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, directoryId)246 resolver.query(childrenUri, documentProjection, null, null, null)?.use { cursor ->247 buildList<SafDocument> {248 while (cursor.moveToNext()) add(readSafDocument(249 DocumentsContract.buildDocumentUriUsingTree(tree, cursor.stringColumn(DocumentsContract.Document.COLUMN_DOCUMENT_ID)),250 cursor,251 ))252 }253 }254 }.getOrNull()255256 private fun readSafDocument(uri: Uri, cursor: Cursor): SafDocument {257 check(cursor.stringColumn(DocumentsContract.Document.COLUMN_DOCUMENT_ID).isNotBlank()) {258 "SAF provider returned a document without an id"259 }260 val name = cursor.stringColumn(DocumentsContract.Document.COLUMN_DISPLAY_NAME)261 val mimeType = cursor.stringColumn(DocumentsContract.Document.COLUMN_MIME_TYPE)262 check(name.isNotBlank() && mimeType.isNotBlank()) { "SAF provider returned an invalid document" }263 val size = cursor.longColumn(DocumentsContract.Document.COLUMN_SIZE)264 val lastModified = cursor.longColumn(DocumentsContract.Document.COLUMN_LAST_MODIFIED)265 return SafDocument(uri, name, mimeType, size, lastModified)266 }267268 private fun safDocumentUri(resolver: ContentResolver, uri: Uri): Uri? = runCatching {269 val tree = treeUri(uri.toString()) ?: return@runCatching null270 val path = safDocumentPath(uri.pathSegments) ?: return@runCatching null271 var current = DocumentsContract.buildDocumentUriUsingTree(tree, path.documentId)272 for (name in path.children) {273 current = querySafChildren(resolver, current)274 ?.firstOrNull { child -> child.name == name }275 ?.uri276 ?: return@runCatching null277 }278 current279 }.getOrNull()280281 private fun treeUri(path: String): Uri? = runCatching {282 val uri = Uri.parse(path)283 if (uri.scheme != "content") return@runCatching null284 DocumentsContract.buildTreeDocumentUri(uri.authority, DocumentsContract.getTreeDocumentId(uri))285 }.getOrNull()286287 private fun hasPersistedReadGrant(resolver: ContentResolver, path: Uri): Boolean {288 val tree = treeUri(path.toString()) ?: return false289 val granted = resolver.persistedUriPermissions.any {290 it.uri == tree && it.isReadPermission291 }292 if (!granted) {293 runCatching {294 resolver.releasePersistableUriPermission(295 tree,296 Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION,297 )298 }299 }300 return granted301 }302303 private companion object {304 val documentProjection = arrayOf(305 DocumentsContract.Document.COLUMN_DOCUMENT_ID,306 DocumentsContract.Document.COLUMN_DISPLAY_NAME,307 DocumentsContract.Document.COLUMN_MIME_TYPE,308 DocumentsContract.Document.COLUMN_SIZE,309 DocumentsContract.Document.COLUMN_LAST_MODIFIED,310 )311 }312}313314/** Opens a local directory in the system file manager. */315internal fun openAndroidDirectory(directory: java.io.File): Boolean {316 val context = AndroidAppContext.appContext ?: return false317 context.startActivity(Intent(Intent.ACTION_VIEW).apply {318 setDataAndType(Uri.fromFile(directory), "resource/folder")319 addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)320 })321 return true322}323324internal fun Cursor.stringColumn(name: String): String {325 val index = getColumnIndex(name)326 return if (index >= 0 && !isNull(index)) getString(index) else ""327}328329internal fun Cursor.longColumn(name: String): Long {330 val index = getColumnIndex(name)331 return if (index >= 0 && !isNull(index)) getLong(index) else 0L332}333