package eu.friedcutlet.yokan.services.files import android.content.ContentResolver import android.net.Uri import android.provider.DocumentsContract import eu.friedcutlet.yokan.AndroidAppContext import eu.friedcutlet.yokan.util.PlatformLock import java.io.File import java.io.InputStream import java.security.MessageDigest /** * [JvmLocalArchiveService] plus SAF `content://` documents. ZipFile needs a filesystem path while * SAF only promises a readable stream, so each document is copied once to * `cacheRoot/archive-staging/` (uri + name + size + mtime) and reused until it falls out of * the [MAX_STAGED_ARCHIVES] most recently used copies; the provider URI is never opened for writing. */ internal class AndroidSafLocalArchiveService( cacheRoot: String, private val contentResolver: ContentResolver? = null, private val contentStreamOpener: ((String) -> InputStream?)? = null, ) : JvmLocalArchiveService(cacheRoot) { private data class ContentMetadata( val name: String, val mimeType: String?, val size: Long, val lastModified: Long, ) private val stagingRoot = File(cacheRoot, "archive-staging") private val stagingLock = PlatformLock() private var stagingGeneration = 0L override fun invalidateIndexCache() { super.invalidateIndexCache() // A full scan must also bypass copies from providers with unchanged or missing timestamps. stagingLock.withLock { stagingGeneration = kotlin.random.Random.nextLong() } } override fun withArchiveFile(path: String, block: (ArchiveFile) -> T): T? = withArchiveFile(path, fresh = false, block = block) override fun withFreshArchiveFile(path: String, block: (ArchiveFile) -> T): T? = withArchiveFile(path, fresh = true, block = block) private fun withArchiveFile(path: String, fresh: Boolean, block: (ArchiveFile) -> T): T? { if (!path.startsWith("content://")) return super.withArchiveFile(path, block) contentStreamOpener?.let { opener -> val cacheKey = path.cacheKey(null) val staged = stage(cacheKey, fresh) { opener(path) } ?: return null val name = path.substringAfterLast('/').ifBlank { "archive" } return runCatching { block(ArchiveFile(staged, name, mimeType = null, cacheKey = cacheKey)) }.getOrNull() } val uri = runCatching { Uri.parse(path) }.getOrNull() ?: return null val documentUri = contentDocumentUri(uri) val resolver = contentResolver ?: AndroidAppContext.appContext?.contentResolver ?: return null val metadata = queryContentMetadata(resolver, documentUri) val cacheKey = path.cacheKey(metadata) val staged = stage(cacheKey, fresh) { resolver.openInputStream(documentUri) } ?: return null val name = metadata?.name?.takeIf(String::isNotBlank) ?: uri.lastPathSegment.orEmpty().ifBlank { "archive" } return runCatching { block(ArchiveFile(staged, name, metadata?.mimeType, cacheKey)) }.getOrNull() } /** * The staged copy for [cacheKey]: reused (and marked used) when present, else copied from * [openStream] through a temp file so a failed copy never looks staged. Null when the copy fails. */ // ponytail: pruning can delete a copy between another reader's touch and open once >3 documents are // read concurrently (that read returns null); add per-key refcounts if that shows up. private fun stage(cacheKey: String, fresh: Boolean, openStream: () -> InputStream?): File? { val target = File(stagingRoot, cacheKey) if (fresh) stagingLock.withLock { target.delete() } val reused = stagingLock.withLock { target.isFile.also { present -> if (present) target.setLastModified(System.currentTimeMillis()) } } if (reused) return target if (!stagingRoot.exists() && !stagingRoot.mkdirs()) return null val partial = runCatching { File.createTempFile("archive-", ".tmp", stagingRoot) }.getOrNull() ?: return null val copied = runCatching { openStream()?.use { input -> partial.outputStream().use { output -> input.copyTo(output) } } != null }.getOrDefault(false) return stagingLock.withLock { // A concurrent read may have staged the same document meanwhile; both copies are current. val staged = copied && (target.isFile || partial.renameTo(target)) partial.delete() if (!staged) return@withLock null pruneLeastRecentlyUsed(stagingRoot, keep = target, maxBytes = Long.MAX_VALUE, maxEntries = MAX_STAGED_ARCHIVES) target } } private fun contentDocumentUri(uri: Uri): Uri = runCatching { if (DocumentsContract.isTreeUri(uri)) { val documentId = if (uri.pathSegments.getOrNull(2) == "document") { DocumentsContract.getDocumentId(uri) } else { DocumentsContract.getTreeDocumentId(uri) } DocumentsContract.buildDocumentUriUsingTree(uri, documentId) } else { uri } }.getOrDefault(uri) private fun queryContentMetadata(resolver: ContentResolver, uri: Uri): ContentMetadata? = runCatching { resolver.query( uri, arrayOf( DocumentsContract.Document.COLUMN_DISPLAY_NAME, DocumentsContract.Document.COLUMN_MIME_TYPE, DocumentsContract.Document.COLUMN_SIZE, DocumentsContract.Document.COLUMN_LAST_MODIFIED, ), null, null, null, )?.use { cursor -> if (!cursor.moveToFirst()) return@use null ContentMetadata( name = cursor.stringColumn(DocumentsContract.Document.COLUMN_DISPLAY_NAME), mimeType = cursor.stringColumn(DocumentsContract.Document.COLUMN_MIME_TYPE).takeIf(String::isNotBlank), size = cursor.longColumn(DocumentsContract.Document.COLUMN_SIZE), lastModified = cursor.longColumn(DocumentsContract.Document.COLUMN_LAST_MODIFIED), ) } }.getOrNull() private fun String.cacheKey(metadata: ContentMetadata?): String { val digest = MessageDigest.getInstance("SHA-1") digest.update(encodeToByteArray()) digest.update(stagingLock.withLock { stagingGeneration }.toString().encodeToByteArray()) metadata?.let { digest.update(it.name.encodeToByteArray()) digest.update(it.size.toString().encodeToByteArray()) digest.update(it.lastModified.toString().encodeToByteArray()) } return digest.digest().toHexString() } private companion object { // ponytail: count-only cap (3 copies, any size); add a byte budget if huge archives crowd the cache. const val MAX_STAGED_ARCHIVES = 3 } }