@@ -18,6 +18,7 @@
|
|||||||
|
|
||||||
package org.oxycblt.musikr.fs.device
|
package org.oxycblt.musikr.fs.device
|
||||||
|
|
||||||
|
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
|
||||||
@@ -34,6 +35,7 @@ import kotlinx.coroutines.flow.flattenMerge
|
|||||||
import kotlinx.coroutines.flow.flow
|
import kotlinx.coroutines.flow.flow
|
||||||
import kotlinx.coroutines.flow.flowOn
|
import kotlinx.coroutines.flow.flowOn
|
||||||
import kotlinx.coroutines.flow.onCompletion
|
import kotlinx.coroutines.flow.onCompletion
|
||||||
|
import kotlinx.coroutines.flow.onStart
|
||||||
import org.oxycblt.musikr.fs.MusicLocation
|
import org.oxycblt.musikr.fs.MusicLocation
|
||||||
import org.oxycblt.musikr.fs.Path
|
import org.oxycblt.musikr.fs.Path
|
||||||
|
|
||||||
@@ -49,34 +51,35 @@ internal interface DeviceFS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@OptIn(ExperimentalCoroutinesApi::class)
|
@OptIn(ExperimentalCoroutinesApi::class)
|
||||||
private class DeviceFSImpl(private val context: Context, private val withHidden: Boolean) :
|
private class DeviceFSImpl(
|
||||||
DeviceFS {
|
private val context: Context,
|
||||||
|
private val withHidden: Boolean
|
||||||
|
) : DeviceFS {
|
||||||
private val contentResolver = context.contentResolverSafe
|
private val contentResolver = context.contentResolverSafe
|
||||||
private val cache = DeviceFSCache(context)
|
private val cache = DeviceFSCache(context)
|
||||||
|
|
||||||
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> =
|
override fun explore(locations: Flow<MusicLocation>): Flow<DeviceFile> =
|
||||||
flow {
|
flow {
|
||||||
// Initialize the cache
|
// Initialize the cache
|
||||||
cache.loadCache()
|
cache.loadCache()
|
||||||
// Start a new traversal to track processed URIs for cleanup
|
// Start a new traversal to track processed URIs for cleanup
|
||||||
cache.resetTraversalTracking()
|
cache.resetTraversalTracking()
|
||||||
|
|
||||||
emitAll(
|
emitAll(
|
||||||
locations
|
locations.flatMapMerge { location ->
|
||||||
.flatMapMerge { location ->
|
exploreDirectoryImpl(
|
||||||
exploreDirectoryImpl(
|
location.uri,
|
||||||
location.uri,
|
DocumentsContract.getTreeDocumentId(location.uri),
|
||||||
DocumentsContract.getTreeDocumentId(location.uri),
|
location.path,
|
||||||
location.path,
|
null
|
||||||
null)
|
)
|
||||||
}
|
}.flowOn(Dispatchers.IO)
|
||||||
.flowOn(Dispatchers.IO))
|
)
|
||||||
}
|
}.onCompletion {
|
||||||
.onCompletion {
|
// Cleanup and save cache when exploration is complete
|
||||||
// Cleanup and save cache when exploration is complete
|
cache.cleanupCache()
|
||||||
cache.cleanupCache()
|
cache.saveCache()
|
||||||
cache.saveCache()
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private fun exploreDirectoryImpl(
|
private fun exploreDirectoryImpl(
|
||||||
rootUri: Uri,
|
rootUri: Uri,
|
||||||
@@ -114,18 +117,18 @@ private class DeviceFSImpl(private val context: Context, private val withHidden:
|
|||||||
// For directories, recursively process them
|
// For directories, recursively process them
|
||||||
val childId = DocumentsContract.getDocumentId(childUri)
|
val childId = DocumentsContract.getDocumentId(childUri)
|
||||||
recursive.add(
|
recursive.add(
|
||||||
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred))
|
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
// For files, create DeviceFile objects and emit them
|
// For files, create DeviceFile objects and emit them
|
||||||
val file =
|
val file = DeviceFile(
|
||||||
DeviceFile(
|
uri = childUri,
|
||||||
uri = childUri,
|
mimeType = "", // We don't cache mime type but it's not used elsewhere
|
||||||
mimeType =
|
path = newPath,
|
||||||
"", // We don't cache mime type but it's not used elsewhere
|
size = 0, // We don't cache size but it's not used elsewhere
|
||||||
path = newPath,
|
modifiedMs = child.modifiedDate,
|
||||||
size = 0, // We don't cache size but it's not used elsewhere
|
parent = directoryDeferred
|
||||||
modifiedMs = child.modifiedDate,
|
)
|
||||||
parent = directoryDeferred)
|
|
||||||
children.add(file)
|
children.add(file)
|
||||||
emit(file)
|
emit(file)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,11 +23,12 @@ 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 android.util.Log
|
||||||
import java.io.File
|
import androidx.annotation.VisibleForTesting
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
private const val TAG = "DeviceFSCache"
|
private const val TAG = "DeviceFSCache"
|
||||||
private const val CACHE_FILE_NAME = "device_fs_cache.json"
|
private const val CACHE_FILE_NAME = "device_fs_cache.json"
|
||||||
@@ -36,9 +37,10 @@ private const val SCHEMA_VERSION = "1.0"
|
|||||||
/**
|
/**
|
||||||
* Caches directory structure information to minimize ContentResolver queries.
|
* Caches directory structure information to minimize ContentResolver queries.
|
||||||
*
|
*
|
||||||
* This cache is based on the concept that a directory's modification date changes when its direct
|
* This cache is based on the concept that a directory's modification date changes
|
||||||
* contents change (files added, removed, renamed). We can avoid expensive children queries by
|
* when its direct contents change (files added, removed, renamed). We can avoid
|
||||||
* caching directory contents and validating them against the directory's modification timestamp.
|
* expensive children queries by caching directory contents and validating them
|
||||||
|
* against the directory's modification timestamp.
|
||||||
*/
|
*/
|
||||||
internal class DeviceFSCache(private val context: Context) {
|
internal class DeviceFSCache(private val context: Context) {
|
||||||
|
|
||||||
@@ -57,22 +59,21 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
uri,
|
uri,
|
||||||
arrayOf(
|
arrayOf(
|
||||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED)) { cursor ->
|
DocumentsContract.Document.COLUMN_LAST_MODIFIED
|
||||||
if (cursor.moveToFirst()) {
|
)
|
||||||
val nameIndex =
|
) { cursor ->
|
||||||
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
if (cursor.moveToFirst()) {
|
||||||
val lastModifiedIndex =
|
val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
||||||
cursor.getColumnIndexOrThrow(
|
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
||||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
|
||||||
|
|
||||||
val name = cursor.getString(nameIndex)
|
val name = cursor.getString(nameIndex)
|
||||||
val lastModified = cursor.getLong(lastModifiedIndex)
|
val lastModified = cursor.getLong(lastModifiedIndex)
|
||||||
|
|
||||||
DirectoryInfo(name, lastModified)
|
DirectoryInfo(name, lastModified)
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -82,21 +83,21 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
* @return A list of DirectoryChildren or null if there was an error
|
* @return A list of DirectoryChildren or null if there was an error
|
||||||
*/
|
*/
|
||||||
fun getDirectoryChildren(uri: Uri): List<DirectoryChild>? {
|
fun getDirectoryChildren(uri: Uri): List<DirectoryChild>? {
|
||||||
val childrenUri =
|
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
|
||||||
DocumentsContract.buildChildDocumentsUriUsingTree(
|
uri,
|
||||||
uri, DocumentsContract.getDocumentId(uri))
|
DocumentsContract.getDocumentId(uri)
|
||||||
|
)
|
||||||
|
|
||||||
return contentResolver.useQuery(childrenUri, CHILDREN_PROJECTION) { cursor ->
|
return contentResolver.useQuery(
|
||||||
|
childrenUri,
|
||||||
|
CHILDREN_PROJECTION
|
||||||
|
) { cursor ->
|
||||||
val children = mutableListOf<DirectoryChild>()
|
val children = mutableListOf<DirectoryChild>()
|
||||||
|
|
||||||
val documentIdIndex =
|
val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
|
||||||
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
|
val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
||||||
val displayNameIndex =
|
val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
|
||||||
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
|
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
||||||
val mimeTypeIndex =
|
|
||||||
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
|
|
||||||
val lastModifiedIndex =
|
|
||||||
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
|
||||||
|
|
||||||
while (cursor.moveToNext()) {
|
while (cursor.moveToNext()) {
|
||||||
val childId = cursor.getString(documentIdIndex)
|
val childId = cursor.getString(documentIdIndex)
|
||||||
@@ -112,7 +113,9 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
uri = childUri.toString(),
|
uri = childUri.toString(),
|
||||||
name = displayName,
|
name = displayName,
|
||||||
type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE,
|
type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE,
|
||||||
modifiedDate = lastModified))
|
modifiedDate = lastModified
|
||||||
|
)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
children
|
children
|
||||||
@@ -120,8 +123,8 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the cached data against directory's current state. If directory's modification time
|
* Validates the cached data against directory's current state.
|
||||||
* has changed, cache is updated.
|
* If directory's modification time has changed, cache is updated.
|
||||||
*
|
*
|
||||||
* @param uri The URI of the directory to validate
|
* @param uri The URI of the directory to validate
|
||||||
* @return Whether the cache was hit (true) or needed updating (false)
|
* @return Whether the cache was hit (true) or needed updating (false)
|
||||||
@@ -130,13 +133,11 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
val uriString = uri.toString()
|
val uriString = uri.toString()
|
||||||
processedUris.add(uriString)
|
processedUris.add(uriString)
|
||||||
|
|
||||||
val dirInfo =
|
val dirInfo = getDirectoryInfo(uri) ?: run {
|
||||||
getDirectoryInfo(uri)
|
// Directory no longer exists or accessible, remove from cache
|
||||||
?: run {
|
cache.remove(uriString)
|
||||||
// Directory no longer exists or accessible, remove from cache
|
return false
|
||||||
cache.remove(uriString)
|
}
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if we have cache entry and whether it's still valid
|
// Check if we have cache entry and whether it's still valid
|
||||||
val cachedDir = cache[uriString]
|
val cachedDir = cache[uriString]
|
||||||
@@ -147,14 +148,17 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
|
|
||||||
// Cache miss or stale data - need to update
|
// Cache miss or stale data - need to update
|
||||||
val children = getDirectoryChildren(uri) ?: emptyList()
|
val children = getDirectoryChildren(uri) ?: emptyList()
|
||||||
cache[uriString] = CachedDirectory(modifiedDate = dirInfo.lastModified, children = children)
|
cache[uriString] = CachedDirectory(
|
||||||
|
modifiedDate = dirInfo.lastModified,
|
||||||
|
children = children
|
||||||
|
)
|
||||||
|
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets cached directory children without validation. Use validateDirectoryCache() first to
|
* Gets cached directory children without validation.
|
||||||
* ensure cached data is valid.
|
* Use validateDirectoryCache() first to ensure cached data is valid.
|
||||||
*
|
*
|
||||||
* @param uri The URI of the directory
|
* @param uri The URI of the directory
|
||||||
* @return The cached children or null if not cached
|
* @return The cached children or null if not cached
|
||||||
@@ -163,71 +167,90 @@ internal class DeviceFSCache(private val context: Context) {
|
|||||||
return cache[uri.toString()]?.children
|
return cache[uri.toString()]?.children
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cleans up the cache by removing entries that weren't accessed in the current traversal. */
|
/**
|
||||||
|
* Cleans up the cache by removing entries that weren't accessed
|
||||||
|
* in the current traversal.
|
||||||
|
*/
|
||||||
fun cleanupCache() {
|
fun cleanupCache() {
|
||||||
val toRemove = cache.keys.filter { it !in processedUris }
|
val toRemove = cache.keys.filter { it !in processedUris }
|
||||||
toRemove.forEach { cache.remove(it) }
|
toRemove.forEach { cache.remove(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Resets the processed URIs tracking set for a new full traversal. */
|
/**
|
||||||
|
* Resets the processed URIs tracking set for a new full traversal.
|
||||||
|
*/
|
||||||
fun resetTraversalTracking() {
|
fun resetTraversalTracking() {
|
||||||
processedUris.clear()
|
processedUris.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Saves the cache to disk. */
|
/**
|
||||||
suspend fun saveCache() =
|
* Saves the cache to disk.
|
||||||
withContext(Dispatchers.IO) {
|
*/
|
||||||
try {
|
suspend fun saveCache() = withContext(Dispatchers.IO) {
|
||||||
val cacheFile = File(context.cacheDir, CACHE_FILE_NAME)
|
try {
|
||||||
val cacheData = CacheData(schemaVersion = SCHEMA_VERSION, entries = cache)
|
val cacheFile = File(context.cacheDir, CACHE_FILE_NAME)
|
||||||
cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData))
|
val cacheData = CacheData(
|
||||||
} catch (e: Exception) {
|
schemaVersion = SCHEMA_VERSION,
|
||||||
Log.e(TAG, "Failed to save cache", e)
|
entries = cache
|
||||||
}
|
)
|
||||||
|
cacheFile.writeText(Json.encodeToString(CacheData.serializer(), cacheData))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Failed to save cache", e)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Loads the cache from disk. */
|
/**
|
||||||
suspend fun loadCache() =
|
* Loads the cache from disk.
|
||||||
withContext(Dispatchers.IO) {
|
*/
|
||||||
try {
|
suspend fun loadCache() = withContext(Dispatchers.IO) {
|
||||||
val cacheFile = File(context.cacheDir, CACHE_FILE_NAME)
|
try {
|
||||||
if (cacheFile.exists()) {
|
val cacheFile = File(context.cacheDir, CACHE_FILE_NAME)
|
||||||
val cacheDataString = cacheFile.readText()
|
if (cacheFile.exists()) {
|
||||||
val cacheData = Json.decodeFromString<CacheData>(cacheDataString)
|
val cacheDataString = cacheFile.readText()
|
||||||
|
val cacheData = Json.decodeFromString<CacheData>(cacheDataString)
|
||||||
|
|
||||||
// Only load if schema version matches
|
// Only load if schema version matches
|
||||||
if (cacheData.schemaVersion == SCHEMA_VERSION) {
|
if (cacheData.schemaVersion == SCHEMA_VERSION) {
|
||||||
cache.clear()
|
cache.clear()
|
||||||
cache.putAll(cacheData.entries)
|
cache.putAll(cacheData.entries)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
|
||||||
Log.e(TAG, "Failed to load cache", e)
|
|
||||||
// Start with empty cache if loading fails
|
|
||||||
cache.clear()
|
|
||||||
}
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e(TAG, "Failed to load cache", e)
|
||||||
|
// Start with empty cache if loading fails
|
||||||
|
cache.clear()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val CHILDREN_PROJECTION =
|
val CHILDREN_PROJECTION = arrayOf(
|
||||||
arrayOf(
|
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
||||||
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
|
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
||||||
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
|
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
||||||
DocumentsContract.Document.COLUMN_MIME_TYPE,
|
DocumentsContract.Document.COLUMN_LAST_MODIFIED
|
||||||
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Information about a directory. */
|
/**
|
||||||
data class DirectoryInfo(val name: String, val lastModified: Long)
|
* Information about a directory.
|
||||||
|
*/
|
||||||
|
data class DirectoryInfo(
|
||||||
|
val name: String,
|
||||||
|
val lastModified: Long
|
||||||
|
)
|
||||||
|
|
||||||
/** Type of a directory entry. */
|
/**
|
||||||
|
* Type of a directory entry.
|
||||||
|
*/
|
||||||
enum class EntryType {
|
enum class EntryType {
|
||||||
FILE,
|
FILE,
|
||||||
DIRECTORY
|
DIRECTORY
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Child entry in a directory. */
|
/**
|
||||||
|
* Child entry in a directory.
|
||||||
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class DirectoryChild(
|
data class DirectoryChild(
|
||||||
val uri: String,
|
val uri: String,
|
||||||
@@ -236,10 +259,20 @@ data class DirectoryChild(
|
|||||||
val modifiedDate: Long
|
val modifiedDate: Long
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Cached information about a directory. */
|
/**
|
||||||
|
* Cached information about a directory.
|
||||||
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class CachedDirectory(val modifiedDate: Long, val children: List<DirectoryChild>)
|
data class CachedDirectory(
|
||||||
|
val modifiedDate: Long,
|
||||||
|
val children: List<DirectoryChild>
|
||||||
|
)
|
||||||
|
|
||||||
/** Structure for serializing/deserializing the entire cache. */
|
/**
|
||||||
|
* Structure for serializing/deserializing the entire cache.
|
||||||
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class CacheData(val schemaVersion: String, val entries: Map<String, CachedDirectory>)
|
data class CacheData(
|
||||||
|
val schemaVersion: String,
|
||||||
|
val entries: Map<String, CachedDirectory>
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user