package link.roadio.riff.storage.saf import android.content.ContentResolver import android.net.Uri import link.roadio.riff.storage.hash.nativeXxh3 /** Read-only current-source access; never starts Indexer, scans media or creates a root marker. * https://wiki.271.pics/Riff/1-1-0/catalog-consumption#queue-and-binding-resolution */ class SourceRootAccess internal constructor( private val readableTrees: () -> List, private val readIdentity: (String) -> String?, private val hash: (ByteArray) -> Long, ) { constructor(resolver: ContentResolver) : this( { resolver.persistedUriPermissions.filter { it.isReadPermission }.map { it.uri.toString() } }, { SourceRootMarker(resolver).resolve(Uri.parse(it), writable = false) }, ::nativeXxh3, ) // Resolve only when preparing the selected source. A grant or mount can change while Indexer // is dead, so neither a stale locator nor an earlier absence is authoritative. fun resolve(rootBindingId: Long): String? = readableTrees().distinct().sorted().firstOrNull { tree -> runCatching { readIdentity(tree)?.let { hash(it.toByteArray(Charsets.UTF_8)) } == rootBindingId }.getOrDefault(false) } }