AndroidSafLocalArchiveService.kt
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/files/AndroidSafLocalArchiveService.kt
1package eu.friedcutlet.yokan.services.files23import android.content.ContentResolver4import android.net.Uri5import android.provider.DocumentsContract6import eu.friedcutlet.yokan.AndroidAppContext7import eu.friedcutlet.yokan.util.PlatformLock8import java.io.File9import java.io.InputStream10import java.security.MessageDigest1112/**13 * [JvmLocalArchiveService] plus SAF `content://` documents. ZipFile needs a filesystem path while14 * SAF only promises a readable stream, so each document is copied once to15 * `cacheRoot/archive-staging/<cacheKey>` (uri + name + size + mtime) and reused until it falls out of16 * the [MAX_STAGED_ARCHIVES] most recently used copies; the provider URI is never opened for writing.17 */18internal class AndroidSafLocalArchiveService(19 cacheRoot: String,20 private val contentResolver: ContentResolver? = null,21 private val contentStreamOpener: ((String) -> InputStream?)? = null,22) : JvmLocalArchiveService(cacheRoot) {23 private data class ContentMetadata(24 val name: String,25 val mimeType: String?,26 val size: Long,27 val lastModified: Long,28 )2930 private val stagingRoot = File(cacheRoot, "archive-staging")31 private val stagingLock = PlatformLock()32 private var stagingGeneration = 0L3334 override fun invalidateIndexCache() {35 super.invalidateIndexCache()36 // A full scan must also bypass copies from providers with unchanged or missing timestamps.37 stagingLock.withLock { stagingGeneration = kotlin.random.Random.nextLong() }38 }3940 override fun <T> withArchiveFile(path: String, block: (ArchiveFile) -> T): T? =41 withArchiveFile(path, fresh = false, block = block)4243 override fun <T> withFreshArchiveFile(path: String, block: (ArchiveFile) -> T): T? =44 withArchiveFile(path, fresh = true, block = block)4546 private fun <T> withArchiveFile(path: String, fresh: Boolean, block: (ArchiveFile) -> T): T? {47 if (!path.startsWith("content://")) return super.withArchiveFile(path, block)48 contentStreamOpener?.let { opener ->49 val cacheKey = path.cacheKey(null)50 val staged = stage(cacheKey, fresh) { opener(path) } ?: return null51 val name = path.substringAfterLast('/').ifBlank { "archive" }52 return runCatching { block(ArchiveFile(staged, name, mimeType = null, cacheKey = cacheKey)) }.getOrNull()53 }54 val uri = runCatching { Uri.parse(path) }.getOrNull() ?: return null55 val documentUri = contentDocumentUri(uri)56 val resolver = contentResolver ?: AndroidAppContext.appContext?.contentResolver ?: return null57 val metadata = queryContentMetadata(resolver, documentUri)58 val cacheKey = path.cacheKey(metadata)59 val staged = stage(cacheKey, fresh) { resolver.openInputStream(documentUri) } ?: return null60 val name = metadata?.name?.takeIf(String::isNotBlank) ?: uri.lastPathSegment.orEmpty().ifBlank { "archive" }61 return runCatching { block(ArchiveFile(staged, name, metadata?.mimeType, cacheKey)) }.getOrNull()62 }6364 /**65 * The staged copy for [cacheKey]: reused (and marked used) when present, else copied from66 * [openStream] through a temp file so a failed copy never looks staged. Null when the copy fails.67 */68 // ponytail: pruning can delete a copy between another reader's touch and open once >3 documents are69 // read concurrently (that read returns null); add per-key refcounts if that shows up.70 private fun stage(cacheKey: String, fresh: Boolean, openStream: () -> InputStream?): File? {71 val target = File(stagingRoot, cacheKey)72 if (fresh) stagingLock.withLock { target.delete() }73 val reused = stagingLock.withLock {74 target.isFile.also { present -> if (present) target.setLastModified(System.currentTimeMillis()) }75 }76 if (reused) return target77 if (!stagingRoot.exists() && !stagingRoot.mkdirs()) return null78 val partial = runCatching { File.createTempFile("archive-", ".tmp", stagingRoot) }.getOrNull() ?: return null79 val copied = runCatching {80 openStream()?.use { input -> partial.outputStream().use { output -> input.copyTo(output) } } != null81 }.getOrDefault(false)82 return stagingLock.withLock {83 // A concurrent read may have staged the same document meanwhile; both copies are current.84 val staged = copied && (target.isFile || partial.renameTo(target))85 partial.delete()86 if (!staged) return@withLock null87 pruneLeastRecentlyUsed(stagingRoot, keep = target, maxBytes = Long.MAX_VALUE, maxEntries = MAX_STAGED_ARCHIVES)88 target89 }90 }9192 private fun contentDocumentUri(uri: Uri): Uri = runCatching {93 if (DocumentsContract.isTreeUri(uri)) {94 val documentId = if (uri.pathSegments.getOrNull(2) == "document") {95 DocumentsContract.getDocumentId(uri)96 } else {97 DocumentsContract.getTreeDocumentId(uri)98 }99 DocumentsContract.buildDocumentUriUsingTree(uri, documentId)100 } else {101 uri102 }103 }.getOrDefault(uri)104105 private fun queryContentMetadata(resolver: ContentResolver, uri: Uri): ContentMetadata? = runCatching {106 resolver.query(107 uri,108 arrayOf(109 DocumentsContract.Document.COLUMN_DISPLAY_NAME,110 DocumentsContract.Document.COLUMN_MIME_TYPE,111 DocumentsContract.Document.COLUMN_SIZE,112 DocumentsContract.Document.COLUMN_LAST_MODIFIED,113 ),114 null,115 null,116 null,117 )?.use { cursor ->118 if (!cursor.moveToFirst()) return@use null119 ContentMetadata(120 name = cursor.stringColumn(DocumentsContract.Document.COLUMN_DISPLAY_NAME),121 mimeType = cursor.stringColumn(DocumentsContract.Document.COLUMN_MIME_TYPE).takeIf(String::isNotBlank),122 size = cursor.longColumn(DocumentsContract.Document.COLUMN_SIZE),123 lastModified = cursor.longColumn(DocumentsContract.Document.COLUMN_LAST_MODIFIED),124 )125 }126 }.getOrNull()127128 private fun String.cacheKey(metadata: ContentMetadata?): String {129 val digest = MessageDigest.getInstance("SHA-1")130 digest.update(encodeToByteArray())131 digest.update(stagingLock.withLock { stagingGeneration }.toString().encodeToByteArray())132 metadata?.let {133 digest.update(it.name.encodeToByteArray())134 digest.update(it.size.toString().encodeToByteArray())135 digest.update(it.lastModified.toString().encodeToByteArray())136 }137 return digest.digest().toHexString()138 }139140 private companion object {141 // ponytail: count-only cap (3 copies, any size); add a byte budget if huge archives crowd the cache.142 const val MAX_STAGED_ARCHIVES = 3143 }144}145