musikr.fs: fully encode dir structure

Previous children did not include subdirectories
due to difficulties in recursive async queries,
now they are included at the cost children also
being asyncronously populated.
This commit is contained in:
Alexander Capehart
2025-05-12 11:36:11 -06:00
parent 1355be1e34
commit baf63b60a0
3 changed files with 58 additions and 47 deletions
@@ -99,6 +99,7 @@ class MutableFSCovers(private val context: Context) : MutableCovers<FDCover> {
val parent = file.parent.await()
val bestCover =
parent.children
.await()
.filterIsInstance<DeviceFile>()
.map { it to coverArtScore(it) }
.maxBy { it.second }
@@ -50,11 +50,13 @@ private class DeviceFSImpl(
) : DeviceFS {
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> =
locations.flatMapMerge { location ->
val (_, query) =
exploreDirectoryImpl(
location.uri,
DocumentsContract.getTreeDocumentId(location.uri),
location.path,
null)
query
}
private fun exploreDirectoryImpl(
@@ -62,10 +64,13 @@ private class DeviceFSImpl(
treeDocumentId: String,
relativePath: Path,
parent: Deferred<DeviceDirectory>?
): Flow<DeviceFile> = flow {
): Pair<DeviceDirectory, Flow<DeviceFile>> {
// Make a kotlin future
val uri = DocumentsContract.buildChildDocumentsUriUsingTree(rootUri, treeDocumentId)
val directoryDeferred = CompletableDeferred<DeviceDirectory>()
val childrenDeferred = CompletableDeferred<List<DeviceFSEntry>>()
val dir = DeviceDirectory(uri, relativePath, parent, childrenDeferred)
val query = flow {
val recursive = mutableListOf<Flow<DeviceFile>>()
val children = mutableListOf<DeviceFSEntry>()
contentResolver.useQuery(uri, PROJECTION) { cursor ->
@@ -93,8 +98,10 @@ private class DeviceFSImpl(
val lastModified = cursor.getLong(lastModifiedIndex)
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
recursive.add(
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred))
val (dir, query) =
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)
children.add(dir)
recursive.add(query)
} else {
val size = cursor.getLong(sizeIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
@@ -110,10 +117,13 @@ private class DeviceFSImpl(
emit(file)
}
}
directoryDeferred.complete(DeviceDirectory(uri, relativePath, parent, children))
childrenDeferred.complete(children)
directoryDeferred.complete(dir)
emitAll(recursive.asFlow().flattenMerge())
}
}
return dir to query
}
private companion object {
val PROJECTION =
@@ -31,7 +31,7 @@ data class DeviceDirectory(
override val uri: Uri,
override val path: Path,
val parent: Deferred<DeviceDirectory>?,
var children: List<DeviceFSEntry>
var children: Deferred<List<DeviceFSEntry>>
) : DeviceFSEntry
data class DeviceFile(