musikr: refactor musiclocation api into location
Improves the API surface pretty heavily. Assisted by Claude 4 Sonnet/Claude 3.5 Haiku.
This commit is contained in:
@@ -38,6 +38,7 @@ import org.oxycblt.musikr.Music
|
||||
import org.oxycblt.musikr.Musikr
|
||||
import org.oxycblt.musikr.MutableLibrary
|
||||
import org.oxycblt.musikr.Playlist
|
||||
import org.oxycblt.musikr.Query
|
||||
import org.oxycblt.musikr.Song
|
||||
import org.oxycblt.musikr.Storage
|
||||
import org.oxycblt.musikr.cache.MutableCache
|
||||
@@ -396,10 +397,11 @@ constructor(
|
||||
val fileTreeCache =
|
||||
if (withCache) FileTreeCache.from(context)
|
||||
else WriteOnlyFileTreeCache(FileTreeCache.from(context))
|
||||
val query = Query(source = locations, exclude = emptyList())
|
||||
val storage = Storage(cache, covers, storedPlaylists, fileTreeCache)
|
||||
val interpretation = Interpretation(nameFactory, separators, withHidden)
|
||||
val result =
|
||||
Musikr.new(context, storage, interpretation).run(locations, ::emitIndexingProgress)
|
||||
Musikr.new(context, storage, interpretation).run(query, ::emitIndexingProgress)
|
||||
// Music loading completed, update the revision right now so we re-use this work
|
||||
// later.
|
||||
musicSettings.revision = newRevision
|
||||
|
||||
@@ -20,12 +20,14 @@ package org.oxycblt.auxio.music
|
||||
|
||||
import android.content.Context
|
||||
import androidx.core.content.edit
|
||||
import androidx.core.net.toUri
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import java.util.UUID
|
||||
import javax.inject.Inject
|
||||
import org.oxycblt.auxio.R
|
||||
import org.oxycblt.auxio.settings.Settings
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.Location
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
@@ -37,7 +39,7 @@ interface MusicSettings : Settings<MusicSettings.Listener> {
|
||||
/** The current library revision. */
|
||||
var revision: UUID?
|
||||
/** The locations of music to load. */
|
||||
var musicLocations: List<MusicLocation>
|
||||
var musicLocations: List<OpenedLocation>
|
||||
/** Whether to exclude non-music audio files from the music library. */
|
||||
val excludeNonMusic: Boolean
|
||||
/** Whether to ignore hidden files and directories during music loading. */
|
||||
@@ -74,17 +76,17 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
|
||||
}
|
||||
}
|
||||
|
||||
override var musicLocations: List<MusicLocation>
|
||||
override var musicLocations: List<OpenedLocation>
|
||||
get() {
|
||||
val locations =
|
||||
sharedPreferences.getString(getString(R.string.set_key_music_locations), null)
|
||||
?: return emptyList()
|
||||
return MusicLocation.existing(context, locations)
|
||||
return locations.toOpenedLocations()
|
||||
}
|
||||
set(value) {
|
||||
sharedPreferences.edit {
|
||||
putString(
|
||||
getString(R.string.set_key_music_locations), MusicLocation.toString(value))
|
||||
getString(R.string.set_key_music_locations), value.stringify())
|
||||
commit()
|
||||
// Sometimes changing this setting just won't actually trigger the listener.
|
||||
// Only this one. No idea why.
|
||||
@@ -136,4 +138,49 @@ class MusicSettingsImpl @Inject constructor(@ApplicationContext private val cont
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun List<OpenedLocation>.stringify(): String =
|
||||
joinToString(separator = ";") { it.uri.toString().replace(";", "\\;") }
|
||||
|
||||
private fun String.toOpenedLocations(): List<OpenedLocation> =
|
||||
splitEscaped { it == ';' }.mapNotNull { Location.from(context, it.toUri())?.open(context) }
|
||||
|
||||
private inline fun String.splitEscaped(selector: (Char) -> Boolean): List<String> {
|
||||
val split = mutableListOf<String>()
|
||||
var currentString = ""
|
||||
var i = 0
|
||||
|
||||
while (i < length) {
|
||||
val a = get(i)
|
||||
val b = getOrNull(i + 1)
|
||||
|
||||
if (selector(a)) {
|
||||
// Non-escaped separator, split the string here, making sure any stray whitespace
|
||||
// is removed.
|
||||
split.add(currentString)
|
||||
currentString = ""
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
if (b != null && a == '\\' && selector(b)) {
|
||||
// Is an escaped character, add the non-escaped variant and skip two
|
||||
// characters to move on to the next one.
|
||||
currentString += b
|
||||
i += 2
|
||||
} else {
|
||||
// Non-escaped, increment normally.
|
||||
currentString += a
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
if (currentString.isNotEmpty()) {
|
||||
// Had an in-progress split string that is now terminated, add it.
|
||||
split.add(currentString)
|
||||
}
|
||||
|
||||
return split
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,21 +25,22 @@ import org.oxycblt.auxio.databinding.ItemMusicLocationBinding
|
||||
import org.oxycblt.auxio.list.recycler.DialogRecyclerView
|
||||
import org.oxycblt.auxio.util.context
|
||||
import org.oxycblt.auxio.util.inflater
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.Location
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
* [RecyclerView.Adapter] that manages a list of [MusicLocation] music directory instances.
|
||||
* [RecyclerView.Adapter] that manages a list of [OpenedLocation] music directory instances.
|
||||
*
|
||||
* @param listener A [LocationAdapter.Listener] to bind interactions to.
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter<MusicDirViewHolder>() {
|
||||
private val _locations = mutableListOf<MusicLocation>()
|
||||
private val _locations = mutableListOf<OpenedLocation>()
|
||||
/**
|
||||
* The current list of [MusicLocation]s, may not line up with [MusicLocation]s due to removals.
|
||||
* The current list of [OpenedLocation]s, may not line up with [OpenedLocation]s due to removals.
|
||||
*/
|
||||
val locations: List<MusicLocation> = _locations
|
||||
val locations: List<OpenedLocation> = _locations
|
||||
|
||||
override fun getItemCount() = locations.size
|
||||
|
||||
@@ -50,11 +51,11 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter<Mus
|
||||
holder.bind(locations[position], listener)
|
||||
|
||||
/**
|
||||
* Add a [MusicLocation] to the end of the list.
|
||||
* Add a [OpenedLocation] to the end of the list.
|
||||
*
|
||||
* @param location The [MusicLocation] to add.
|
||||
* @param location The [OpenedLocation] to add.
|
||||
*/
|
||||
fun add(location: MusicLocation) {
|
||||
fun add(location: OpenedLocation) {
|
||||
if (_locations.contains(location)) return
|
||||
L.d("Adding $location")
|
||||
_locations.add(location)
|
||||
@@ -62,11 +63,11 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter<Mus
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a list of [MusicLocation] instances to the end of the list.
|
||||
* Add a list of [OpenedLocation] instances to the end of the list.
|
||||
*
|
||||
* @param locations The [MusicLocation] instances to add.
|
||||
* @param locations The [OpenedLocation] instances to add.
|
||||
*/
|
||||
fun addAll(locations: List<MusicLocation>) {
|
||||
fun addAll(locations: List<OpenedLocation>) {
|
||||
L.d("Adding ${locations.size} locations")
|
||||
val oldLastIndex = locations.lastIndex
|
||||
_locations.addAll(locations)
|
||||
@@ -74,11 +75,11 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter<Mus
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a [MusicLocation] from the list.
|
||||
* Remove a [OpenedLocation] from the list.
|
||||
*
|
||||
* @param location The [MusicLocation] to remove. Must exist in the list.
|
||||
* @param location The [OpenedLocation] to remove. Must exist in the list.
|
||||
*/
|
||||
fun remove(location: MusicLocation) {
|
||||
fun remove(location: OpenedLocation) {
|
||||
L.d("Removing $location")
|
||||
val idx = _locations.indexOf(location)
|
||||
_locations.removeAt(idx)
|
||||
@@ -88,12 +89,12 @@ class LocationAdapter(private val listener: Listener) : RecyclerView.Adapter<Mus
|
||||
/** A Listener for [LocationAdapter] interactions. */
|
||||
interface Listener {
|
||||
/** Called when the delete button on a directory item is clicked. */
|
||||
fun onRemoveLocation(location: MusicLocation)
|
||||
fun onRemoveLocation(location: OpenedLocation)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A [RecyclerView.Recycler] that displays a [MusicLocation]. Use [from] to create an instance.
|
||||
* A [RecyclerView.Recycler] that displays a [OpenedLocation]. Use [from] to create an instance.
|
||||
*
|
||||
* @author Alexander Capehart (OxygenCobalt)
|
||||
*/
|
||||
@@ -102,10 +103,10 @@ class MusicDirViewHolder private constructor(private val binding: ItemMusicLocat
|
||||
/**
|
||||
* Bind new data to this instance.
|
||||
*
|
||||
* @param location The new [MusicLocation] to bind.
|
||||
* @param location The new [OpenedLocation] to bind.
|
||||
* @param listener A [LocationAdapter.Listener] to bind interactions to.
|
||||
*/
|
||||
fun bind(location: MusicLocation, listener: LocationAdapter.Listener) {
|
||||
fun bind(location: OpenedLocation, listener: LocationAdapter.Listener) {
|
||||
binding.locationPath.text = location.path.resolve(binding.context)
|
||||
binding.locationDelete.setOnClickListener { listener.onRemoveLocation(location) }
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ import org.oxycblt.auxio.databinding.DialogMusicLocationsBinding
|
||||
import org.oxycblt.auxio.music.MusicSettings
|
||||
import org.oxycblt.auxio.ui.ViewBindingMaterialDialogFragment
|
||||
import org.oxycblt.auxio.util.showToast
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.Location
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import timber.log.Timber as L
|
||||
|
||||
/**
|
||||
@@ -81,7 +82,8 @@ class MusicSourcesDialog :
|
||||
|
||||
val locations =
|
||||
savedInstanceState?.getStringArrayList(KEY_PENDING_LOCATIONS)?.mapNotNull {
|
||||
MusicLocation.existing(requireContext(), it.toUri())
|
||||
val context = requireContext()
|
||||
Location.from(context, it.toUri())?.open(context)
|
||||
} ?: musicSettings.musicLocations
|
||||
|
||||
locationAdapter.addAll(locations)
|
||||
@@ -99,7 +101,7 @@ class MusicSourcesDialog :
|
||||
binding.locationsRecycler.adapter = null
|
||||
}
|
||||
|
||||
override fun onRemoveLocation(location: MusicLocation) {
|
||||
override fun onRemoveLocation(location: OpenedLocation) {
|
||||
locationAdapter.remove(location)
|
||||
}
|
||||
|
||||
@@ -117,7 +119,7 @@ class MusicSourcesDialog :
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a Document Tree [Uri] chosen by the user to the current [MusicLocation]s.
|
||||
* Add a Document Tree [Uri] chosen by the user to the current [OpenedLocation]s.
|
||||
*
|
||||
* @param uri The document tree [Uri] to add, chosen by the user. Will do nothing if the [Uri]
|
||||
* is null or not valid.
|
||||
@@ -128,7 +130,8 @@ class MusicSourcesDialog :
|
||||
L.d("No URI given (user closed the dialog)")
|
||||
return
|
||||
}
|
||||
val location = MusicLocation.new(requireContext(), uri)
|
||||
val context = requireContext()
|
||||
val location = Location.from(context, uri)?.open(context)
|
||||
|
||||
if (location != null) {
|
||||
locationAdapter.add(location)
|
||||
|
||||
@@ -36,7 +36,7 @@ import org.oxycblt.auxio.music.shim.UpdateTrackerFactory
|
||||
import org.oxycblt.auxio.playback.state.PlaybackStateManager
|
||||
import org.oxycblt.auxio.util.getSystemServiceCompat
|
||||
import org.oxycblt.musikr.MusicParent
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import org.oxycblt.musikr.track.UpdateTracker
|
||||
import timber.log.Timber as L
|
||||
|
||||
@@ -168,7 +168,7 @@ private constructor(
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUpdate(location: MusicLocation) {
|
||||
override fun onUpdate(location: OpenedLocation) {
|
||||
if (musicSettings.shouldBeObserving) {
|
||||
musicRepository.requestIndex(true)
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ graph LR
|
||||
## Module Structure
|
||||
|
||||
### 1. File System (`fs` package)
|
||||
- **MusicLocation** - Represents a location to search for music
|
||||
- **OpenedLocation** - Represents a location to search for music
|
||||
- **DeviceFS** - Provides access to device storage
|
||||
- **FileTreeCache** - Caches filesystem structure for faster indexing
|
||||
|
||||
|
||||
@@ -21,11 +21,19 @@ package org.oxycblt.musikr
|
||||
import org.oxycblt.musikr.cache.MutableCache
|
||||
import org.oxycblt.musikr.covers.Cover
|
||||
import org.oxycblt.musikr.covers.MutableCovers
|
||||
import org.oxycblt.musikr.fs.Location
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
import org.oxycblt.musikr.fs.device.FileTreeCache
|
||||
import org.oxycblt.musikr.playlist.db.StoredPlaylists
|
||||
import org.oxycblt.musikr.tag.interpret.Naming
|
||||
import org.oxycblt.musikr.tag.interpret.Separators
|
||||
|
||||
data class Query(
|
||||
val source: List<OpenedLocation>,
|
||||
val exclude: List<Location>
|
||||
)
|
||||
|
||||
/** Side-effect laden [Storage] for use during music loading and [MutableLibrary] operation. */
|
||||
data class Storage(
|
||||
/**
|
||||
|
||||
@@ -26,7 +26,6 @@ import kotlinx.coroutines.flow.buffer
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import kotlinx.coroutines.flow.onStart
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.pipeline.EvaluateStep
|
||||
import org.oxycblt.musikr.pipeline.ExploreStep
|
||||
import org.oxycblt.musikr.pipeline.ExtractStep
|
||||
@@ -48,13 +47,13 @@ interface Musikr {
|
||||
/**
|
||||
* Start loading music from the given [locations] and the configuration provided earlier.
|
||||
*
|
||||
* @param locations The [MusicLocation]s to search for music in.
|
||||
* @param query The [Query] to load music from.
|
||||
* @param onProgress Optional callback to receive progress on the current status of the music
|
||||
* pipeline. Warning: These events will be rapid-fire.
|
||||
* @return A handle to the newly created library alongside further cleanup.
|
||||
*/
|
||||
suspend fun run(
|
||||
locations: List<MusicLocation>,
|
||||
query: Query,
|
||||
onProgress: suspend (IndexingProgress) -> Unit = {}
|
||||
): LibraryResult
|
||||
|
||||
@@ -71,6 +70,7 @@ interface Musikr {
|
||||
*/
|
||||
fun new(context: Context, storage: Storage, interpretation: Interpretation): Musikr =
|
||||
MusikrImpl(
|
||||
context,
|
||||
storage,
|
||||
ExploreStep.from(context, storage, interpretation),
|
||||
ExtractStep.from(context, storage),
|
||||
@@ -97,7 +97,7 @@ sealed interface IndexingProgress {
|
||||
/**
|
||||
* Currently indexing and extracting tags from device music.
|
||||
*
|
||||
* @param explored The amount of music currently found from the given [MusicLocation]s.
|
||||
* @param explored The amount of music currently found from the given [Query].
|
||||
* @param loaded The amount of music that has had metadata extracted and parsed.
|
||||
*/
|
||||
data class Songs(val loaded: Int, val explored: Int) : IndexingProgress
|
||||
@@ -111,13 +111,14 @@ sealed interface IndexingProgress {
|
||||
}
|
||||
|
||||
private class MusikrImpl(
|
||||
private val context: Context,
|
||||
private val storage: Storage,
|
||||
private val exploreStep: ExploreStep,
|
||||
private val extractStep: ExtractStep,
|
||||
private val evaluateStep: EvaluateStep
|
||||
) : Musikr {
|
||||
override suspend fun run(
|
||||
locations: List<MusicLocation>,
|
||||
query: Query,
|
||||
onProgress: suspend (IndexingProgress) -> Unit
|
||||
) = coroutineScope {
|
||||
val start = System.currentTimeMillis()
|
||||
@@ -125,7 +126,7 @@ private class MusikrImpl(
|
||||
var extractedCount = 0
|
||||
val explored =
|
||||
exploreStep
|
||||
.explore(locations)
|
||||
.explore(query)
|
||||
.buffer(Channel.UNLIMITED)
|
||||
.onStart { onProgress(IndexingProgress.Songs(0, 0)) }
|
||||
.onEach { onProgress(IndexingProgress.Songs(extractedCount, ++exploredCount)) }
|
||||
|
||||
+33
-31
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* Copyright (c) 2024 Auxio Project
|
||||
* MusicLocation.kt is part of Auxio.
|
||||
* Location.kt is part of Auxio.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@@ -24,49 +24,51 @@ import android.net.Uri
|
||||
import android.provider.DocumentsContract
|
||||
import org.oxycblt.musikr.fs.device.contentResolverSafe
|
||||
import org.oxycblt.musikr.fs.path.DocumentPathFactory
|
||||
import org.oxycblt.musikr.util.splitEscaped
|
||||
|
||||
class MusicLocation private constructor(val uri: Uri, val path: Path) {
|
||||
override fun equals(other: Any?) = other is MusicLocation && uri == other.uri
|
||||
class Location private constructor(val uri: Uri, val path: Path) {
|
||||
override fun equals(other: Any?) = other is Location && uri == other.uri
|
||||
|
||||
override fun hashCode() = 31 * uri.hashCode()
|
||||
|
||||
override fun toString(): String = uri.toString()
|
||||
|
||||
companion object {
|
||||
fun new(context: Context, uri: Uri): MusicLocation? {
|
||||
if (!DocumentsContract.isTreeUri(uri)) return null
|
||||
val documentPathFactory = DocumentPathFactory.from(context)
|
||||
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
|
||||
val notPersisted =
|
||||
context.contentResolverSafe.persistedUriPermissions.none {
|
||||
it.uri == uri && it.isReadPermission && it.isWritePermission
|
||||
}
|
||||
if (notPersisted) {
|
||||
fun open(context: Context): OpenedLocation? {
|
||||
if (isUnopened(context, uri)) {
|
||||
try {
|
||||
context.contentResolverSafe.takePersistableUriPermission(
|
||||
uri,
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
|
||||
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
// Not fully sure what happens if I'm disallowed to take the permission,
|
||||
// check for both circumstances (error or no-op)
|
||||
return null
|
||||
}
|
||||
return MusicLocation(uri, path)
|
||||
|
||||
if (isUnopened(context, uri)) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return OpenedLocation(uri, path)
|
||||
}
|
||||
|
||||
private fun isUnopened(context: Context, uri: Uri) =
|
||||
context.contentResolverSafe.persistedUriPermissions.none {
|
||||
it.uri == uri && it.isReadPermission && it.isWritePermission
|
||||
}
|
||||
|
||||
fun existing(context: Context, uri: Uri): MusicLocation? {
|
||||
val documentPathFactory = DocumentPathFactory.from(context)
|
||||
companion object {
|
||||
fun from(context: Context, uri: Uri): Location? {
|
||||
if (!DocumentsContract.isTreeUri(uri)) return null
|
||||
val notPersisted =
|
||||
context.contentResolverSafe.persistedUriPermissions.none {
|
||||
it.uri == uri && it.isReadPermission && it.isWritePermission
|
||||
}
|
||||
if (notPersisted) return null
|
||||
val documentPathFactory = DocumentPathFactory.from(context)
|
||||
val path = documentPathFactory.unpackDocumentTreeUri(uri) ?: return null
|
||||
return MusicLocation(uri, path)
|
||||
}
|
||||
|
||||
fun toString(list: List<MusicLocation>) =
|
||||
list.joinToString(";") { it.uri.toString().replace(";", "\\;") }
|
||||
|
||||
fun existing(context: Context, string: String): List<MusicLocation> {
|
||||
return string.splitEscaped { it == ';' }.mapNotNull { existing(context, Uri.parse(it)) }
|
||||
return Location(uri, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class OpenedLocation internal constructor(val uri: Uri, val path: Path) {
|
||||
override fun equals(other: Any?) = other is OpenedLocation && uri == other.uri && path == other.path
|
||||
override fun hashCode() = 31 * uri.hashCode() + path.hashCode()
|
||||
override fun toString(): String = uri.toString()
|
||||
}
|
||||
@@ -8,7 +8,7 @@ The filesystem package provides abstraction layers for accessing music files on
|
||||
|
||||
### Core Types
|
||||
|
||||
**MusicLocation** (`MusicLocation.kt`)
|
||||
**OpenedLocation** (`OpenedLocation.kt`)
|
||||
- Represents a location to search for music
|
||||
- Can be a device storage location or content URI
|
||||
|
||||
@@ -50,7 +50,7 @@ The filesystem package provides abstraction layers for accessing music files on
|
||||
|
||||
## Usage Flow
|
||||
|
||||
1. User provides `MusicLocation`s to scan
|
||||
1. User provides `OpenedLocation`s to scan
|
||||
2. `DeviceFS` traverses these locations
|
||||
3. `FileTreeCache` optimizes subsequent scans
|
||||
4. Discovered files are passed to the pipeline for processing
|
||||
|
||||
@@ -33,6 +33,7 @@ import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.asFlow
|
||||
import kotlinx.coroutines.flow.emitAll
|
||||
import kotlinx.coroutines.flow.emptyFlow
|
||||
import kotlinx.coroutines.flow.filterNotNull
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -40,15 +41,20 @@ 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 kotlinx.coroutines.flow.transform
|
||||
import org.oxycblt.musikr.Query
|
||||
import org.oxycblt.musikr.fs.Location
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import org.oxycblt.musikr.fs.Path
|
||||
|
||||
internal interface DeviceFS {
|
||||
fun explore(locations: Flow<MusicLocation>, fileTree: FileTree): Flow<DeviceDirectory>
|
||||
fun explore(query: Query, fileTree: FileTree): Flow<DeviceDirectory>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context, withHidden: Boolean): DeviceFS =
|
||||
DeviceFSImpl(context.contentResolverSafe, withHidden)
|
||||
fun from(
|
||||
context: Context,
|
||||
withHidden: Boolean
|
||||
): DeviceFS = DeviceFSImpl(context.contentResolverSafe, withHidden)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,10 +64,10 @@ private class DeviceFSImpl(
|
||||
) : DeviceFS {
|
||||
private val explorationScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
|
||||
override fun explore(locations: Flow<MusicLocation>, fileTree: FileTree) =
|
||||
locations.mapNotNull { location -> queryRoot(location, fileTree) }
|
||||
override fun explore(query: Query, fileTree: FileTree) =
|
||||
query.source.asFlow().mapNotNull { location -> queryRoot(location, fileTree, query.exclude) }
|
||||
|
||||
private suspend fun queryRoot(location: MusicLocation, fileTree: FileTree): DeviceDirectory? {
|
||||
private suspend fun queryRoot(location: OpenedLocation, fileTree: FileTree, exclude: List<Location>): DeviceDirectory? {
|
||||
val treeDocumentId = DocumentsContract.getTreeDocumentId(location.uri)
|
||||
val uri = DocumentsContract.buildDocumentUriUsingTree(location.uri, treeDocumentId)
|
||||
val modifiedMs =
|
||||
@@ -76,7 +82,7 @@ private class DeviceFSImpl(
|
||||
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, exclude)
|
||||
}
|
||||
|
||||
private suspend fun query(
|
||||
@@ -85,13 +91,14 @@ private class DeviceFSImpl(
|
||||
path: Path,
|
||||
modifiedMs: Long,
|
||||
parent: DeviceDirectory?,
|
||||
fileTree: FileTree
|
||||
fileTree: FileTree,
|
||||
exclude: List<Location>
|
||||
): 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)
|
||||
cached = cached, parentDir = parent, path = path, fileTree = fileTree, exclude)
|
||||
}
|
||||
val dir =
|
||||
DeviceDirectoryImpl(
|
||||
@@ -145,6 +152,19 @@ private class DeviceFSImpl(
|
||||
val lastModified = cursor.getLong(lastModifiedIndex)
|
||||
|
||||
if (mimeType == DocumentsContract.Document.MIME_TYPE_DIR) {
|
||||
// Check if this directory should be excluded
|
||||
|
||||
val shouldExclude =
|
||||
exclude.any { excluded ->
|
||||
// Check if the current path matches the excluded path
|
||||
// exactly
|
||||
excluded.path.volume == newPath.volume &&
|
||||
excluded.path.components == newPath.components
|
||||
}
|
||||
if (shouldExclude) {
|
||||
continue
|
||||
}
|
||||
|
||||
val subdir =
|
||||
query(
|
||||
rootUri = rootUri,
|
||||
@@ -152,7 +172,8 @@ private class DeviceFSImpl(
|
||||
path = newPath,
|
||||
modifiedMs = modifiedMs,
|
||||
parent = dir,
|
||||
fileTree = fileTree)
|
||||
fileTree = fileTree,
|
||||
exclude = exclude)
|
||||
childSubdirUris.add(subdir.uri.toString())
|
||||
emit(StreamedFile.More(subdir))
|
||||
} else {
|
||||
@@ -202,7 +223,8 @@ private class DeviceFSImpl(
|
||||
cached: CachedDirectory,
|
||||
parentDir: DeviceDirectory?,
|
||||
path: Path,
|
||||
fileTree: FileTree
|
||||
fileTree: FileTree,
|
||||
exclude: List<Location>
|
||||
): DeviceDirectory = coroutineScope {
|
||||
val dir =
|
||||
DeviceDirectoryImpl(
|
||||
@@ -215,18 +237,30 @@ private class DeviceFSImpl(
|
||||
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."
|
||||
cached.subdirUris
|
||||
.asFlow()
|
||||
.transform { subdirUriString ->
|
||||
val subdirUri = subdirUriString.toUri()
|
||||
val cachedSubdir =
|
||||
requireNotNull(fileTree.queryDirectory(subdirUri)) {
|
||||
"No cached subdir for $subdirUri, malformed cache! Rescan needed."
|
||||
}
|
||||
val subdirPath = dir.path.file(cachedSubdir.name)
|
||||
|
||||
val shouldExclude =
|
||||
exclude.any { excluded ->
|
||||
excluded.path.volume == subdirPath.volume &&
|
||||
excluded.path.components ==
|
||||
subdirPath.components
|
||||
}
|
||||
|
||||
if (shouldExclude) {
|
||||
return@transform
|
||||
}
|
||||
hydrateCached(
|
||||
cachedSubdir,
|
||||
dir,
|
||||
dir.path.file(cachedSubdir.name),
|
||||
fileTree)
|
||||
},
|
||||
|
||||
emit(hydrateCached(cachedSubdir, dir, subdirPath, fileTree, exclude))
|
||||
}
|
||||
.filterNotNull(),
|
||||
cached.fileUris.asFlow().map {
|
||||
val cachedFile = requireNotNull(fileTree.queryFile(it.toUri()))
|
||||
DeviceFile(
|
||||
|
||||
@@ -34,6 +34,7 @@ import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.merge
|
||||
import kotlinx.coroutines.flow.onCompletion
|
||||
import org.oxycblt.musikr.Interpretation
|
||||
import org.oxycblt.musikr.Query
|
||||
import org.oxycblt.musikr.Storage
|
||||
import org.oxycblt.musikr.cache.Cache
|
||||
import org.oxycblt.musikr.cache.CacheResult
|
||||
@@ -41,7 +42,7 @@ import org.oxycblt.musikr.cache.CachedSong
|
||||
import org.oxycblt.musikr.covers.Cover
|
||||
import org.oxycblt.musikr.covers.CoverResult
|
||||
import org.oxycblt.musikr.covers.Covers
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
import org.oxycblt.musikr.fs.device.DeviceFS
|
||||
import org.oxycblt.musikr.fs.device.FileTreeCache
|
||||
import org.oxycblt.musikr.fs.device.flatten
|
||||
@@ -49,12 +50,14 @@ import org.oxycblt.musikr.playlist.db.StoredPlaylists
|
||||
import org.oxycblt.musikr.playlist.m3u.M3U
|
||||
|
||||
internal interface ExploreStep {
|
||||
fun explore(locations: List<MusicLocation>): Flow<Explored>
|
||||
fun explore(query: Query): Flow<Explored>
|
||||
|
||||
companion object {
|
||||
fun from(context: Context, storage: Storage, interpretation: Interpretation): ExploreStep =
|
||||
ExploreStepImpl(
|
||||
DeviceFS.from(context, interpretation.withHidden),
|
||||
DeviceFS.from(
|
||||
context = context,
|
||||
withHidden = interpretation.withHidden),
|
||||
storage.cache,
|
||||
storage.covers,
|
||||
storage.fileTreeCache,
|
||||
@@ -70,12 +73,12 @@ private class ExploreStepImpl(
|
||||
private val storedPlaylists: StoredPlaylists
|
||||
) : ExploreStep {
|
||||
@OptIn(ExperimentalCoroutinesApi::class)
|
||||
override fun explore(locations: List<MusicLocation>): Flow<Explored> {
|
||||
override fun explore(query: Query): Flow<Explored> {
|
||||
val addingMs = System.currentTimeMillis()
|
||||
val fileTree = fileTreeCache.read()
|
||||
return merge(
|
||||
deviceFS
|
||||
.explore(locations.asFlow(), fileTree)
|
||||
.explore(query, fileTree)
|
||||
.flatMapMerge { it.flatten() }
|
||||
.onCompletion { fileTree.write() }
|
||||
.filter { it.mimeType.startsWith("audio/") || it.mimeType == M3U.MIME_TYPE }
|
||||
|
||||
@@ -49,7 +49,7 @@ The `PipelineItem.kt` defines the data types that flow through the pipeline:
|
||||
## Pipeline Flow
|
||||
|
||||
```
|
||||
MusicLocation → ExploreStep → ExtractStep → EvaluateStep → Library
|
||||
OpenedLocation → ExploreStep → ExtractStep → EvaluateStep → Library
|
||||
```
|
||||
|
||||
Data flows through the pipeline using Kotlin's Flow API, with extensive use of parallel processing and buffering to optimize performance.
|
||||
|
||||
@@ -22,11 +22,11 @@ import android.content.Context
|
||||
import android.database.ContentObserver
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
|
||||
internal class LocationObserver(
|
||||
private val context: Context,
|
||||
private val location: MusicLocation,
|
||||
private val location: OpenedLocation,
|
||||
private val listener: UpdateTracker.Callback
|
||||
) : ContentObserver(Handler(Looper.getMainLooper())), Runnable {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
|
||||
@@ -19,15 +19,15 @@
|
||||
package org.oxycblt.musikr.track
|
||||
|
||||
import android.content.Context
|
||||
import org.oxycblt.musikr.fs.MusicLocation
|
||||
import org.oxycblt.musikr.fs.OpenedLocation
|
||||
|
||||
interface UpdateTracker {
|
||||
fun track(locations: List<MusicLocation>)
|
||||
fun track(locations: List<OpenedLocation>)
|
||||
|
||||
fun release()
|
||||
|
||||
interface Callback {
|
||||
fun onUpdate(location: MusicLocation)
|
||||
fun onUpdate(location: OpenedLocation)
|
||||
}
|
||||
|
||||
companion object {
|
||||
@@ -42,7 +42,7 @@ private class UpdateTrackerImpl(
|
||||
) : UpdateTracker {
|
||||
private val observers = mutableListOf<LocationObserver>()
|
||||
|
||||
override fun track(locations: List<MusicLocation>) {
|
||||
override fun track(locations: List<OpenedLocation>) {
|
||||
release()
|
||||
observers.addAll(locations.map { LocationObserver(context, it, callback) })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user