package eu.friedcutlet.yokan.services.files import android.content.ContentResolver import android.content.Intent import android.database.Cursor import android.net.Uri import android.provider.DocumentsContract import eu.friedcutlet.yokan.AndroidAppContext /** * [JvmLocalFileService] plus SAF `content://` paths. Persisted tree grants are read-only local * folders: they can be listed, read and opened, never written or deleted. A separately picked * `content://` document (not under a tree) keeps write support. */ internal class AndroidSafLocalFileService( private val files: JvmLocalFileService, ) : LocalFileService by files { override fun writeBytes(path: String, bytes: ByteArray) { if (!path.startsWith("content://")) return files.writeBytes(path, bytes) if (treeUri(path) != null) return val context = AndroidAppContext.appContext ?: return context.contentResolver.openOutputStream(Uri.parse(path), "wt")?.use { it.write(bytes) } } override fun appendBytes(path: String, bytes: ByteArray) { if (!path.startsWith("content://")) return files.appendBytes(path, bytes) if (treeUri(path) != null) return val context = AndroidAppContext.appContext ?: return context.contentResolver.openOutputStream(Uri.parse(path), "wa")?.use { it.write(bytes) } } override suspend fun writeChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = if (path.startsWith("content://")) super.writeChunks(path, block) else files.writeChunks(path, block) override suspend fun appendChunks(path: String, block: suspend (write: suspend (ByteArray) -> Unit) -> T): T = if (path.startsWith("content://")) super.appendChunks(path, block) else files.appendChunks(path, block) override fun promote(sourcePath: String, targetPath: String): Boolean = if (sourcePath.startsWith("content://") || targetPath.startsWith("content://")) { // Provider documents cannot be moved atomically; copy through the resolver instead. super.promote(sourcePath, targetPath) } else { files.promote(sourcePath, targetPath) } override fun atomicReplaceFile(tempPath: String, finalPath: String): Boolean = if (tempPath.startsWith("content://") || finalPath.startsWith("content://")) false else files.atomicReplaceFile(tempPath, finalPath) override fun publishDirectoryIfAbsent(stagedPath: String, finalPath: String): Boolean = if (stagedPath.startsWith("content://") || finalPath.startsWith("content://")) false else files.publishDirectoryIfAbsent(stagedPath, finalPath) override fun canonicalPath(path: String): String? = if (path.startsWith("content://")) null else files.canonicalPath(path) override fun readBytes(path: String): ByteArray { if (!path.startsWith("content://")) return files.readBytes(path) val context = AndroidAppContext.appContext ?: return ByteArray(0) return runCatching { val uri = Uri.parse(path) if (treeUri(path) != null && !hasPersistedReadGrant(context.contentResolver, uri)) return@runCatching null val documentUri = safDocumentUri(context.contentResolver, uri) ?: uri context.contentResolver.openInputStream(documentUri)?.use { it.readBytes() } }.getOrNull() ?: ByteArray(0) } override fun mimeType(path: String): String? { if (!path.startsWith("content://")) return files.mimeType(path) val context = AndroidAppContext.appContext ?: return null return runCatching { context.contentResolver.getType(Uri.parse(path)) }.getOrNull() } override fun readBytesBounded(path: String, maxBytes: Long): ByteArray { require(maxBytes >= 0) { "maxBytes must not be negative" } if (!path.startsWith("content://")) return files.readBytesBounded(path, maxBytes) require(maxBytes < Int.MAX_VALUE) { "Bound exceeds ByteArray capacity" } val context = AndroidAppContext.appContext ?: error("Content resolver is unavailable") val uri = Uri.parse(path) if (treeUri(path) != null) require(hasPersistedReadGrant(context.contentResolver, uri)) { "No SAF read grant" } val documentUri = safDocumentUri(context.contentResolver, uri) ?: uri val input = context.contentResolver.openInputStream(documentUri) ?: error("Cannot open $path") input.use { val output = java.io.ByteArrayOutputStream() val buffer = ByteArray(16 * 1024) var total = 0L while (total <= maxBytes) { val count = it.read(buffer, 0, minOf(buffer.size.toLong(), maxBytes + 1 - total).toInt()) if (count < 0) break output.write(buffer, 0, count) total += count } require(total <= maxBytes) { "File exceeds $maxBytes bytes" } return output.toByteArray() } } override fun listFiles(root: String): List { val context = AndroidAppContext.appContext if (context != null && root.startsWith("content://") && treeUri(root) != null) { return listSafFiles(context.contentResolver, Uri.parse(root)).orEmpty() } return files.listFiles(root) } override fun exists(path: String): Boolean { if (!path.startsWith("content://")) return files.exists(path) val context = AndroidAppContext.appContext ?: return false val uri = Uri.parse(path) return if (treeUri(path) != null) { hasPersistedReadGrant(context.contentResolver, uri) && querySafDocument(context.contentResolver, uri) != null } else { runCatching { context.contentResolver.openInputStream(uri)?.use { true } ?: false }.getOrDefault(false) } } override fun deleteRecursively(path: String): Boolean = if (path.startsWith("content://")) false else files.deleteRecursively(path) override fun directorySize(path: String): Long { val context = AndroidAppContext.appContext if (context != null && path.startsWith("content://") && treeUri(path) != null) { return directorySizeSaf(context.contentResolver, Uri.parse(path)) } return files.directorySize(path) } override fun openLocation(path: String): Boolean { if (!path.startsWith("content://")) return files.openLocation(path) val context = AndroidAppContext.appContext ?: return false val uri = Uri.parse(path) if (treeUri(path) == null || !hasPersistedReadGrant(context.contentResolver, uri)) return false return runCatching { context.startActivity(Intent(Intent.ACTION_VIEW).apply { data = uri addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK) }) true }.getOrDefault(false) } override fun listDirectoryEntries(root: String): List? { if (!root.startsWith("content://")) return files.listDirectoryEntries(root) val resolver = AndroidAppContext.appContext?.contentResolver ?: return null val uri = Uri.parse(root) if (treeUri(root) == null || !hasPersistedReadGrant(resolver, uri)) return null val document = querySafDocument(resolver, uri)?.takeIf { it.isDirectory } ?: return null return querySafChildren(resolver, document.uri)?.map { LocalDirectoryEntry(it.uri.toString(), it.name, it.isDirectory) } ?.sortedBy { it.name.lowercase() } } override fun listLocalEntries(root: String): List? { val context = AndroidAppContext.appContext if (context != null && root.startsWith("content://") && treeUri(root) != null) { return listSafLocalEntries(context.contentResolver, Uri.parse(root)) } return files.listLocalEntries(root) } private data class SafDocument( val uri: Uri, val name: String, val mimeType: String, val size: Long, val lastModified: Long, ) { val isDirectory: Boolean get() = mimeType == DocumentsContract.Document.MIME_TYPE_DIR val isReadableFile: Boolean get() = !isDirectory && name.substringAfterLast('.', "").lowercase() in readableLocalFileExtensions } private fun listSafLocalEntries(resolver: ContentResolver, root: Uri): List? { if (!hasPersistedReadGrant(resolver, root)) return null val rootDocument = querySafDocument(resolver, root) ?: return null if (!rootDocument.isDirectory) return null return collectSafLocalEntries(resolver, rootDocument.uri, mutableSetOf()) } private fun collectSafLocalEntries( resolver: ContentResolver, directory: Uri, visited: MutableSet, ): List? { val documentId = runCatching { DocumentsContract.getDocumentId(directory) }.getOrNull() ?: return null if (!visited.add(documentId)) return null val children = querySafChildren(resolver, directory) ?: return null val entries = mutableListOf() for (child in children.sortedBy { it.name.lowercase() }) { if (child.isDirectory) { val containsReadableFile = querySafChildren(resolver, child.uri)?.any { it.isReadableFile } ?: return null if (containsReadableFile) { entries += LocalEntry(child.uri.toString(), child.name, isArchive = false) } else { entries += collectSafLocalEntries(resolver, child.uri, visited) ?: return null } } else if (child.isReadableFile) { entries += LocalEntry(child.uri.toString(), child.name.substringBeforeLast('.'), isArchive = true) } } return entries } private fun listSafFiles(resolver: ContentResolver, root: Uri): List? { if (!hasPersistedReadGrant(resolver, root)) return null val rootDocument = querySafDocument(resolver, root) ?: return null if (!rootDocument.isDirectory) return null return querySafChildren(resolver, rootDocument.uri)?.filterNot { it.isDirectory } ?.sortedByDescending { it.lastModified } ?.map { LocalFileEntry(it.uri.toString(), it.name, it.size, it.lastModified) } } private fun directorySizeSaf(resolver: ContentResolver, root: Uri): Long { if (!hasPersistedReadGrant(resolver, root)) return 0L val document = querySafDocument(resolver, root) ?: return 0L if (!document.isDirectory) return document.size return directorySizeSafChildren(resolver, document.uri, mutableSetOf()) } private fun directorySizeSafChildren( resolver: ContentResolver, directory: Uri, visited: MutableSet, ): Long { val id = runCatching { DocumentsContract.getDocumentId(directory) }.getOrNull() ?: return 0L if (!visited.add(id)) return 0L return querySafChildren(resolver, directory)?.sumOf { child -> if (child.isDirectory) directorySizeSafChildren(resolver, child.uri, visited) else child.size.coerceAtLeast(0L) } ?: 0L } private fun querySafDocument(resolver: ContentResolver, path: Uri): SafDocument? = runCatching { val uri = safDocumentUri(resolver, path) ?: return@runCatching null resolver.query(uri, documentProjection, null, null, null)?.use { cursor -> if (!cursor.moveToFirst()) return@use null readSafDocument(uri, cursor) } }.getOrNull() private fun querySafChildren(resolver: ContentResolver, directory: Uri): List? = runCatching { val tree = treeUri(directory.toString()) ?: return@runCatching null val directoryId = DocumentsContract.getDocumentId(safDocumentUri(resolver, directory) ?: return@runCatching null) val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(tree, directoryId) resolver.query(childrenUri, documentProjection, null, null, null)?.use { cursor -> buildList { while (cursor.moveToNext()) add(readSafDocument( DocumentsContract.buildDocumentUriUsingTree(tree, cursor.stringColumn(DocumentsContract.Document.COLUMN_DOCUMENT_ID)), cursor, )) } } }.getOrNull() private fun readSafDocument(uri: Uri, cursor: Cursor): SafDocument { check(cursor.stringColumn(DocumentsContract.Document.COLUMN_DOCUMENT_ID).isNotBlank()) { "SAF provider returned a document without an id" } val name = cursor.stringColumn(DocumentsContract.Document.COLUMN_DISPLAY_NAME) val mimeType = cursor.stringColumn(DocumentsContract.Document.COLUMN_MIME_TYPE) check(name.isNotBlank() && mimeType.isNotBlank()) { "SAF provider returned an invalid document" } val size = cursor.longColumn(DocumentsContract.Document.COLUMN_SIZE) val lastModified = cursor.longColumn(DocumentsContract.Document.COLUMN_LAST_MODIFIED) return SafDocument(uri, name, mimeType, size, lastModified) } private fun safDocumentUri(resolver: ContentResolver, uri: Uri): Uri? = runCatching { val tree = treeUri(uri.toString()) ?: return@runCatching null val path = safDocumentPath(uri.pathSegments) ?: return@runCatching null var current = DocumentsContract.buildDocumentUriUsingTree(tree, path.documentId) for (name in path.children) { current = querySafChildren(resolver, current) ?.firstOrNull { child -> child.name == name } ?.uri ?: return@runCatching null } current }.getOrNull() private fun treeUri(path: String): Uri? = runCatching { val uri = Uri.parse(path) if (uri.scheme != "content") return@runCatching null DocumentsContract.buildTreeDocumentUri(uri.authority, DocumentsContract.getTreeDocumentId(uri)) }.getOrNull() private fun hasPersistedReadGrant(resolver: ContentResolver, path: Uri): Boolean { val tree = treeUri(path.toString()) ?: return false val granted = resolver.persistedUriPermissions.any { it.uri == tree && it.isReadPermission } if (!granted) { runCatching { resolver.releasePersistableUriPermission( tree, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION, ) } } return granted } private companion object { val documentProjection = arrayOf( DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE, DocumentsContract.Document.COLUMN_LAST_MODIFIED, ) } } /** Opens a local directory in the system file manager. */ internal fun openAndroidDirectory(directory: java.io.File): Boolean { val context = AndroidAppContext.appContext ?: return false context.startActivity(Intent(Intent.ACTION_VIEW).apply { setDataAndType(Uri.fromFile(directory), "resource/folder") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) return true } internal fun Cursor.stringColumn(name: String): String { val index = getColumnIndex(name) return if (index >= 0 && !isNull(index)) getString(index) else "" } internal fun Cursor.longColumn(name: String): Long { val index = getColumnIndex(name) return if (index >= 0 && !isNull(index)) getLong(index) else 0L }