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.net.Uri
import android.provider.DocumentsContract
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import androidx.core.net.toUri
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.takeWhile
import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.Path
import org.oxycblt.musikr.fs.path.DocumentPathFactory
internal interface DeviceFS {
suspend fun explore(locations: Flow<MusicLocation>): Flow<DeviceDirectory>
fun explore(locations: Flow<MusicLocation>, fileTree: FileTree): Flow<DeviceDirectory>
companion object {
fun from(context: Context, withHidden: Boolean): DeviceFS =
DeviceFSImpl(context.contentResolverSafe, JsonFileTreeCache(context), withHidden)
DeviceFSImpl(context.contentResolverSafe, withHidden)
}
}
@OptIn(ExperimentalCoroutinesApi::class)
private class DeviceFSImpl(
private val contentResolver: ContentResolver,
private val cache: FileTreeCache,
private val withHidden: Boolean
) : DeviceFS {
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceDirectory> {
override fun explore(locations: Flow<MusicLocation>, fileTree: FileTree) =
locations.mapNotNull { location ->
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@mapNotNull null
}
query(
location.uri,
treeDocumentId,
location.path,
modifiedMs,
null
)
queryRoot(location, fileTree)
}
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(
@@ -86,9 +93,20 @@ private class DeviceFSImpl(
path: Path,
modifiedMs: Long,
parent: DeviceDirectory?,
fileTree: FileTree
): 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(
uri = DocumentsContract.buildDocumentUriUsingTree(rootUri, treeDocumentId),
uri = uri,
path = path,
modifiedMs = modifiedMs,
parent = parent,
@@ -111,6 +129,9 @@ private class DeviceFSImpl(
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val childSubdirUris = mutableListOf<String>()
val childFileUris = mutableListOf<String>()
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
@@ -131,8 +152,10 @@ private class DeviceFSImpl(
treeDocumentId = childId,
path = newPath,
modifiedMs = modifiedMs,
parent = dir
parent = dir,
fileTree = fileTree
)
childSubdirUris.add(subdir.uri.toString())
emit(StreamedFile.More(subdir))
} else {
val size = cursor.getLong(sizeIndex)
@@ -146,9 +169,26 @@ private class DeviceFSImpl(
modifiedMs = lastModified,
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))
}
}
val writeDir = CachedDirectory(
uri = uri.toString(),
name = requireNotNull(path.name),
modifiedMs = modifiedMs,
subdirUris = childSubdirUris,
fileUris = childFileUris
)
fileTree.updateDirectory(uri, writeDir)
emit(StreamedFile.Done)
}
}.shareIn(this, SharingStarted.Eagerly, replay = Int.MAX_VALUE)
@@ -157,6 +197,42 @@ private class DeviceFSImpl(
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 {
data class More(val value: DeviceFSEntry) : StreamedFile
data object Done : StreamedFile
@@ -21,39 +21,143 @@ package org.oxycblt.musikr.fs.device
import android.content.Context
import android.net.Uri
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import java.io.File
interface FileTreeCache {
suspend fun queryRootDirectory(uri: Uri): CachedRoot
suspend fun updateRootDirectory(uri: Uri, cachedRoot: CachedRoot)
fun read(): FileTree
}
suspend fun queryDirectory(uri: Uri): CachedDirectory
interface FileTree {
suspend fun queryDirectory(uri: Uri): CachedDirectory?
suspend fun updateDirectory(uri: Uri, directory: CachedDirectory)
suspend fun queryFile(uri: Uri): CachedFile?
suspend fun updateFile(uri: Uri, file: CachedFile)
suspend fun write()
}
data class CachedRoot(
val uri: String,
val path: String,
val modifiedMs: Long,
val childUris: List<String>
)
// Define the sealed interface
@Serializable
sealed interface FileSystemEntry {
val uri: String
val modifiedMs: Long
}
@Serializable
data class CachedDirectory(
val uri: String,
override val uri: String,
val name: String,
val modifiedMs: Long,
val childUris: List<String>
)
override val modifiedMs: Long,
val subdirUris: List<String>,
val fileUris: List<String>
) : FileSystemEntry
@Serializable
data class CachedFile(
val uri: String,
override val uri: String,
val name: String,
val modifiedMs: Long,
override val modifiedMs: Long,
val mimeType: String,
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.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onCompletion
import org.oxycblt.musikr.Interpretation
import org.oxycblt.musikr.Storage
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.fs.MusicLocation
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.playlist.db.StoredPlaylists
import org.oxycblt.musikr.playlist.m3u.M3U
@@ -55,6 +58,7 @@ internal interface ExploreStep {
DeviceFS.from(context, interpretation.withHidden),
storage.cache,
storage.covers,
FileTreeCacheImpl(context),
storage.storedPlaylists)
}
}
@@ -63,15 +67,18 @@ private class ExploreStepImpl(
private val deviceFS: DeviceFS,
private val cache: Cache,
private val covers: Covers<out Cover>,
private val fileTreeCache: FileTreeCache,
private val storedPlaylists: StoredPlaylists
) : ExploreStep {
@OptIn(ExperimentalCoroutinesApi::class)
override fun explore(locations: List<MusicLocation>): Flow<Explored> {
val addingMs = System.currentTimeMillis()
val fileTree = fileTreeCache.read()
return merge(
deviceFS
.explore(locations.asFlow())
.explore(locations.asFlow(), fileTree)
.flatMapMerge { it.flatten() }
.onCompletion { fileTree.write() }
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE }
.distributedMap(n = 8, on = Dispatchers.IO, buffer = Channel.UNLIMITED) { file ->
when (val cacheResult = cache.read(file)) {