musikr.fs: prototype file tree caching

This commit is contained in:
Alexander Capehart
2025-05-14 12:06:25 -06:00
parent b3f51ea4b7
commit 93c892afed
3 changed files with 234 additions and 47 deletions
@@ -22,62 +22,69 @@ import android.content.ContentResolver
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import android.provider.DocumentsContract import android.provider.DocumentsContract
import android.util.Log import androidx.core.net.toUri
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.flow.takeWhile
import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.Path import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.DocumentPathFactory
internal interface DeviceFS { internal interface DeviceFS {
suspend fun explore(locations: Flow<MusicLocation>): Flow<DeviceDirectory> fun explore(locations: Flow<MusicLocation>, fileTree: FileTree): Flow<DeviceDirectory>
companion object { companion object {
fun from(context: Context, withHidden: Boolean): DeviceFS = fun from(context: Context, withHidden: Boolean): DeviceFS =
DeviceFSImpl(context.contentResolverSafe, JsonFileTreeCache(context), withHidden) DeviceFSImpl(context.contentResolverSafe, withHidden)
} }
} }
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
private class DeviceFSImpl( private class DeviceFSImpl(
private val contentResolver: ContentResolver, private val contentResolver: ContentResolver,
private val cache: FileTreeCache,
private val withHidden: Boolean private val withHidden: Boolean
) : DeviceFS { ) : DeviceFS {
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceDirectory> { override fun explore(locations: Flow<MusicLocation>, fileTree: FileTree) =
locations.mapNotNull { location -> locations.mapNotNull { location ->
val treeDocumentId = queryRoot(location, fileTree)
DocumentsContract.getTreeDocumentId(location.uri)
val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId)
val modifiedMs = contentResolver.useQuery(
uri,
arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
) { cursor ->
if (!cursor.moveToFirst()) return@useQuery null
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
cursor.getLong(lastModifiedIndex)
}
if (modifiedMs == null) {
return@mapNotNull null
}
query(
location.uri,
treeDocumentId,
location.path,
modifiedMs,
null
)
} }
private suspend fun queryRoot(
location: MusicLocation,
fileTree: FileTree
): DeviceDirectory? {
val treeDocumentId =
DocumentsContract.getTreeDocumentId(location.uri)
val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId)
val modifiedMs = contentResolver.useQuery(
uri,
arrayOf(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
) { cursor ->
if (!cursor.moveToFirst()) return@useQuery null
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
cursor.getLong(lastModifiedIndex)
}
if (modifiedMs == null) {
return null
}
return query(
location.uri,
treeDocumentId,
location.path,
modifiedMs,
null,
fileTree
)
} }
private suspend fun query( private suspend fun query(
@@ -86,9 +93,20 @@ private class DeviceFSImpl(
path: Path, path: Path,
modifiedMs: Long, modifiedMs: Long,
parent: DeviceDirectory?, parent: DeviceDirectory?,
fileTree: FileTree
): DeviceDirectory = coroutineScope { ): DeviceDirectory = coroutineScope {
val uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId)
val cached = fileTree.queryDirectory(uri)
if (cached != null && cached.modifiedMs == modifiedMs) {
return@coroutineScope hydrateCached(
cached = cached,
parentDir = parent,
path = path,
fileTree = fileTree
)
}
val dir = DeviceDirectoryImpl( val dir = DeviceDirectoryImpl(
uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId), uri = uri,
path = path, path = path,
modifiedMs = modifiedMs, modifiedMs = modifiedMs,
parent = parent, parent = parent,
@@ -111,6 +129,9 @@ private class DeviceFSImpl(
val lastModifiedIndex = val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED) cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val childSubdirUris = mutableListOf<String>()
val childFileUris = mutableListOf<String>()
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex) val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex) val displayName = cursor.getString(displayNameIndex)
@@ -131,8 +152,10 @@ private class DeviceFSImpl(
treeDocumentId = childId, treeDocumentId = childId,
path = newPath, path = newPath,
modifiedMs = modifiedMs, modifiedMs = modifiedMs,
parent = dir parent = dir,
fileTree = fileTree
) )
childSubdirUris.add(subdir.uri.toString())
emit(StreamedFile.More(subdir)) emit(StreamedFile.More(subdir))
} else { } else {
val size = cursor.getLong(sizeIndex) val size = cursor.getLong(sizeIndex)
@@ -146,9 +169,26 @@ private class DeviceFSImpl(
modifiedMs = lastModified, modifiedMs = lastModified,
parent = dir parent = dir
) )
val write = CachedFile(
uri = childUri.toString(),
name = displayName,
modifiedMs = lastModified,
mimeType = mimeType,
size = size
)
fileTree.updateFile(childUri, write)
childFileUris.add(childUri.toString())
emit(StreamedFile.More(file)) emit(StreamedFile.More(file))
} }
} }
val writeDir = CachedDirectory(
uri = uri.toString(),
name = requireNotNull(path.name),
modifiedMs = modifiedMs,
subdirUris = childSubdirUris,
fileUris = childFileUris
)
fileTree.updateDirectory(uri, writeDir)
emit(StreamedFile.Done) emit(StreamedFile.Done)
} }
}.shareIn(this, SharingStarted.Eagerly, replay = Int.MAX_VALUE) }.shareIn(this, SharingStarted.Eagerly, replay = Int.MAX_VALUE)
@@ -157,6 +197,42 @@ private class DeviceFSImpl(
dir dir
} }
private fun hydrateCached(
cached: CachedDirectory,
parentDir: DeviceDirectory?,
path: Path,
fileTree: FileTree
): DeviceDirectory {
val dir = DeviceDirectoryImpl(
uri = cached.uri.toUri(),
path = path,
modifiedMs = cached.modifiedMs,
parent = parentDir,
children = emptyFlow()
)
dir.children = merge(
cached.subdirUris.asFlow().map { subdirUriString ->
val subdirUri = subdirUriString.toUri()
val cachedSubdir = requireNotNull(fileTree.queryDirectory(subdirUri)) {
"No cached subdir for $subdirUri, malformed cache! Rescan needed."
}
hydrateCached(cachedSubdir, dir, dir.path.file(cachedSubdir.name), fileTree)
},
cached.fileUris.asFlow().map {
val cachedFile = requireNotNull(fileTree.queryFile(it.toUri()))
DeviceFile(
uri = it.toUri(),
path = dir.path.file(cachedFile.name),
modifiedMs = cachedFile.modifiedMs,
mimeType = cachedFile.mimeType,
size = cachedFile.size,
parent = dir
)
}
)
return dir
}
private sealed interface StreamedFile { private sealed interface StreamedFile {
data class More(val value: DeviceFSEntry) : StreamedFile data class More(val value: DeviceFSEntry) : StreamedFile
data object Done : StreamedFile data object Done : StreamedFile
@@ -21,39 +21,143 @@ package org.oxycblt.musikr.fs.device
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import android.util.Log import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import java.io.File import java.io.File
interface FileTreeCache { interface FileTreeCache {
suspend fun queryRootDirectory(uri: Uri): CachedRoot fun read(): FileTree
suspend fun updateRootDirectory(uri: Uri, cachedRoot: CachedRoot) }
suspend fun queryDirectory(uri: Uri): CachedDirectory interface FileTree {
suspend fun queryDirectory(uri: Uri): CachedDirectory?
suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) suspend fun updateDirectory(uri: Uri, directory: CachedDirectory)
suspend fun queryFile(uri: Uri): CachedFile? suspend fun queryFile(uri: Uri): CachedFile?
suspend fun updateFile(uri: Uri, file: CachedFile) suspend fun updateFile(uri: Uri, file: CachedFile)
suspend fun write()
} }
data class CachedRoot( // Define the sealed interface
val uri: String, @Serializable
val path: String, sealed interface FileSystemEntry {
val modifiedMs: Long, val uri: String
val childUris: List<String> val modifiedMs: Long
) }
@Serializable
data class CachedDirectory( data class CachedDirectory(
val uri: String, override val uri: String,
val name: String, val name: String,
val modifiedMs: Long, override val modifiedMs: Long,
val childUris: List<String> val subdirUris: List<String>,
) val fileUris: List<String>
) : FileSystemEntry
@Serializable
data class CachedFile( data class CachedFile(
val uri: String, override val uri: String,
val name: String, val name: String,
val modifiedMs: Long, override val modifiedMs: Long,
val mimeType: String, val mimeType: String,
val size: Long val size: Long
) : FileSystemEntry
@Serializable
data class FileTreeData(
val directories: Map<String, CachedDirectory> = mapOf(),
val files: Map<String, CachedFile> = mapOf()
) )
class FileTreeCacheImpl(private val context: Context) : FileTreeCache {
companion object {
private const val TAG = "FileTreeCache"
private const val CACHE_FILENAME = "file_tree_cache.json"
private val json = Json {
ignoreUnknownKeys = true
prettyPrint = true
}
}
override fun read(): FileTree {
val cacheFile = File(context.cacheDir, CACHE_FILENAME)
return if (cacheFile.exists()) {
try {
val jsonContent = cacheFile.readText()
val fileTreeCache = json.decodeFromString<FileTreeData>(jsonContent)
FileTreeImpl(context, fileTreeCache.directories.toMutableMap(), fileTreeCache.files.toMutableMap())
} catch (e: Exception) {
Log.e(TAG, "Failed to read cache file", e)
FileTreeImpl(context, mutableMapOf(), mutableMapOf())
}
} else {
Log.i(TAG, "Cache file does not exist, creating new FileTree")
FileTreeImpl(context, mutableMapOf(), mutableMapOf())
}
}
}
class FileTreeImpl(
private val context: Context,
private val mutableDirectories: MutableMap<String, CachedDirectory> = mutableMapOf(),
private val mutableFiles: MutableMap<String, CachedFile> = mutableMapOf()
) : FileTree {
companion object {
private const val TAG = "FileTree"
private const val CACHE_FILENAME = "file_tree_cache.json"
private val json = Json {
ignoreUnknownKeys = true
prettyPrint = true
}
}
// Directory operations
override suspend fun queryDirectory(uri: Uri): CachedDirectory? {
Log.d("FileTreeCache", "Querying directory: $uri ${mutableDirectories[uri.toString()]}")
val uriString = uri.toString()
return mutableDirectories[uriString]
}
override suspend fun updateDirectory(uri: Uri, directory: CachedDirectory) {
Log.d("FileTreeCache", "Updating directory: $uri")
val uriString = uri.toString()
mutableDirectories[uriString] = directory
}
// File operations
override suspend fun queryFile(uri: Uri): CachedFile? {
Log.d("FileTreeCache", "Querying file: $uri")
val uriString = uri.toString()
return mutableFiles[uriString]
}
override suspend fun updateFile(uri: Uri, file: CachedFile) {
Log.d("FileTreeCache", "Updating file: $uri")
val uriString = uri.toString()
mutableFiles[uriString] = file
}
override suspend fun write() = withContext(Dispatchers.IO) {
Log.d(TAG, "Writing cache to disk")
val cacheFile = File(context.cacheDir, CACHE_FILENAME)
try {
val fileTreeCache = FileTreeData(
directories = mutableDirectories.toMap(),
files = mutableFiles.toMap()
)
val jsonContent = json.encodeToString(fileTreeCache)
cacheFile.writeText(jsonContent)
Log.d(TAG, "Successfully wrote cache to disk")
} catch (e: Exception) {
Log.e(TAG, "Failed to write cache file", e)
}
Unit
}
}
@@ -32,6 +32,7 @@ import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onCompletion
import org.oxycblt.musikr.Interpretation import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Storage import org.oxycblt.musikr.Storage
import org.oxycblt.musikr.cache.Cache import org.oxycblt.musikr.cache.Cache
@@ -42,6 +43,8 @@ import org.oxycblt.musikr.covers.CoverResult
import org.oxycblt.musikr.covers.Covers import org.oxycblt.musikr.covers.Covers
import org.oxycblt.musikr.fs.MusicLocation import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.device.DeviceFS import org.oxycblt.musikr.fs.device.DeviceFS
import org.oxycblt.musikr.fs.device.FileTreeCache
import org.oxycblt.musikr.fs.device.FileTreeCacheImpl
import org.oxycblt.musikr.fs.device.flatten import org.oxycblt.musikr.fs.device.flatten
import org.oxycblt.musikr.playlist.db.StoredPlaylists import org.oxycblt.musikr.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.m3u.M3U import org.oxycblt.musikr.playlist.m3u.M3U
@@ -55,6 +58,7 @@ internal interface ExploreStep {
DeviceFS.from(context, interpretation.withHidden), DeviceFS.from(context, interpretation.withHidden),
storage.cache, storage.cache,
storage.covers, storage.covers,
FileTreeCacheImpl(context),
storage.storedPlaylists) storage.storedPlaylists)
} }
} }
@@ -63,15 +67,18 @@ private class ExploreStepImpl(
private val deviceFS: DeviceFS, private val deviceFS: DeviceFS,
private val cache: Cache, private val cache: Cache,
private val covers: Covers<out Cover>, private val covers: Covers<out Cover>,
private val fileTreeCache: FileTreeCache,
private val storedPlaylists: StoredPlaylists private val storedPlaylists: StoredPlaylists
) : ExploreStep { ) : ExploreStep {
@OptIn(ExperimentalCoroutinesApi::class) @OptIn(ExperimentalCoroutinesApi::class)
override fun explore(locations: List<MusicLocation>): Flow<Explored> { override fun explore(locations: List<MusicLocation>): Flow<Explored> {
val addingMs = System.currentTimeMillis() val addingMs = System.currentTimeMillis()
val fileTree = fileTreeCache.read()
return merge( return merge(
deviceFS deviceFS
.explore(locations.asFlow()) .explore(locations.asFlow(), fileTree)
.flatMapMerge { it.flatten() } .flatMapMerge { it.flatten() }
.onCompletion { fileTree.write() }
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE } .filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE }
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file -> .distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file ->
when (val cacheResult = cache.read(file)) { when (val cacheResult = cache.read(file)) {