all: reformat

This commit is contained in:
Alexander Capehart
2025-05-15 17:00:36 -06:00
parent 22d43e5849
commit ec4d003af8
6 changed files with 195 additions and 203 deletions
@@ -128,9 +128,7 @@ private class MusikrImpl(
.explore(locations)
.buffer(Channel.UNLIMITED)
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
.onEach {
onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount))
}
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) }
val extracted =
extractStep
.extract(explored)
@@ -20,7 +20,6 @@ package org.oxycblt.musikr.cache.db
import android.content.Context
import android.net.Uri
import android.util.Log
import kotlinx.coroutines.sync.Mutex
import org.oxycblt.musikr.cache.Cache
import org.oxycblt.musikr.cache.CacheResult
@@ -15,7 +15,7 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.fs.device
import android.content.ContentResolver
@@ -26,7 +26,6 @@ import android.util.Log
import androidx.core.net.toUri
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
@@ -43,7 +42,6 @@ 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 {
fun explore(locations: Flow<MusicLocation>, fileTree: FileTree): Flow<DeviceDirectory>
@@ -59,38 +57,26 @@ private class DeviceFSImpl(
private val withHidden: Boolean
) : DeviceFS {
private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
override fun explore(locations: Flow<MusicLocation>, fileTree: FileTree) =
locations.mapNotNull { location ->
queryRoot(location, fileTree)
}
private suspend fun queryRoot(
location: MusicLocation,
fileTree: FileTree
): DeviceDirectory? {
val treeDocumentId =
DocumentsContract.getTreeDocumentId(location.uri)
override fun explore(locations: Flow<MusicLocation>, fileTree: FileTree) =
locations.mapNotNull { location -> 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)
}
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
)
return query(location.uri, treeDocumentId, location.path, modifiedMs, null, fileTree)
}
private suspend fun query(
@@ -105,105 +91,110 @@ private class DeviceFSImpl(
val cached = fileTree.queryDirectory(uri)
if (cached != null && cached.modifiedMs == modifiedMs) {
return@coroutineScope hydrateCached(
cached = cached,
parentDir = parent,
path = path,
fileTree = fileTree
)
cached = cached, parentDir = parent, path = path, fileTree = fileTree)
}
val dir = DeviceDirectoryImpl(
uri = uri,
path = path,
modifiedMs = modifiedMs,
parent = parent,
children = emptyFlow()
)
dir.children = flow {
Log.d("DeviceFS", "Querying $uri")
contentResolver.useQuery(
DocumentsContract.buildChildDocumentsUriUsingTree(
rootUri,
treeDocumentId,
), projection = PROJECTION, sortOrder = "${DocumentsContract.Document.COLUMN_DISPLAY_NAME} DESC"
) { cursor ->
val childUriIndex =
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 sizeIndex = cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val dir =
DeviceDirectoryImpl(
uri = uri,
path = path,
modifiedMs = modifiedMs,
parent = parent,
children = emptyFlow())
dir.children =
flow {
Log.d("DeviceFS", "Querying $uri")
contentResolver.useQuery(
DocumentsContract.buildChildDocumentsUriUsingTree(
rootUri,
treeDocumentId,
),
projection = PROJECTION,
sortOrder = "${DocumentsContract.Document.COLUMN_DISPLAY_NAME} DESC") {
cursor ->
val childUriIndex =
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 sizeIndex =
cursor.getColumnIndexOrThrow(DocumentsContract.Document.COLUMN_SIZE)
val lastModifiedIndex =
cursor.getColumnIndexOrThrow(
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
val childSubdirUris = mutableListOf<String>()
val childFileUris = mutableListOf<String>()
val childSubdirUris = mutableListOf<String>()
val childFileUris = mutableListOf<String>()
val subqueries = mutableListOf<DeviceDirectory>()
val subqueries = mutableListOf<DeviceDirectory>()
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
while (cursor.moveToNext()) {
val childId = cursor.getString(childUriIndex)
val displayName = cursor.getString(displayNameIndex)
// Skip hidden files/directories if ignoreHidden is true
if (!withHidden && displayName.startsWith(".")) {
continue
}
// Skip hidden files/directories if ignoreHidden is true
if (!withHidden && displayName.startsWith(".")) {
continue
}
val newPath = path.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
val newPath = path.file(displayName)
val mimeType = cursor.getString(mimeTypeIndex)
val lastModified = cursor.getLong(lastModifiedIndex)
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
val subdir =
query(
rootUri = rootUri,
treeDocumentId = childId,
path = newPath,
modifiedMs = modifiedMs,
parent = dir,
fileTree = fileTree
)
childSubdirUris.add(subdir.uri.toString())
emit(StreamedFile.More(subdir))
} else {
Log.d("DeviceFS", "Querying file $childId")
val size = cursor.getLong(sizeIndex)
val childUri = DocumentsContract.buildDocumentUriUsingTree(rootUri, childId)
val file =
DeviceFile(
uri = childUri,
mimeType = mimeType,
path = newPath,
size = size,
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))
}
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
val subdir =
query(
rootUri = rootUri,
treeDocumentId = childId,
path = newPath,
modifiedMs = modifiedMs,
parent = dir,
fileTree = fileTree)
childSubdirUris.add(subdir.uri.toString())
emit(StreamedFile.More(subdir))
} else {
Log.d("DeviceFS", "Querying file $childId")
val size = cursor.getLong(sizeIndex)
val childUri =
DocumentsContract.buildDocumentUriUsingTree(
rootUri, childId)
val file =
DeviceFile(
uri = childUri,
mimeType = mimeType,
path = newPath,
size = size,
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)
}
}
val writeDir = CachedDirectory(
uri = uri.toString(),
name = requireNotNull(path.name),
modifiedMs = modifiedMs,
subdirUris = childSubdirUris,
fileUris = childFileUris
)
fileTree.updateDirectory(uri, writeDir)
emit(StreamedFile.Done)
}
}.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
.takeWhile { it is StreamedFile.More }
.map { (it as StreamedFile.More).value }
.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
.takeWhile { it is StreamedFile.More }
.map { (it as StreamedFile.More).value }
dir
}
@@ -213,47 +204,52 @@ private class DeviceFSImpl(
path: Path,
fileTree: FileTree
): DeviceDirectory = coroutineScope {
val dir = DeviceDirectoryImpl(
uri = cached.uri.toUri(),
path = path,
modifiedMs = cached.modifiedMs,
parent = parentDir,
children = emptyFlow()
)
dir.children = flow {
emitAll(
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
)
}
).map { StreamedFile.More(it) }
)
emit(StreamedFile.Done)
}
.flowOn(Dispatchers.IO)
.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
.takeWhile { it is StreamedFile.More }
.map { (it as StreamedFile.More).value }
val dir =
DeviceDirectoryImpl(
uri = cached.uri.toUri(),
path = path,
modifiedMs = cached.modifiedMs,
parent = parentDir,
children = emptyFlow())
dir.children =
flow {
emitAll(
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)
})
.map { StreamedFile.More(it) })
emit(StreamedFile.Done)
}
.flowOn(Dispatchers.IO)
.shareIn(explorationScope, SharingStarted.Lazily, replay = Int.MAX_VALUE)
.takeWhile { it is StreamedFile.More }
.map { (it as StreamedFile.More).value }
dir
}
private sealed interface StreamedFile {
data class More(val value: DeviceFSEntry) : StreamedFile
data object Done : StreamedFile
}
@@ -264,8 +260,7 @@ private class DeviceFSImpl(
DocumentsContract.Document.COLUMN_DISPLAY_NAME,
DocumentsContract.Document.COLUMN_MIME_TYPE,
DocumentsContract.Document.COLUMN_SIZE,
DocumentsContract.Document.COLUMN_LAST_MODIFIED
)
DocumentsContract.Document.COLUMN_LAST_MODIFIED)
}
}
@@ -276,6 +271,3 @@ private class DeviceDirectoryImpl(
override val parent: DeviceDirectory?,
override var children: Flow<DeviceFSEntry>,
) : DeviceDirectory
@@ -19,14 +19,8 @@
package org.oxycblt.musikr.fs.device
import android.net.Uri
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flatMapMerge
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.transform
import org.oxycblt.musikr.fs.Path
@@ -50,9 +44,10 @@ data class DeviceFile(
val parent: DeviceDirectory
) : DeviceFSEntry
fun DeviceDirectory.flatten(): Flow<DeviceFile> = children.transform {
fun DeviceDirectory.flatten(): Flow<DeviceFile> =
children.transform {
when (it) {
is DeviceDirectory -> emitAll(it.flatten())
is DeviceFile -> emit(it)
}
}
}
@@ -15,19 +15,19 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.oxycblt.musikr.fs.device
import android.content.Context
import android.net.Uri
import android.util.Log
import java.io.File
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
import kotlinx.serialization.json.Json
interface FileTreeCache {
fun read(): FileTree
@@ -35,11 +35,13 @@ interface FileTreeCache {
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()
}
@@ -78,20 +80,23 @@ 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
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())
FileTreeImpl(
context,
fileTreeCache.directories.toMutableMap(),
fileTreeCache.files.toMutableMap())
} catch (e: Exception) {
Log.e(TAG, "Failed to read cache file", e)
FileTreeImpl(context, mutableMapOf(), mutableMapOf())
@@ -111,8 +116,8 @@ class FileTreeImpl(
companion object {
private const val TAG = "FileTree"
private const val CACHE_FILENAME = "file_tree_cache.json"
private val json = Json {
ignoreUnknownKeys = true
private val json = Json {
ignoreUnknownKeys = true
prettyPrint = true
}
}
@@ -142,22 +147,22 @@ class FileTreeImpl(
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)
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
}
Unit
}
}
@@ -48,7 +48,10 @@ internal fun ContentResolver.safeQuery(
selector: String? = null,
args: Array<String>? = null,
sortOrder: String? = null
) = requireNotNull(query(uri, projection, selector, args, sortOrder)) { "ContentResolver query failed" }
) =
requireNotNull(query(uri, projection, selector, args, sortOrder)) {
"ContentResolver query failed"
}
/**
* A shortcut for [safeQuery] with [use] applied, automatically cleaning up the [Cursor]'s resources