Revert "all: reformat"

This reverts commit 920dda0fe0.
This commit is contained in:
Alexander Capehart
2025-05-10 21:57:05 -06:00
parent 154bfb3c97
commit dbc46e7567
2 changed files with 182 additions and 146 deletions
@@ -18,6 +18,7 @@
package org.oxycblt.musikr.fs.device
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
@@ -34,6 +35,7 @@ import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import org.oxycblt.musikr.fs.MusicLocation
import org.oxycblt.musikr.fs.Path
@@ -49,8 +51,10 @@ internal interface DeviceFS {
}
@OptIn(ExperimentalCoroutinesApi::class)
private class DeviceFSImpl(private val context: Context, private val withHidden: Boolean) :
DeviceFS {
private class DeviceFSImpl(
private val context: Context,
private val withHidden: Boolean
) : DeviceFS {
private val contentResolver = context.contentResolverSafe
private val cache = DeviceFSCache(context)
@@ -62,17 +66,16 @@ private class DeviceFSImpl(private val context: Context, private val withHidden:
cache.resetTraversalTracking()
emitAll(
locations
.flatMapMerge { location ->
locations.flatMapMerge { location ->
exploreDirectoryImpl(
location.uri,
DocumentsContract.getTreeDocumentId(location.uri),
location.path,
null)
}
.flowOn(Dispatchers.IO))
}
.onCompletion {
null
)
}.flowOn(Dispatchers.IO)
)
}.onCompletion {
// Cleanup and save cache when exploration is complete
cache.cleanupCache()
cache.saveCache()
@@ -114,18 +117,18 @@ private class DeviceFSImpl(private val context: Context, private val withHidden:
// For directories, recursively process them
val childId = DocumentsContract.getDocumentId(childUri)
recursive.add(
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred))
exploreDirectoryImpl(rootUri, childId, newPath, directoryDeferred)
)
} else {
// For files, create DeviceFile objects and emit them
val file =
DeviceFile(
val file = DeviceFile(
uri = childUri,
mimeType =
"", // We don't cache mime type but it's not used elsewhere
mimeType = "", // We don't cache mime type but it's not used elsewhere
path = newPath,
size = 0, // We don't cache size but it's not used elsewhere
modifiedMs = child.modifiedDate,
parent = directoryDeferred)
parent = directoryDeferred
)
children.add(file)
emit(file)
}
@@ -23,11 +23,12 @@ import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Log
import java.io.File
import androidx.annotation.VisibleForTesting
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.io.File
private const val TAG = "DeviceFSCache"
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.
*
* This cache is based on the concept that a directory's modification date changes when its direct
* contents change (files added, removed, renamed). We can avoid expensive children queries by
* caching directory contents and validating them against the directory's modification timestamp.
* This cache is based on the concept that a directory's modification date changes
* when its direct contents change (files added, removed, renamed). We can avoid
* expensive children queries by caching directory contents and validating them
* against the directory's modification timestamp.
*/
internal class DeviceFSCache(private val context: Context) {
@@ -57,13 +59,12 @@ internal class DeviceFSCache(private val context: Context) {
uri,
arrayOf(
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_LAST_MODIFIED)) { cursor ->
DocumentsContract.Document.COLUMN_LAST_MODIFIED
)
) { cursor ->
if (cursor.moveToFirst()) {
val nameIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val nameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val name = cursor.getString(nameIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
@@ -82,21 +83,21 @@ internal class DeviceFSCache(private val context: Context) {
* @return A list of DirectoryChildren or null if there was an error
*/
fun getDirectoryChildren(uri: Uri): List<DirectoryChild>? {
val childrenUri =
DocumentsContract.buildChildDocumentsUriUsingTree(
uri, DocumentsContract.getDocumentId(uri))
val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(
uri,
DocumentsContract.getDocumentId(uri)
)
return contentResolver.useQuery(childrenUri, CHILDREN_PROJECTION) { cursor ->
return contentResolver.useQuery(
childrenUri,
CHILDREN_PROJECTION
) { cursor ->
val children = mutableListOf<DirectoryChild>()
val documentIdIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val documentIdIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DOCUMENT_ID)
val displayNameIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_DISPLAY_NAME)
val mimeTypeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_MIME_TYPE)
val lastModifiedIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
while (cursor.moveToNext()) {
val childId = cursor.getString(documentIdIndex)
@@ -112,7 +113,9 @@ internal class DeviceFSCache(private val context: Context) {
uri = childUri.toString(),
name = displayName,
type = if (isDirectory) EntryType.DIRECTORY else EntryType.FILE,
modifiedDate = lastModified))
modifiedDate = lastModified
)
)
}
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
* has changed, cache is updated.
* Validates the cached data against directory's current state.
* If directory's modification time has changed, cache is updated.
*
* @param uri The URI of the directory to validate
* @return Whether the cache was hit (true) or needed updating (false)
@@ -130,9 +133,7 @@ internal class DeviceFSCache(private val context: Context) {
val uriString = uri.toString()
processedUris.add(uriString)
val dirInfo =
getDirectoryInfo(uri)
?: run {
val dirInfo = getDirectoryInfo(uri) ?: run {
// Directory no longer exists or accessible, remove from cache
cache.remove(uriString)
return false
@@ -147,14 +148,17 @@ internal class DeviceFSCache(private val context: Context) {
// Cache miss or stale data - need to update
val children = getDirectoryChildren(uri) ?: emptyList()
cache[uriString] = CachedDirectory(modifiedDate = dirInfo.lastModified, children = children)
cache[uriString] = CachedDirectory(
modifiedDate = dirInfo.lastModified,
children = children
)
return false
}
/**
* Gets cached directory children without validation. Use validateDirectoryCache() first to
* ensure cached data is valid.
* Gets cached directory children without validation.
* Use validateDirectoryCache() first to ensure cached data is valid.
*
* @param uri The URI of the directory
* @return The cached children or null if not cached
@@ -163,32 +167,42 @@ internal class DeviceFSCache(private val context: Context) {
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() {
val toRemove = cache.keys.filter { it !in processedUris }
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() {
processedUris.clear()
}
/** Saves the cache to disk. */
suspend fun saveCache() =
withContext(Dispatchers.IO) {
/**
* Saves the cache to disk.
*/
suspend fun saveCache() = withContext(Dispatchers.IO) {
try {
val cacheFile = File(context.cacheDir, CACHE_FILE_NAME)
val cacheData = CacheData(schemaVersion = SCHEMA_VERSION, entries = cache)
val cacheData = CacheData(
schemaVersion = SCHEMA_VERSION,
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() =
withContext(Dispatchers.IO) {
/**
* Loads the cache from disk.
*/
suspend fun loadCache() = withContext(Dispatchers.IO) {
try {
val cacheFile = File(context.cacheDir, CACHE_FILE_NAME)
if (cacheFile.exists()) {
@@ -209,25 +223,34 @@ internal class DeviceFSCache(private val context: Context) {
}
companion object {
val CHILDREN_PROJECTION =
arrayOf(
val CHILDREN_PROJECTION = arrayOf(
DocumentsContract.Document.COLUMN_DOCUMENT_ID,
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
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 {
FILE,
DIRECTORY
}
/** Child entry in a directory. */
/**
* Child entry in a directory.
*/
@Serializable
data class DirectoryChild(
val uri: String,
@@ -236,10 +259,20 @@ data class DirectoryChild(
val modifiedDate: Long
)
/** Cached information about a directory. */
/**
* Cached information about a directory.
*/
@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
data class CacheData(val schemaVersion: String, val entries: Map<String, CachedDirectory>)
data class CacheData(
val schemaVersion: String,
val entries: Map<String, CachedDirectory>
)